diff --git a/AUTHORS.txt b/AUTHORS.txt new file mode 100644 index 000000000..38c5d242c --- /dev/null +++ b/AUTHORS.txt @@ -0,0 +1,29 @@ +# This file is an addendum to the Chromium AUTHORS file. +# Names should be added to this file like so: +# Name or Organization + +Marshall Greenblatt +Jamie Kirkpatrick +Johan Lindström +Igor Pavlov +Yanko Yankov +Emerick Rogul +Valve Corporation +Anthony Taranto +Joe Andrieu +Keith Poole +Aviv Rind +Michael Kaminski +ADInstruments Ltd. +Gus Verdun +Joinerysoft Ltd. +Johan Björk +Dmitry Azaraev +David Xue +Russell (Rusty) Richards +Brian Power +Corey Lucier +Mihai Tica +Czarek Tomczak +Felix Bruns +YuTeh Shen diff --git a/CHROMIUM_BUILD_COMPATIBILITY.txt b/CHROMIUM_BUILD_COMPATIBILITY.txt new file mode 100644 index 000000000..cc36e6b3a --- /dev/null +++ b/CHROMIUM_BUILD_COMPATIBILITY.txt @@ -0,0 +1,11 @@ +# The Chromium Embedded Framework (CEF) project is built on top of the Chromium +# project source tree. Chromium should be updated to the URL and revision listed +# below before building CEF. Chromium compatibility information for older CEF +# revisions is available by viewing this file's change history. +# +# Instructions for building CEF are available at: +# https://code.google.com/p/chromiumembedded/wiki/BranchesAndBuilding + +{ + 'chromium_checkout': 'refs/tags/41.0.2272.16', +} diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in new file mode 100644 index 000000000..ae88556e6 --- /dev/null +++ b/CMakeLists.txt.in @@ -0,0 +1,581 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +# OVERVIEW +# +# CMake is a cross-platform open-source build system that can generate project +# files in many different formats. It can be downloaded from +# http://www.cmake.org or installed via a platform package manager. +# +# CMake-generated project formats that have been tested with this CEF binary +# distribution include: +# +# Linux: Ninja, Unix Makefiles +# Mac OS X: Ninja, Xcode 5+ +# Windows: Ninja, Visual Studio 2010+ +# +# Ninja is a cross-platform open-source tool for running fast builds using +# pre-installed platform toolchains (GNU, clang, Xcode or MSVC). It can be +# downloaded from http://martine.github.io/ninja/ or installed via a platform +# package manager. +# +# CMAKE STRUCTURE +# +# This CEF binary distribution includes the following CMake files: +# +# CMakeLists.txt Bootstrap that sets up the CMake environment and +# loads the other CMake files. +# macros.cmake Helper macros for building a generic CEF-based +# application. +# libcef_dll/CMakeLists.txt Defines the libcef_dll_wrapper target. +# cefclient/CMakeLists.txt Defines the cefclient target. +# cefsimple/CMakeLists.txt Defines the cefsimple target. +# +# Existing CMake projects that use this binary distribution without changing the +# directory structure can include the existing "libcef_dll/CMakeLists.txt" file +# with minimal or no changes. +# +# BUILD REQUIREMENTS +# +# The below requirements must be met to build this CEF binary distribution. +# +# - CMake version 2.8.12.2 or newer. +# +# - Linux requirements: +# Currently supported distributions include Debian Wheezy, Ubuntu Precise, and +# related. Newer versions will likely also work but may not have been tested. +# Required packages include: +# build-essential +# libgtk2.0-dev (required by the cefclient target only) +# libgtkglext1-dev (required by the cefclient target only) +# +# - Mac OS X requirements: +# Xcode 5 or newer building on Mac OS X 10.7 (Lion) or newer. The Xcode +# command-line tools must also be installed. +# +# - Windows requirements: +# Visual Studio 2010 or newer building on Windows XP SP3 or newer. 64-bit +# version of Windows 7 or newer recommended. +# +# BUILD EXAMPLES +# +# The below commands will generate project files and create a Debug build of all +# CEF targets using CMake and the platform toolchain. +# +# Start by creating and entering the CMake build output directory: +# > cd path/to/cef_binary_* +# > mkdir build && cd build +# +# To perform a Linux build using a 32-bit CEF binary distribution on a 32-bit +# Linux platform or a 64-bit CEF binary distribution on a 64-bit Linux platform: +# Using Unix Makefiles: +# > cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug .. +# > make -j4 cefclient cefsimple +# +# Using Ninja: +# > cmake -G "Ninja" -DCMAKE_BUILD_TYPE=Debug .. +# > ninja cefclient cefsimple +# +# To perform a Mac OS X build using a 32-bit CEF binary distribution: +# Using the Xcode IDE: +# > cmake -G "Xcode" -DPROJECT_ARCH="i386" .. +# Open build\cef.xcodeproj in Xcode and select Product > Build. +# +# Using Ninja: +# > cmake -G "Ninja" -DPROJECT_ARCH="i386" -DCMAKE_BUILD_TYPE=Debug .. +# > ninja cefclient cefsimple +# +# To perform a Mac OS X build using a 64-bit CEF binary distribution: +# Using the Xcode IDE: +# > cmake -G "Xcode" -DPROJECT_ARCH="x86_64" .. +# Open build\cef.xcodeproj in Xcode and select Product > Build. +# +# Using Ninja: +# > cmake -G "Ninja" -DPROJECT_ARCH="x86_64" -DCMAKE_BUILD_TYPE=Debug .. +# > ninja cefclient cefsimple +# +# To perform a Windows build using a 32-bit CEF binary distribution: +# Using the Visual Studio 2013 IDE: +# > cmake -G "Visual Studio 12" .. +# Open build\cef.sln in Visual Studio and select Build > Build Solution. +# +# Using Ninja with Visual Studio 2013 command-line tools: +# (this path may be different depending on your Visual Studio installation) +# > "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\vcvars32.bat" +# > cmake -G "Ninja" -DCMAKE_BUILD_TYPE=Debug .. +# > ninja cefclient cefsimple +# +# To perform a Windows build using a 64-bit CEF binary distribution: +# Using the Visual Studio 2013 IDE: +# > cmake -G "Visual Studio 12 Win64" .. +# Open build\cef.sln in Visual Studio and select Build > Build Solution. +# +# Using Ninja with Visual Studio 2013 command-line tools: +# (this path may be different depending on your Visual Studio installation) +# > "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\amd64\vcvars64.bat" +# > cmake -G "Ninja" -DCMAKE_BUILD_TYPE=Debug .. +# > ninja cefclient cefsimple + +# +# Shared configuration. +# + +cmake_minimum_required(VERSION 2.8.12.2) + +# Only generate Debug and Release configuration types. +set(CMAKE_CONFIGURATION_TYPES Debug Release) + +# Project name. +project(cef) + +# Use folders in the resulting project files. +set_property(GLOBAL PROPERTY OS_FOLDERS ON) + +# Determine the platform. +if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin") + set(OS_MACOSX 1) + set(OS_POSIX 1) +elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") + set(OS_LINUX 1) + set(OS_POSIX 1) +elseif("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") + set(OS_WINDOWS 1) +endif() + +# Determine the project architecture. +if(NOT DEFINED PROJECT_ARCH) + if(CMAKE_SIZEOF_VOID_P MATCHES 8) + set(PROJECT_ARCH "x86_64") + else() + set(PROJECT_ARCH "x86") + endif() + + if(OS_MACOSX) + # PROJECT_ARCH should be specified on Mac OS X. + message(WARNING "No PROJECT_ARCH value specified, using ${PROJECT_ARCH}") + endif() +endif() + +if(NOT CMAKE_BUILD_TYPE AND + (${CMAKE_GENERATOR} STREQUAL "Ninja" OR ${CMAKE_GENERATOR} STREQUAL "Unix Makefiles")) + # CMAKE_BUILD_TYPE should be specified when using Ninja or Unix Makefiles. + set(CMAKE_BUILD_TYPE Release) + message(WARNING "No CMAKE_BUILD_TYPE value selected, using ${CMAKE_BUILD_TYPE}") +endif() + +# Include cmake macros. +set(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}") +include("macros") + +# Source include directory. +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) + +# Allow C++ programs to use stdint.h macros specified in the C99 standard that +# aren't in the C++ standard (e.g. UINT8_MAX, INT64_MIN, etc). +add_definitions(-D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS) + + +# +# Linux configuration. +# + +if(OS_LINUX) + # Platform-specific compiler/linker flags. + set(CEF_LIBTYPE SHARED) + # -fno-strict-aliasing = Avoid assumptions regarding non-aliasing of objects of different types + # -fPIC = Generate position-independent code for shared libraries + # -fstack-protector = Protect some vulnerable functions from stack-smashing (security feature) + # -funwind-tables = Support stack unwinding for backtrace() + # -fvisibility=hidden = Give hidden visibility to declarations that are not explicitly marked as visible + # --param=ssp-buffer-size=4 = Set the minimum buffer size protected by SSP (security feature, related to stack-protector) + # -pipe = Use pipes rather than temporary files for communication between build stages + # -pthread = Use the pthread library + # -Wall = Enable all warnings + # -Werror = Treat warnings as errors + # -Wno-missing-field-initializers = Don't warn about missing field initializers + # -Wno-unused-parameter = Don't warn about unused parameters + set(CEF_COMPILER_FLAGS "-fno-strict-aliasing -fPIC -fstack-protector -funwind-tables -fvisibility=hidden --param=ssp-buffer-size=4 -pipe -pthread -Wall -Werror -Wno-missing-field-initializers -Wno-unused-parameter") + # -std=c99 = Use the C99 language standard + set(CEF_C_COMPILER_FLAGS "-std=c99") + # -fno-exceptions = Disable exceptions + # -fno-rtti = Disable real-time type information + # -fno-threadsafe-statics = Don't generate thread-safe statics + # -fvisibility-inlines-hidden = Give hidden visibility to inlined class member functions + # -std=gnu++11 = Use the C++11 language standard including GNU extensions + # -Wsign-compare = Warn about mixed signed/unsigned type comparisons + set(CEF_CXX_COMPILER_FLAGS "-fno-exceptions -fno-rtti -fno-threadsafe-statics -fvisibility-inlines-hidden -std=gnu++11 -Wsign-compare") + # -O0 = Disable optimizations + # -g = Generate debug information + set(CEF_COMPILER_FLAGS_DEBUG "-O0 -g") + # -O2 = Optimize for maximum speed + # -fdata-sections = Enable linker optimizations to improve locality of reference for data sections + # -ffunction-sections = Enable linker optimizations to improve locality of reference for function sections + # -fno-ident = Ignore the #ident directive + # -DNDEBUG = Not a debug build + # -U_FORTIFY_SOURCE = Undefine _FORTIFY_SOURCE in case it was previously defined + # -D_FORTIFY_SOURCE=2 = Add memory and string function protection (security feature, related to stack-protector) + set(CEF_COMPILER_FLAGS_RELEASE "-O2 -fdata-sections -ffunction-sections -fno-ident -DNDEBUG -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2") + # -Wl,--disable-new-dtags = Don't generate new-style dynamic tags in ELF + # -Wl,--fatal-warnings = Treat warnings as errors + # -Wl,-rpath,. = Set rpath so that libraries can be placed next to the executable + # -Wl,-z,noexecstack = Mark the stack as non-executable (security feature) + # -Wl,-z,now = Resolve symbols on program start instead of on first use (security feature) + # -Wl,-z,relro = Mark relocation sections as read-only (security feature) + set(CEF_LINKER_FLAGS "-fPIC -pthread -Wl,--disable-new-dtags -Wl,--fatal-warnings -Wl,-rpath,. -Wl,-z,noexecstack -Wl,-z,now -Wl,-z,relro") + # -Wl,-O1 = Enable linker optimizations + # -Wl,--as-needed = Only link libraries that export symbols used by the binary + # -Wl,--gc-sections = Remove unused code resulting from -fdata-sections and -function-sections + set(CEF_LINKER_FLAGS_RELEASE "-Wl,-O1 -Wl,--as-needed -Wl,--gc-sections") + + include(CheckCCompilerFlag) + include(CheckCXXCompilerFlag) + + # -Wno-unused-local-typedefs = Don't warn about unused local typedefs + CHECK_C_COMPILER_FLAG(-Wno-unused-local-typedefs COMPILER_SUPPORTS_NO_UNUSED_LOCAL_TYPEDEFS) + if(COMPILER_SUPPORTS_NO_UNUSED_LOCAL_TYPEDEFS) + set(CEF_C_COMPILER_FLAGS "${CEF_C_COMPILER_FLAGS} -Wno-unused-local-typedefs") + endif() + + # -Wno-literal-suffix = Don't warn about invalid suffixes on literals + CHECK_CXX_COMPILER_FLAG(-Wno-literal-suffix COMPILER_SUPPORTS_NO_LITERAL_SUFFIX) + if(COMPILER_SUPPORTS_NO_LITERAL_SUFFIX) + set(CEF_CXX_COMPILER_FLAGS "${CEF_CXX_COMPILER_FLAGS} -Wno-literal-suffix") + endif() + + # -Wno-narrowing = Don't warn about type narrowing + CHECK_CXX_COMPILER_FLAG(-Wno-narrowing COMPILER_SUPPORTS_NO_NARROWING) + if(COMPILER_SUPPORTS_NO_NARROWING) + set(CEF_CXX_COMPILER_FLAGS "${CEF_CXX_COMPILER_FLAGS} -Wno-narrowing") + endif() + + if(PROJECT_ARCH STREQUAL "x86_64") + # 64-bit architecture. + set(CEF_COMPILER_FLAGS "${CEF_COMPILER_FLAGS} -m64 -march=x86-64") + set(CEF_LINKER_FLAGS "${CEF_LINKER_FLAGS} -m64") + elseif(PROJECT_ARCH STREQUAL "x86") + # 32-bit architecture. + set(CEF_COMPILER_FLAGS "${CEF_COMPILER_FLAGS} -msse2 -mfpmath=sse -mmmx -m32") + set(CEF_LINKER_FLAGS "${CEF_LINKER_FLAGS} -m32") + endif() + + # Allow the Large File Support (LFS) interface to replace the old interface. + add_definitions(-D_FILE_OFFSET_BITS=64) + + # Standard libraries. + set(CEF_STANDARD_LIBS "X11") + + # CEF directory paths. + set(CEF_RESOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Resources") + set(CEF_BINARY_DIR "${CMAKE_CURRENT_SOURCE_DIR}/${CMAKE_BUILD_TYPE}") + set(CEF_BINARY_DIR_DEBUG "${CMAKE_CURRENT_SOURCE_DIR}/Debug") + set(CEF_BINARY_DIR_RELEASE "${CMAKE_CURRENT_SOURCE_DIR}/Release") + + # CEF library paths. + set(CEF_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/libcef.so") + set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.so") + + # List of CEF binary files. + set(CEF_BINARY_FILES + chrome-sandbox + libffmpegsumo.so + libcef.so + libpdf.so + ) + + # List of CEF resource files. + set(CEF_RESOURCE_FILES + cef.pak + cef_100_percent.pak + cef_200_percent.pak + devtools_resources.pak + icudtl.dat + locales + natives_blob.bin + snapshot_blob.bin + ) +endif() + + +# +# Mac OS X configuration. +# + +if(OS_MACOSX) + # Platform-specific compiler/linker flags. + # See also SET_XCODE_TARGET_PROPERTIES in macros.cmake. + set(CEF_LIBTYPE SHARED) + # -fno-strict-aliasing = Avoid assumptions regarding non-aliasing of objects of different types + # -fstack-protector = Protect some vulnerable functions from stack-smashing (security feature) + # -funwind-tables = Support stack unwinding for backtrace() + # -fvisibility=hidden = Give hidden visibility to declarations that are not explicitly marked as visible + # -Wall = Enable all warnings + # -Wendif-labels = Warn whenever an #else or an #endif is followed by text + # -Werror = Treat warnings as errors + # -Wextra = Enable additional warnings + # -Wnewline-eof = Warn about no newline at end of file + # -Wno-missing-field-initializers = Don't warn about missing field initializers + # -Wno-unused-parameter = Don't warn about unused parameters + set(CEF_COMPILER_FLAGS "-fno-strict-aliasing -fstack-protector -funwind-tables -fvisibility=hidden -Wall -Wendif-labels -Werror -Wextra -Wnewline-eof -Wno-missing-field-initializers -Wno-unused-parameter") + # -std=c99 = Use the C99 language standard + set(CEF_C_COMPILER_FLAGS "-std=c99") + # -fno-exceptions = Disable exceptions + # -fno-rtti = Disable real-time type information + # -fno-threadsafe-statics = Don't generate thread-safe statics + # -fobjc-call-cxx-cdtors = Call the constructor/destructor of C++ instance variables in ObjC objects + # -fvisibility-inlines-hidden = Give hidden visibility to inlined class member functions + # -std=gnu++11 = Use the C++11 language standard including GNU extensions + # -Wno-narrowing = Don't warn about type narrowing + # -Wsign-compare = Warn about mixed signed/unsigned type comparisons + set(CEF_CXX_COMPILER_FLAGS "-fno-exceptions -fno-rtti -fno-threadsafe-statics -fobjc-call-cxx-cdtors -fvisibility-inlines-hidden -std=gnu++11 -Wno-narrowing -Wsign-compare") + # -O0 = Disable optimizations + # -g = Generate debug information + set(CEF_COMPILER_FLAGS_DEBUG "-O0 -g") + # -O3 = Optimize for maximum speed plus a few extras + set(CEF_COMPILER_FLAGS_RELEASE "-O3") + # -Wl,-search_paths_first = Search for static or shared library versions in the same pass + # -Wl,-ObjC = Support creation of creation of ObjC static libraries + # -Wl,-pie = Generate position-independent code suitable for executables only + set(CEF_LINKER_FLAGS "-Wl,-search_paths_first -Wl,-ObjC -Wl,-pie") + # -Wl,-dead_strip = Strip dead code + set(CEF_LINKER_FLAGS_RELEASE "-Wl,-dead_strip") + + # Standard libraries. + set(CEF_STANDARD_LIBS "-lpthread" "-framework Cocoa" "-framework AppKit") + + # Find the newest available base SDK. + execute_process(COMMAND xcode-select --print-path OUTPUT_VARIABLE XCODE_PATH OUTPUT_STRIP_TRAILING_WHITESPACE) + foreach(OS_VERSION 10.10 10.9 10.8 10.7) + set(SDK "${XCODE_PATH}/Platforms/MacOSX.platform/Developer/SDKs/MacOSX${OS_VERSION}.sdk") + if(NOT "${CMAKE_OSX_SYSROOT}" AND EXISTS "${SDK}" AND IS_DIRECTORY "${SDK}") + set(CMAKE_OSX_SYSROOT ${SDK}) + endif() + endforeach() + + # Target SDK. + set(CEF_TARGET_SDK "10.6") + set(CEF_COMPILER_FLAGS "${CEF_COMPILER_FLAGS} -mmacosx-version-min=${CEF_TARGET_SDK}") + set(CMAKE_OSX_DEPLOYMENT_TARGET ${CEF_TARGET_SDK}) + + # Target architecture. + if(PROJECT_ARCH STREQUAL "x86_64") + set(CMAKE_OSX_ARCHITECTURES "x86_64") + else() + set(CMAKE_OSX_ARCHITECTURES "i386") + endif() + + # CEF directory paths. + set(CEF_BINARY_DIR "${CMAKE_CURRENT_SOURCE_DIR}/$") + set(CEF_BINARY_DIR_DEBUG "${CMAKE_CURRENT_SOURCE_DIR}/Debug") + set(CEF_BINARY_DIR_RELEASE "${CMAKE_CURRENT_SOURCE_DIR}/Release") + + # CEF library paths. + set(CEF_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/Chromium Embedded Framework.framework/Chromium Embedded Framework") + set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/Chromium Embedded Framework.framework/Chromium Embedded Framework") +endif() + + +# +# Windows configuration. +# + +if(OS_WINDOWS) + # Platform-specific compiler/linker flags. + set(CEF_LIBTYPE STATIC) + # /MP = Multiprocess compilation + # /Gy = Enable function-level linking + # /GR- = Disable run-time type information + # /Zi = Enable program database + # /W4 = Warning level 4 + # /WX = Treat warnings as errors + # /wd"4100" = Ignore "unreferenced formal parameter" warning + # /wd"4127" = Ignore "conditional expression is constant" warning + # /wd"4244" = Ignore "conversion possible loss of data" warning + # /wd"4512" = Ignore "assignment operator could not be generated" warning + # /wd"4701" = Ignore "potentially uninitialized local variable" warning + # /wd"4702" = Ignore "unreachable code" warning + # /wd"4996" = Ignore "function or variable may be unsafe" warning + set(CEF_COMPILER_FLAGS "/MP /Gy /GR- /Zi /W4 /WX /wd\"4100\" /wd\"4127\" /wd\"4244\" /wd\"4512\" /wd\"4701\" /wd\"4702\" /wd\"4996\"") + # /MTd = Multithreaded debug runtime + # /Od = Disable optimizations + # /RTC1 = Enable basic run-time checks + set(CEF_COMPILER_FLAGS_DEBUG "/MTd /RTC1 /Od") + # /MT = Multithreaded release runtime + # /O2 = Optimize for maximum speed + # /Ob2 = Inline any suitable function + # /GF = Enable string pooling + # /D NDEBUG /D _NDEBUG = Not a debug build + set(CEF_COMPILER_FLAGS_RELEASE "/MT /O2 /Ob2 /GF /D NDEBUG /D _NDEBUG") + # /DEBUG = Generate debug information + set(CEF_LINKER_FLAGS_DEBUG "/DEBUG") + # /MANIFEST:NO = No default manifest (see ADD_WINDOWS_MANIFEST macro usage) + set(CEF_EXE_LINKER_FLAGS "/MANIFEST:NO") + + # Standard definitions + # -DWIN32 -D_WIN32 -D_WINDOWS = Windows platform + # -DUNICODE -D_UNICODE = Unicode build + # -DWINVER=0x0602 -D_WIN32_WINNT=0x602 = Targeting Windows 8 + # -DNOMINMAX = Use the standard's templated min/max + # -DWIN32_LEAN_AND_MEAN = Exclude less common API declarations + # -D_HAS_EXCEPTIONS=0 = Disable exceptions + add_definitions(-DWIN32 -D_WIN32 -D_WINDOWS -DUNICODE -D_UNICODE -DWINVER=0x0602 + -D_WIN32_WINNT=0x602 -DNOMINMAX -DWIN32_LEAN_AND_MEAN -D_HAS_EXCEPTIONS=0) + + # Standard libraries. + set(CEF_STANDARD_LIBS "comctl32.lib" "rpcrt4.lib" "shlwapi.lib") + + # CEF directory paths. + set(CEF_RESOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Resources") + set(CEF_BINARY_DIR "${CMAKE_CURRENT_SOURCE_DIR}/$") + set(CEF_BINARY_DIR_DEBUG "${CMAKE_CURRENT_SOURCE_DIR}/Debug") + set(CEF_BINARY_DIR_RELEASE "${CMAKE_CURRENT_SOURCE_DIR}/Release") + + # CEF library paths. + set(CEF_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/libcef.lib") + set(CEF_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/libcef.lib") + + # List of CEF binary files. + set(CEF_BINARY_FILES + d3dcompiler_43.dll + d3dcompiler_47.dll + ffmpegsumo.dll + libcef.dll + libEGL.dll + libGLESv2.dll + pdf.dll + ) + if(PROJECT_ARCH STREQUAL "x86") + # Only used on 32-bit platforms. + set(CEF_BINARY_FILES + ${CEF_BINARY_FILES} + wow_helper.exe + ) + endif() + + # List of CEF resource files. + set(CEF_RESOURCE_FILES + cef.pak + cef_100_percent.pak + cef_200_percent.pak + devtools_resources.pak + icudtl.dat + locales + ) + + # Configure use of the sandbox. + option(USE_SANDBOX "Enable or disable use of the sandbox." ON) + if(USE_SANDBOX AND NOT MSVC_VERSION EQUAL 1800) + # The cef_sandbox.lib static library is currently built with VS2013. It will + # not link successfully with other VS versions. + set(USE_SANDBOX OFF) + endif() + + if(USE_SANDBOX) + # Definition required by cef_sandbox.lib. + add_definitions(-DPSAPI_VERSION=1) + # Definition used by apps to test if the sandbox is enabled. + add_definitions(-DCEF_USE_SANDBOX) + + # Libraries required by cef_sandbox.lib. + set(CEF_SANDBOX_STANDARD_LIBS "dbghelp.lib" "psapi.lib") + + # CEF sandbox library paths. + set(CEF_SANDBOX_LIB_DEBUG "${CEF_BINARY_DIR_DEBUG}/cef_sandbox.lib") + set(CEF_SANDBOX_LIB_RELEASE "${CEF_BINARY_DIR_RELEASE}/cef_sandbox.lib") + endif() + + # Configure use of ATL. + option(USE_ATL "Enable or disable use of ATL." ON) + if(USE_ATL) + # Determine if the Visual Studio install supports ATL. + get_filename_component(VC_BIN_DIR ${CMAKE_CXX_COMPILER} DIRECTORY) + get_filename_component(VC_DIR ${VC_BIN_DIR} DIRECTORY) + if(NOT IS_DIRECTORY "${VC_DIR}/atlmfc") + set(USE_ATL OFF) + endif() + endif() + + if(USE_ATL) + # Definition used by apps to test if ATL support is enabled. + add_definitions(-DCEF_USE_ATL) + endif() +endif() + + +# +# Post-configuration actions. +# + +# Merge compiler/linker flags. +set(CMAKE_C_FLAGS "${CEF_COMPILER_FLAGS} ${CEF_C_COMPILER_FLAGS}") +set(CMAKE_C_FLAGS_DEBUG "${CEF_COMPILER_FLAGS_DEBUG} ${CEF_C_COMPILER_FLAGS_DEBUG}") +set(CMAKE_C_FLAGS_RELEASE "${CEF_COMPILER_FLAGS_RELEASE} ${CEF_C_COMPILER_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS "${CEF_COMPILER_FLAGS} ${CEF_CXX_COMPILER_FLAGS}") +set(CMAKE_CXX_FLAGS_DEBUG "${CEF_COMPILER_FLAGS_DEBUG} ${CEF_CXX_COMPILER_FLAGS_DEBUG}") +set(CMAKE_CXX_FLAGS_RELEASE "${CEF_COMPILER_FLAGS_RELEASE} ${CEF_CXX_COMPILER_FLAGS_RELEASE}") +set(CMAKE_EXE_LINKER_FLAGS "${CEF_LINKER_FLAGS} ${CEF_EXE_LINKER_FLAGS}") +set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CEF_LINKER_FLAGS_DEBUG} ${CEF_EXE_LINKER_FLAGS_DEBUG}") +set(CMAKE_EXE_LINKER_FLAGS_RELEASE "${CEF_LINKER_FLAGS_RELEASE} ${CEF_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS "${CEF_LINKER_FLAGS} ${CEF_SHARED_LINKER_FLAGS}") +set(CMAKE_SHARED_LINKER_FLAGS_DEBUG "${CEF_LINKER_FLAGS_DEBUG} ${CEF_SHARED_LINKER_FLAGS_DEBUG}") +set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CEF_LINKER_FLAGS_RELEASE} ${CEF_SHARED_LINKER_FLAGS_RELEASE}") + + +# +# Include target subdirectories. +# + +add_subdirectory(libcef_dll) +add_subdirectory(cefclient) +add_subdirectory(cefsimple) + + +# +# Display configuration settings. +# + +message(STATUS "*** CONFIGURATION SETTINGS ***") +message(STATUS "Generator: ${CMAKE_GENERATOR}") +message(STATUS "Platform: ${CMAKE_SYSTEM_NAME}") +message(STATUS "Project architecture: ${PROJECT_ARCH}") + +if(${CMAKE_GENERATOR} STREQUAL "Ninja" OR ${CMAKE_GENERATOR} STREQUAL "Unix Makefiles") + message(STATUS "Build type: ${CMAKE_BUILD_TYPE}") +endif() + +if(OS_MACOSX) + message(STATUS "Base SDK: ${CMAKE_OSX_SYSROOT}") + message(STATUS "Target SDK: ${CEF_TARGET_SDK}") +endif() + +if(OS_WINDOWS) + message(STATUS "CEF Windows sandbox: ${USE_SANDBOX}") + message(STATUS "Visual Studio ATL support: ${USE_ATL}") +endif() + +set(LIBRARIES ${CEF_STANDARD_LIBS}) +if(OS_WINDOWS AND USE_SANDBOX) + set(LIBRARIES ${LIBRARIES} ${CEF_SANDBOX_STANDARD_LIBS}) +endif() +message(STATUS "Standard libraries: ${LIBRARIES}") + +get_directory_property(DEFINITIONS COMPILE_DEFINITIONS) +message(STATUS "Compiler definitions: ${DEFINITIONS}") + +message(STATUS "C_FLAGS: ${CMAKE_C_FLAGS}") +message(STATUS "C_FLAGS_DEBUG: ${CMAKE_C_FLAGS_DEBUG}") +message(STATUS "C_FLAGS_RELEASE: ${CMAKE_C_FLAGS_RELEASE}") +message(STATUS "CXX_FLAGS: ${CMAKE_CXX_FLAGS}") +message(STATUS "CXX_FLAGS_DEBUG: ${CMAKE_CXX_FLAGS_DEBUG}") +message(STATUS "CXX_FLAGS_RELEASE: ${CMAKE_CXX_FLAGS_RELEASE}") +message(STATUS "EXE_LINKER_FLAGS: ${CMAKE_EXE_LINKER_FLAGS}") +message(STATUS "EXE_LINKER_FLAGS_DEBUG: ${CMAKE_EXE_LINKER_FLAGS_DEBUG}") +message(STATUS "EXE_LINKER_FLAGS_RELEASE: ${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +message(STATUS "SHARED_LINKER_FLAGS: ${CMAKE_SHARED_LINKER_FLAGS}") +message(STATUS "SHARED_LINKER_FLAGS_DEBUG: ${CMAKE_SHARED_LINKER_FLAGS_DEBUG}") +message(STATUS "SHARED_LINKER_FLAGS_RELEASE: ${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") + +if(OS_LINUX OR OS_WINDOWS) + message(STATUS "CEF Binary files: ${CEF_BINARY_FILES}") + message(STATUS "CEF Resource files: ${CEF_RESOURCE_FILES}") +endif() diff --git a/DEPS b/DEPS new file mode 100644 index 000000000..0a7dc22e3 --- /dev/null +++ b/DEPS @@ -0,0 +1,7 @@ +hooks = [ + { + # A change to a .gyp, .gypi, or to GYP itself should run the generator. + "pattern": ".", + "action": ["python", "src/cef/tools/gclient_hook.py"], + }, +] diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 000000000..b69b14293 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,29 @@ +// Copyright (c) 2008-2014 Marshall A. Greenblatt. Portions Copyright (c) +// 2006-2009 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. diff --git a/VERSION b/VERSION new file mode 100644 index 000000000..2ecb9806b --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +CEF_MAJOR=3 diff --git a/cef.gyp b/cef.gyp new file mode 100644 index 000000000..6c450d3a8 --- /dev/null +++ b/cef.gyp @@ -0,0 +1,1748 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +{ + 'variables': { + 'pkg-config': 'pkg-config', + 'chromium_code': 1, + 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/cef', + 'about_credits_file': '<(SHARED_INTERMEDIATE_DIR)/about_credits.html', + 'framework_name': 'Chromium Embedded Framework', + 'revision': '=46', { + 'target_defaults': { + # Disable warnings about c++0x compatibility, as some names (such + # as nullptr) conflict with upcoming c++0x types. + 'cflags_cc': ['-Wno-c++0x-compat'], + }, + }], + ['OS=="mac"', { + 'targets': [ + { + 'target_name': 'cef_framework', + 'type': 'shared_library', + 'product_name': '<(framework_name)', + 'mac_bundle': 1, + 'mac_bundle_resources': [ + '<(PRODUCT_DIR)/cef.pak', + '<(PRODUCT_DIR)/cef_100_percent.pak', + '<(PRODUCT_DIR)/cef_200_percent.pak', + '<(PRODUCT_DIR)/devtools_resources.pak', + '<(PRODUCT_DIR)/icudtl.dat', + '<(PRODUCT_DIR)/natives_blob.bin', + '<(PRODUCT_DIR)/snapshot_blob.bin', + 'libcef/resources/framework-Info.plist', + ], + 'mac_bundle_resources!': [ + 'libcef/resources/framework-Info.plist', + ], + 'xcode_settings': { + # Default path that will be changed by install_name_tool in dependent targets. + 'INSTALL_PATH': '@executable_path', + 'DYLIB_INSTALL_NAME_BASE': '@executable_path', + 'LD_DYLIB_INSTALL_NAME': '@executable_path/<(framework_name)', + + # The libcef_static target contains ObjC categories. Passing the -ObjC flag + # is necessary to properly load them and avoid a "selector not recognized" + # runtime error. See http://developer.apple.com/library/mac/#qa/qa1490/_index.html + # for more information. + 'OTHER_LDFLAGS': ['-Wl,-ObjC'], + + 'DYLIB_COMPATIBILITY_VERSION': '<(version_mac_dylib)', + 'DYLIB_CURRENT_VERSION': '<(version_mac_dylib)', + 'INFOPLIST_FILE': 'libcef/resources/framework-Info.plist', + }, + 'dependencies': [ + 'cef_pak', + 'libcef_static', + ], + 'defines': [ + 'BUILDING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'sources': [ + '<@(includes_common)', + '<@(includes_capi)', + '<@(libcef_sources_common)', + ], + 'postbuilds': [ + { + # Modify the Info.plist as needed. The script explains why + # this is needed. This is also done in the chrome target. + # The framework needs the Breakpad keys if this feature is + # enabled. It does not need the Keystone keys; these always + # come from the outer application bundle. The framework + # doesn't currently use the SCM keys for anything, + # but this seems like a really good place to store them. + 'postbuild_name': 'Tweak Info.plist', + 'action': ['../build/mac/tweak_info_plist.py', + '--breakpad=1', + '--keystone=0', + '--scm=1', + '--version=<(chrome_version)', + '--branding=<(framework_name)'], + }, + ], + 'copies': [ + { + # Copy binaries for HTML5 audio/video and PDF support. + 'destination': '<(PRODUCT_DIR)/$(CONTENTS_FOLDER_PATH)/Libraries', + 'files': [ + '<(PRODUCT_DIR)/ffmpegsumo.so', + '<(PRODUCT_DIR)/PDF.plugin', + ], + }, + { + # Copy binaries for breakpad support. + 'destination': '<(PRODUCT_DIR)/$(CONTENTS_FOLDER_PATH)/Resources', + 'files': [ + '<(PRODUCT_DIR)/crash_inspector', + '<(PRODUCT_DIR)/crash_report_sender.app', + ], + }, + ], + }, # target cef_framework + { + 'target_name': 'cefclient_helper_app', + 'type': 'executable', + 'variables': { 'enable_wexit_time_destructors': 1, }, + 'product_name': 'cefclient Helper', + 'mac_bundle': 1, + 'dependencies': [ + 'cef_framework', + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + # cefclient includes are relative to the tests directory to make + # creation of binary releases easier. + 'tests' + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + ], + }, + 'sources': [ + '<@(cefclient_sources_mac_helper)', + ], + # TODO(mark): Come up with a fancier way to do this. It should only + # be necessary to list helper-Info.plist once, not the three times it + # is listed here. + 'mac_bundle_resources!': [ + 'tests/cefclient/mac/helper-Info.plist', + ], + # TODO(mark): For now, don't put any resources into this app. Its + # resources directory will be a symbolic link to the browser app's + # resources directory. + 'mac_bundle_resources/': [ + ['exclude', '.*'], + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'tests/cefclient/mac/helper-Info.plist', + # Necessary to avoid an "install_name_tool: changing install names or + # rpaths can't be redone" error. + 'OTHER_LDFLAGS': ['-Wl,-headerpad_max_install_names'], + }, + 'postbuilds': [ + { + # The framework defines its load-time path + # (DYLIB_INSTALL_NAME_BASE) relative to the main executable + # (chrome). A different relative path needs to be used in + # cefclient_helper_app. + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../../../../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + { + # Modify the Info.plist as needed. The script explains why this + # is needed. This is also done in the chrome and chrome_dll + # targets. In this case, --breakpad=0, --keystone=0, and --scm=0 + # are used because Breakpad, Keystone, and SCM keys are + # never placed into the helper. + 'postbuild_name': 'Tweak Info.plist', + 'action': ['../build/mac/tweak_info_plist.py', + '--breakpad=0', + '--keystone=0', + '--scm=0'], + }, + ], + }, # target cefclient_helper_app + { + 'target_name': 'cefsimple_helper_app', + 'type': 'executable', + 'variables': { 'enable_wexit_time_destructors': 1, }, + 'product_name': 'cefsimple Helper', + 'mac_bundle': 1, + 'dependencies': [ + 'cef_framework', + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + # cefsimple includes are relative to the tests directory to make + # creation of binary releases easier. + 'tests' + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + ], + }, + 'sources': [ + '<@(cefsimple_sources_mac_helper)', + ], + # TODO(mark): Come up with a fancier way to do this. It should only + # be necessary to list helper-Info.plist once, not the three times it + # is listed here. + 'mac_bundle_resources!': [ + 'tests/cefsimple/mac/helper-Info.plist', + ], + # TODO(mark): For now, don't put any resources into this app. Its + # resources directory will be a symbolic link to the browser app's + # resources directory. + 'mac_bundle_resources/': [ + ['exclude', '.*'], + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'tests/cefsimple/mac/helper-Info.plist', + # Necessary to avoid an "install_name_tool: changing install names or + # rpaths can't be redone" error. + 'OTHER_LDFLAGS': ['-Wl,-headerpad_max_install_names'], + }, + 'postbuilds': [ + { + # The framework defines its load-time path + # (DYLIB_INSTALL_NAME_BASE) relative to the main executable + # (chrome). A different relative path needs to be used in + # cefsimple_helper_app. + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../../../../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + { + # Modify the Info.plist as needed. The script explains why this + # is needed. This is also done in the chrome and chrome_dll + # targets. In this case, --breakpad=0, --keystone=0, and --scm=0 + # are used because Breakpad, Keystone, and SCM keys are + # never placed into the helper. + 'postbuild_name': 'Tweak Info.plist', + 'action': ['../build/mac/tweak_info_plist.py', + '--breakpad=0', + '--keystone=0', + '--scm=0'], + }, + ], + }, # target cefsimple_helper_app + { + 'target_name': 'cef_unittests_helper_app', + 'type': 'executable', + 'product_name': 'cef_unittests Helper', + 'mac_bundle': 1, + 'dependencies': [ + '<(DEPTH)/base/base.gyp:base', + '<(DEPTH)/base/base.gyp:base_i18n', + '<(DEPTH)/base/base.gyp:test_support_base', + '<(DEPTH)/testing/gtest.gyp:gtest', + '<(DEPTH)/third_party/icu/icu.gyp:icui18n', + '<(DEPTH)/third_party/icu/icu.gyp:icuuc', + 'cef_framework', + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'sources': [ + 'tests/cefclient/client_app.cc', + 'tests/cefclient/client_app.h', + 'tests/cefclient/client_switches.cc', + 'tests/cefclient/client_switches.h', + 'tests/cefclient/process_helper_mac.cc', + 'tests/unittests/client_app_delegates.cc', + 'tests/unittests/cookie_unittest.cc', + 'tests/unittests/dom_unittest.cc', + 'tests/unittests/frame_unittest.cc', + 'tests/unittests/message_router_unittest.cc', + 'tests/unittests/navigation_unittest.cc', + 'tests/unittests/process_message_unittest.cc', + 'tests/unittests/request_handler_unittest.cc', + 'tests/unittests/request_unittest.cc', + 'tests/unittests/routing_test_handler.cc', + 'tests/unittests/routing_test_handler.h', + 'tests/unittests/scheme_handler_unittest.cc', + 'tests/unittests/urlrequest_unittest.cc', + 'tests/unittests/test_handler.cc', + 'tests/unittests/test_handler.h', + 'tests/unittests/test_suite.cc', + 'tests/unittests/test_suite.h', + 'tests/unittests/test_util.cc', + 'tests/unittests/test_util.h', + 'tests/unittests/tracing_unittest.cc', + 'tests/unittests/v8_unittest.cc', + ], + # TODO(mark): Come up with a fancier way to do this. It should only + # be necessary to list helper-Info.plist once, not the three times it + # is listed here. + 'mac_bundle_resources!': [ + 'tests/cefclient/mac/helper-Info.plist', + ], + # TODO(mark): For now, don't put any resources into this app. Its + # resources directory will be a symbolic link to the browser app's + # resources directory. + 'mac_bundle_resources/': [ + ['exclude', '.*'], + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'tests/cefclient/mac/helper-Info.plist', + # Necessary to avoid an "install_name_tool: changing install names or + # rpaths can't be redone" error. + 'OTHER_LDFLAGS': ['-Wl,-headerpad_max_install_names'], + }, + 'postbuilds': [ + { + # The framework defines its load-time path + # (DYLIB_INSTALL_NAME_BASE) relative to the main executable + # (chrome). A different relative path needs to be used in + # cefclient_helper_app. + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../../../../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + { + # Modify the Info.plist as needed. The script explains why this + # is needed. This is also done in the chrome and chrome_dll + # targets. In this case, --breakpad=0, --keystone=0, and --scm=0 + # are used because Breakpad, Keystone, and SCM keys are + # never placed into the helper. + 'postbuild_name': 'Tweak Info.plist', + 'action': ['../build/mac/tweak_info_plist.py', + '--breakpad=0', + '--keystone=0', + '--scm=0'], + }, + ], + }, # target cef_unittests_helper_app + ], + }, { # OS!="mac" + 'targets': [ + { + 'target_name': 'libcef', + 'type': 'shared_library', + 'msvs_guid': 'C13650D5-CF1A-4259-BE45-B1EBA6280E47', + 'dependencies': [ + 'libcef_static', + ], + 'defines': [ + 'BUILDING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'sources': [ + '<@(includes_common)', + '<@(includes_capi)', + '<@(libcef_sources_common)', + ], + 'conditions': [ + ['OS=="win" and win_use_allocator_shim==1', { + 'dependencies': [ + '<(DEPTH)/base/allocator/allocator.gyp:allocator', + ], + }], + ['OS=="win"', { + 'configurations': { + 'Debug_Base': { + 'msvs_settings': { + 'VCLinkerTool': { + 'LinkIncremental': '<(msvs_large_module_debug_link_mode)', + }, + }, + }, + }, + 'sources': [ + '<@(includes_win)', + # TODO(cef): Remove ui_unscaled_resources.rc once custom cursor + # resources can be loaded via ResourceBundle. See crbug.com/147663. + '<(SHARED_INTERMEDIATE_DIR)/content/content_resources.rc', + '<(SHARED_INTERMEDIATE_DIR)/ui/resources/ui_unscaled_resources.rc', + 'libcef_dll/libcef_dll.rc', + ], + 'link_settings': { + 'libraries': [ + '-lcomctl32.lib', + ], + }, + 'msvs_settings': { + 'VCLinkerTool': { + # Generate a PDB symbol file for both Debug and Release builds. + 'GenerateDebugInformation': 'true', + }, + 'VCManifestTool': { + 'AdditionalManifestFiles': [ + 'libcef_dll/libcef.dll.manifest', + ], + }, + }, + }], + [ '(OS=="linux" or OS=="freebsd" or OS=="openbsd") and use_allocator!="none"', { + 'dependencies':[ + '<(DEPTH)/base/allocator/allocator.gyp:allocator', + ], + }], + ], + }], + }], # OS!="mac" + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'targets': [ + { + 'target_name': 'gtk', + 'type': 'none', + 'variables': { + # gtk requires gmodule, but it does not list it as a dependency + # in some misconfigured systems. + 'gtk_packages': 'gmodule-2.0 gtk+-2.0 gthread-2.0 gtk+-unix-print-2.0', + }, + 'direct_dependent_settings': { + 'cflags': [ + ' + +#include "include/base/cef_build.h" + +#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS) +// windows.h #defines this (only on x64). This causes problems because the +// public API also uses MemoryBarrier at the public name for this fence. So, on +// X64, undef it, and call its documented +// (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx) +// implementation directly. +#undef MemoryBarrier +#endif + +namespace base { +namespace subtle { + +typedef int32_t Atomic32; +#ifdef ARCH_CPU_64_BITS +// We need to be able to go between Atomic64 and AtomicWord implicitly. This +// means Atomic64 and AtomicWord should be the same type on 64-bit. +#if defined(__ILP32__) || defined(OS_NACL) +// NaCl's intptr_t is not actually 64-bits on 64-bit! +// http://code.google.com/p/nativeclient/issues/detail?id=1162 +typedef int64_t Atomic64; +#else +typedef intptr_t Atomic64; +#endif +#endif + +// Use AtomicWord for a machine-sized pointer. It will use the Atomic32 or +// Atomic64 routines below, depending on your architecture. +typedef intptr_t AtomicWord; + +// Atomically execute: +// result = *ptr; +// if (*ptr == old_value) +// *ptr = new_value; +// return result; +// +// I.e., replace "*ptr" with "new_value" if "*ptr" used to be "old_value". +// Always return the old value of "*ptr" +// +// This routine implies no memory barriers. +Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value); + +// Atomically store new_value into *ptr, returning the previous value held in +// *ptr. This routine implies no memory barriers. +Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, Atomic32 new_value); + +// Atomically increment *ptr by "increment". Returns the new value of +// *ptr with the increment applied. This routine implies no memory barriers. +Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, Atomic32 increment); + +Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment); + +// These following lower-level operations are typically useful only to people +// implementing higher-level synchronization operations like spinlocks, +// mutexes, and condition-variables. They combine CompareAndSwap(), a load, or +// a store with appropriate memory-ordering instructions. "Acquire" operations +// ensure that no later memory access can be reordered ahead of the operation. +// "Release" operations ensure that no previous memory access can be reordered +// after the operation. "Barrier" operations have both "Acquire" and "Release" +// semantics. A MemoryBarrier() has "Barrier" semantics, but does no memory +// access. +Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value); +Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value); + +void MemoryBarrier(); +void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value); +void Acquire_Store(volatile Atomic32* ptr, Atomic32 value); +void Release_Store(volatile Atomic32* ptr, Atomic32 value); + +Atomic32 NoBarrier_Load(volatile const Atomic32* ptr); +Atomic32 Acquire_Load(volatile const Atomic32* ptr); +Atomic32 Release_Load(volatile const Atomic32* ptr); + +// 64-bit atomic operations (only available on 64-bit processors). +#ifdef ARCH_CPU_64_BITS +Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value); +Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, Atomic64 new_value); +Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); +Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, Atomic64 increment); + +Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value); +Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value); +void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value); +void Acquire_Store(volatile Atomic64* ptr, Atomic64 value); +void Release_Store(volatile Atomic64* ptr, Atomic64 value); +Atomic64 NoBarrier_Load(volatile const Atomic64* ptr); +Atomic64 Acquire_Load(volatile const Atomic64* ptr); +Atomic64 Release_Load(volatile const Atomic64* ptr); +#endif // ARCH_CPU_64_BITS + +} // namespace subtle +} // namespace base + +// Include our platform specific implementation. +#if defined(OS_WIN) && defined(COMPILER_MSVC) && defined(ARCH_CPU_X86_FAMILY) +#include "include/base/internal/cef_atomicops_x86_msvc.h" +#elif defined(OS_MACOSX) +#include "include/base/internal/cef_atomicops_mac.h" +#elif defined(COMPILER_GCC) && defined(ARCH_CPU_X86_FAMILY) +#include "include/base/internal/cef_atomicops_x86_gcc.h" +#else +#error "Atomic operations are not supported on your platform" +#endif + +// On some platforms we need additional declarations to make +// AtomicWord compatible with our other Atomic* types. +#if defined(OS_MACOSX) || defined(OS_OPENBSD) +#include "include/base/internal/cef_atomicops_atomicword_compat.h" +#endif + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_ATOMICOPS_H_ diff --git a/include/base/cef_basictypes.h b/include/base/cef_basictypes.h new file mode 100644 index 000000000..af3431127 --- /dev/null +++ b/include/base/cef_basictypes.h @@ -0,0 +1,86 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_BASICTYPES_H_ +#define CEF_INCLUDE_BASE_CEF_BASICTYPES_H_ +#pragma once + +#if defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/basictypes.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include // For UINT_MAX +#include // For size_t + +#include "include/base/cef_build.h" + +// The NSPR system headers define 64-bit as |long| when possible, except on +// Mac OS X. In order to not have typedef mismatches, we do the same on LP64. +// +// On Mac OS X, |long long| is used for 64-bit types for compatibility with +// format macros even in the LP64 model. +#if defined(__LP64__) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) +typedef long int64; // NOLINT(runtime/int) +typedef unsigned long uint64; // NOLINT(runtime/int) +#else +typedef long long int64; // NOLINT(runtime/int) +typedef unsigned long long uint64; // NOLINT(runtime/int) +#endif + +// TODO: Remove these type guards. These are to avoid conflicts with +// obsolete/protypes.h in the Gecko SDK. +#ifndef _INT32 +#define _INT32 +typedef int int32; +#endif + +// TODO: Remove these type guards. These are to avoid conflicts with +// obsolete/protypes.h in the Gecko SDK. +#ifndef _UINT32 +#define _UINT32 +typedef unsigned int uint32; +#endif + +// UTF-16 character type +#ifndef char16 +#if defined(WIN32) +typedef wchar_t char16; +#else +typedef unsigned short char16; +#endif +#endif + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_BASICTYPES_H_ diff --git a/include/base/cef_bind.h b/include/base/cef_bind.h new file mode 100644 index 000000000..dcf86ac7e --- /dev/null +++ b/include/base/cef_bind.h @@ -0,0 +1,548 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_BIND_H_ +#define CEF_INCLUDE_BASE_CEF_BIND_H_ +#pragma once + +#if defined(BASE_BIND_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/bind.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/internal/cef_bind_internal.h" +#include "include/base/internal/cef_callback_internal.h" + +// ----------------------------------------------------------------------------- +// Usage documentation +// ----------------------------------------------------------------------------- +// +// See base/cef_callback.h for documentation. +// +// +// ----------------------------------------------------------------------------- +// Implementation notes +// ----------------------------------------------------------------------------- +// +// If you're reading the implementation, before proceeding further, you should +// read the top comment of base/bind_internal.h for a definition of common +// terms and concepts. +// +// RETURN TYPES +// +// Though Bind()'s result is meant to be stored in a Callback<> type, it +// cannot actually return the exact type without requiring a large amount +// of extra template specializations. The problem is that in order to +// discern the correct specialization of Callback<>, Bind would need to +// unwrap the function signature to determine the signature's arity, and +// whether or not it is a method. +// +// Each unique combination of (arity, function_type, num_prebound) where +// function_type is one of {function, method, const_method} would require +// one specialization. We eventually have to do a similar number of +// specializations anyways in the implementation (see the Invoker<>, +// classes). However, it is avoidable in Bind if we return the result +// via an indirection like we do below. +// +// TODO(ajwong): We might be able to avoid this now, but need to test. +// +// It is possible to move most of the COMPILE_ASSERT asserts into BindState<>, +// but it feels a little nicer to have the asserts here so people do not +// need to crack open bind_internal.h. On the other hand, it makes Bind() +// harder to read. + +namespace base { + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void()> + ::UnboundRunType> +Bind(Functor functor) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + typedef cef_internal::BindState BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor))); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + typedef cef_internal::BindState::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1)); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1, const P2& p2) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value || + is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p2_is_refcounted_type_and_needs_scoped_refptr); + typedef cef_internal::BindState::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1, p2)); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p2_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p3_is_refcounted_type_and_needs_scoped_refptr); + typedef cef_internal::BindState::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3)); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p2_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p3_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p4_is_refcounted_type_and_needs_scoped_refptr); + typedef cef_internal::BindState::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4)); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, + const P5& p5) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p2_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p3_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p4_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p5_is_refcounted_type_and_needs_scoped_refptr); + typedef cef_internal::BindState::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5)); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, + const P5& p5, const P6& p6) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p2_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p3_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p4_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p5_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p6_is_refcounted_type_and_needs_scoped_refptr); + typedef cef_internal::BindState::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6)); +} + +template +base::Callback< + typename cef_internal::BindState< + typename cef_internal::FunctorTraits::RunnableType, + typename cef_internal::FunctorTraits::RunType, + void(typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> + ::UnboundRunType> +Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4, + const P5& p5, const P6& p6, const P7& p7) { + // Typedefs for how to store and run the functor. + typedef typename cef_internal::FunctorTraits::RunnableType RunnableType; + typedef typename cef_internal::FunctorTraits::RunType RunType; + + // Use RunnableType::RunType instead of RunType above because our + // checks should below for bound references need to know what the actual + // functor is going to interpret the argument as. + typedef cef_internal::FunctionTraits + BoundFunctorTraits; + + // Do not allow binding a non-const reference parameter. Non-const reference + // parameters are disallowed by the Google style guide. Also, binding a + // non-const reference parameter can make for subtle bugs because the + // invoked function will receive a reference to the stored copy of the + // argument and not the original. + COMPILE_ASSERT( + !(is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value || + is_non_const_reference::value ), + do_not_bind_functions_with_nonconst_ref); + + // For methods, we need to be careful for parameter 1. We do not require + // a scoped_refptr because BindState<> itself takes care of AddRef() for + // methods. We also disallow binding of an array as the method's target + // object. + COMPILE_ASSERT( + cef_internal::HasIsMethodTag::value || + !cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p1_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::HasIsMethodTag::value || + !is_array::value, + first_bound_argument_to_method_cannot_be_array); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p2_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p3_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p4_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p5_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p6_is_refcounted_type_and_needs_scoped_refptr); + COMPILE_ASSERT(!cef_internal::NeedsScopedRefptrButGetsRawPtr::value, + p7_is_refcounted_type_and_needs_scoped_refptr); + typedef cef_internal::BindState::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType, + typename cef_internal::CallbackParamTraits::StorageType)> BindState; + + + return Callback( + new BindState(cef_internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6, + p7)); +} + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_BIND_H_ diff --git a/include/base/cef_bind_helpers.h b/include/base/cef_bind_helpers.h new file mode 100644 index 000000000..e8c4cffd8 --- /dev/null +++ b/include/base/cef_bind_helpers.h @@ -0,0 +1,586 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// This defines a set of argument wrappers and related factory methods that +// can be used specify the refcounting and reference semantics of arguments +// that are bound by the Bind() function in base/bind.h. +// +// It also defines a set of simple functions and utilities that people want +// when using Callback<> and Bind(). +// +// +// ARGUMENT BINDING WRAPPERS +// +// The wrapper functions are base::Unretained(), base::Owned(), base::Passed(), +// base::ConstRef(), and base::IgnoreResult(). +// +// Unretained() allows Bind() to bind a non-refcounted class, and to disable +// refcounting on arguments that are refcounted objects. +// +// Owned() transfers ownership of an object to the Callback resulting from +// bind; the object will be deleted when the Callback is deleted. +// +// Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr) +// through a Callback. Logically, this signifies a destructive transfer of +// the state of the argument into the target function. Invoking +// Callback::Run() twice on a Callback that was created with a Passed() +// argument will CHECK() because the first invocation would have already +// transferred ownership to the target function. +// +// ConstRef() allows binding a constant reference to an argument rather +// than a copy. +// +// IgnoreResult() is used to adapt a function or Callback with a return type to +// one with a void return. This is most useful if you have a function with, +// say, a pesky ignorable bool return that you want to use with PostTask or +// something else that expect a Callback with a void return. +// +// EXAMPLE OF Unretained(): +// +// class Foo { +// public: +// void func() { cout << "Foo:f" << endl; } +// }; +// +// // In some function somewhere. +// Foo foo; +// Closure foo_callback = +// Bind(&Foo::func, Unretained(&foo)); +// foo_callback.Run(); // Prints "Foo:f". +// +// Without the Unretained() wrapper on |&foo|, the above call would fail +// to compile because Foo does not support the AddRef() and Release() methods. +// +// +// EXAMPLE OF Owned(): +// +// void foo(int* arg) { cout << *arg << endl } +// +// int* pn = new int(1); +// Closure foo_callback = Bind(&foo, Owned(pn)); +// +// foo_callback.Run(); // Prints "1" +// foo_callback.Run(); // Prints "1" +// *n = 2; +// foo_callback.Run(); // Prints "2" +// +// foo_callback.Reset(); // |pn| is deleted. Also will happen when +// // |foo_callback| goes out of scope. +// +// Without Owned(), someone would have to know to delete |pn| when the last +// reference to the Callback is deleted. +// +// +// EXAMPLE OF ConstRef(): +// +// void foo(int arg) { cout << arg << endl } +// +// int n = 1; +// Closure no_ref = Bind(&foo, n); +// Closure has_ref = Bind(&foo, ConstRef(n)); +// +// no_ref.Run(); // Prints "1" +// has_ref.Run(); // Prints "1" +// +// n = 2; +// no_ref.Run(); // Prints "1" +// has_ref.Run(); // Prints "2" +// +// Note that because ConstRef() takes a reference on |n|, |n| must outlive all +// its bound callbacks. +// +// +// EXAMPLE OF IgnoreResult(): +// +// int DoSomething(int arg) { cout << arg << endl; } +// +// // Assign to a Callback with a void return type. +// Callback cb = Bind(IgnoreResult(&DoSomething)); +// cb->Run(1); // Prints "1". +// +// // Prints "1" on |ml|. +// ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1); +// +// +// EXAMPLE OF Passed(): +// +// void TakesOwnership(scoped_ptr arg) { } +// scoped_ptr CreateFoo() { return scoped_ptr(new Foo()); } +// +// scoped_ptr f(new Foo()); +// +// // |cb| is given ownership of Foo(). |f| is now NULL. +// // You can use f.Pass() in place of &f, but it's more verbose. +// Closure cb = Bind(&TakesOwnership, Passed(&f)); +// +// // Run was never called so |cb| still owns Foo() and deletes +// // it on Reset(). +// cb.Reset(); +// +// // |cb| is given a new Foo created by CreateFoo(). +// cb = Bind(&TakesOwnership, Passed(CreateFoo())); +// +// // |arg| in TakesOwnership() is given ownership of Foo(). |cb| +// // no longer owns Foo() and, if reset, would not delete Foo(). +// cb.Run(); // Foo() is now transferred to |arg| and deleted. +// cb.Run(); // This CHECK()s since Foo() already been used once. +// +// Passed() is particularly useful with PostTask() when you are transferring +// ownership of an argument into a task, but don't necessarily know if the +// task will always be executed. This can happen if the task is cancellable +// or if it is posted to a MessageLoopProxy. +// +// +// SIMPLE FUNCTIONS AND UTILITIES. +// +// DoNothing() - Useful for creating a Closure that does nothing when called. +// DeletePointer() - Useful for creating a Closure that will delete a +// pointer when invoked. Only use this when necessary. +// In most cases MessageLoop::DeleteSoon() is a better +// fit. + +#ifndef CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ +#define CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ +#pragma once + +#if defined(BASE_BIND_HELPERS_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/bind_helpers.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_basictypes.h" +#include "include/base/cef_callback.h" +#include "include/base/cef_template_util.h" +#include "include/base/cef_weak_ptr.h" + +namespace base { +namespace cef_internal { + +// Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T +// for the existence of AddRef() and Release() functions of the correct +// signature. +// +// http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error +// http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence +// http://stackoverflow.com/questions/4358584/sfinae-approach-comparison +// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions +// +// The last link in particular show the method used below. +// +// For SFINAE to work with inherited methods, we need to pull some extra tricks +// with multiple inheritance. In the more standard formulation, the overloads +// of Check would be: +// +// template +// Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*); +// +// template +// No NotTheCheckWeWant(...); +// +// static const bool value = sizeof(NotTheCheckWeWant(0)) == sizeof(Yes); +// +// The problem here is that template resolution will not match +// C::TargetFunc if TargetFunc does not exist directly in C. That is, if +// TargetFunc in inherited from an ancestor, &C::TargetFunc will not match, +// |value| will be false. This formulation only checks for whether or +// not TargetFunc exist directly in the class being introspected. +// +// To get around this, we play a dirty trick with multiple inheritance. +// First, We create a class BaseMixin that declares each function that we +// want to probe for. Then we create a class Base that inherits from both T +// (the class we wish to probe) and BaseMixin. Note that the function +// signature in BaseMixin does not need to match the signature of the function +// we are probing for; thus it's easiest to just use void(void). +// +// Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an +// ambiguous resolution between BaseMixin and T. This lets us write the +// following: +// +// template +// No GoodCheck(Helper<&C::TargetFunc>*); +// +// template +// Yes GoodCheck(...); +// +// static const bool value = sizeof(GoodCheck(0)) == sizeof(Yes); +// +// Notice here that the variadic version of GoodCheck() returns Yes here +// instead of No like the previous one. Also notice that we calculate |value| +// by specializing GoodCheck() on Base instead of T. +// +// We've reversed the roles of the variadic, and Helper overloads. +// GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid +// substitution if T::TargetFunc exists. Thus GoodCheck(0) will resolve +// to the variadic version if T has TargetFunc. If T::TargetFunc does not +// exist, then &C::TargetFunc is not ambiguous, and the overload resolution +// will prefer GoodCheck(Helper<&C::TargetFunc>*). +// +// This method of SFINAE will correctly probe for inherited names, but it cannot +// typecheck those names. It's still a good enough sanity check though. +// +// Works on gcc-4.2, gcc-4.4, and Visual Studio 2008. +// +// TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted +// this works well. +// +// TODO(ajwong): Make this check for Release() as well. +// See http://crbug.com/82038. +template +class SupportsAddRefAndRelease { + typedef char Yes[1]; + typedef char No[2]; + + struct BaseMixin { + void AddRef(); + }; + +// MSVC warns when you try to use Base if T has a private destructor, the +// common pattern for refcounted types. It does this even though no attempt to +// instantiate Base is made. We disable the warning for this definition. +#if defined(OS_WIN) +#pragma warning(push) +#pragma warning(disable:4624) +#endif + struct Base : public T, public BaseMixin { + }; +#if defined(OS_WIN) +#pragma warning(pop) +#endif + + template struct Helper {}; + + template + static No& Check(Helper<&C::AddRef>*); + + template + static Yes& Check(...); + + public: + static const bool value = sizeof(Check(0)) == sizeof(Yes); +}; + +// Helpers to assert that arguments of a recounted type are bound with a +// scoped_refptr. +template +struct UnsafeBindtoRefCountedArgHelper : false_type { +}; + +template +struct UnsafeBindtoRefCountedArgHelper + : integral_constant::value> { +}; + +template +struct UnsafeBindtoRefCountedArg : false_type { +}; + +template +struct UnsafeBindtoRefCountedArg + : UnsafeBindtoRefCountedArgHelper::value, T> { +}; + +template +class HasIsMethodTag { + typedef char Yes[1]; + typedef char No[2]; + + template + static Yes& Check(typename U::IsMethod*); + + template + static No& Check(...); + + public: + static const bool value = sizeof(Check(0)) == sizeof(Yes); +}; + +template +class UnretainedWrapper { + public: + explicit UnretainedWrapper(T* o) : ptr_(o) {} + T* get() const { return ptr_; } + private: + T* ptr_; +}; + +template +class ConstRefWrapper { + public: + explicit ConstRefWrapper(const T& o) : ptr_(&o) {} + const T& get() const { return *ptr_; } + private: + const T* ptr_; +}; + +template +struct IgnoreResultHelper { + explicit IgnoreResultHelper(T functor) : functor_(functor) {} + + T functor_; +}; + +template +struct IgnoreResultHelper > { + explicit IgnoreResultHelper(const Callback& functor) : functor_(functor) {} + + const Callback& functor_; +}; + +// An alternate implementation is to avoid the destructive copy, and instead +// specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to +// a class that is essentially a scoped_ptr<>. +// +// The current implementation has the benefit though of leaving ParamTraits<> +// fully in callback_internal.h as well as avoiding type conversions during +// storage. +template +class OwnedWrapper { + public: + explicit OwnedWrapper(T* o) : ptr_(o) {} + ~OwnedWrapper() { delete ptr_; } + T* get() const { return ptr_; } + OwnedWrapper(const OwnedWrapper& other) { + ptr_ = other.ptr_; + other.ptr_ = NULL; + } + + private: + mutable T* ptr_; +}; + +// PassedWrapper is a copyable adapter for a scoper that ignores const. +// +// It is needed to get around the fact that Bind() takes a const reference to +// all its arguments. Because Bind() takes a const reference to avoid +// unnecessary copies, it is incompatible with movable-but-not-copyable +// types; doing a destructive "move" of the type into Bind() would violate +// the const correctness. +// +// This conundrum cannot be solved without either C++11 rvalue references or +// a O(2^n) blowup of Bind() templates to handle each combination of regular +// types and movable-but-not-copyable types. Thus we introduce a wrapper type +// that is copyable to transmit the correct type information down into +// BindState<>. Ignoring const in this type makes sense because it is only +// created when we are explicitly trying to do a destructive move. +// +// Two notes: +// 1) PassedWrapper supports any type that has a "Pass()" function. +// This is intentional. The whitelisting of which specific types we +// support is maintained by CallbackParamTraits<>. +// 2) is_valid_ is distinct from NULL because it is valid to bind a "NULL" +// scoper to a Callback and allow the Callback to execute once. +template +class PassedWrapper { + public: + explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {} + PassedWrapper(const PassedWrapper& other) + : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) { + } + T Pass() const { + CHECK(is_valid_); + is_valid_ = false; + return scoper_.Pass(); + } + + private: + mutable bool is_valid_; + mutable T scoper_; +}; + +// Unwrap the stored parameters for the wrappers above. +template +struct UnwrapTraits { + typedef const T& ForwardType; + static ForwardType Unwrap(const T& o) { return o; } +}; + +template +struct UnwrapTraits > { + typedef T* ForwardType; + static ForwardType Unwrap(UnretainedWrapper unretained) { + return unretained.get(); + } +}; + +template +struct UnwrapTraits > { + typedef const T& ForwardType; + static ForwardType Unwrap(ConstRefWrapper const_ref) { + return const_ref.get(); + } +}; + +template +struct UnwrapTraits > { + typedef T* ForwardType; + static ForwardType Unwrap(const scoped_refptr& o) { return o.get(); } +}; + +template +struct UnwrapTraits > { + typedef const WeakPtr& ForwardType; + static ForwardType Unwrap(const WeakPtr& o) { return o; } +}; + +template +struct UnwrapTraits > { + typedef T* ForwardType; + static ForwardType Unwrap(const OwnedWrapper& o) { + return o.get(); + } +}; + +template +struct UnwrapTraits > { + typedef T ForwardType; + static T Unwrap(PassedWrapper& o) { + return o.Pass(); + } +}; + +// Utility for handling different refcounting semantics in the Bind() +// function. +template +struct MaybeRefcount; + +template +struct MaybeRefcount { + static void AddRef(const T&) {} + static void Release(const T&) {} +}; + +template +struct MaybeRefcount { + static void AddRef(const T*) {} + static void Release(const T*) {} +}; + +template +struct MaybeRefcount { + static void AddRef(const T&) {} + static void Release(const T&) {} +}; + +template +struct MaybeRefcount { + static void AddRef(T* o) { o->AddRef(); } + static void Release(T* o) { o->Release(); } +}; + +// No need to additionally AddRef() and Release() since we are storing a +// scoped_refptr<> inside the storage object already. +template +struct MaybeRefcount > { + static void AddRef(const scoped_refptr& o) {} + static void Release(const scoped_refptr& o) {} +}; + +template +struct MaybeRefcount { + static void AddRef(const T* o) { o->AddRef(); } + static void Release(const T* o) { o->Release(); } +}; + +// IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a +// method. It is used internally by Bind() to select the correct +// InvokeHelper that will no-op itself in the event the WeakPtr<> for +// the target object is invalidated. +// +// P1 should be the type of the object that will be received of the method. +template +struct IsWeakMethod : public false_type {}; + +template +struct IsWeakMethod > : public true_type {}; + +template +struct IsWeakMethod > > : public true_type {}; + +} // namespace cef_internal + +template +static inline cef_internal::UnretainedWrapper Unretained(T* o) { + return cef_internal::UnretainedWrapper(o); +} + +template +static inline cef_internal::ConstRefWrapper ConstRef(const T& o) { + return cef_internal::ConstRefWrapper(o); +} + +template +static inline cef_internal::OwnedWrapper Owned(T* o) { + return cef_internal::OwnedWrapper(o); +} + +// We offer 2 syntaxes for calling Passed(). The first takes a temporary and +// is best suited for use with the return value of a function. The second +// takes a pointer to the scoper and is just syntactic sugar to avoid having +// to write Passed(scoper.Pass()). +template +static inline cef_internal::PassedWrapper Passed(T scoper) { + return cef_internal::PassedWrapper(scoper.Pass()); +} +template +static inline cef_internal::PassedWrapper Passed(T* scoper) { + return cef_internal::PassedWrapper(scoper->Pass()); +} + +template +static inline cef_internal::IgnoreResultHelper IgnoreResult(T data) { + return cef_internal::IgnoreResultHelper(data); +} + +template +static inline cef_internal::IgnoreResultHelper > +IgnoreResult(const Callback& data) { + return cef_internal::IgnoreResultHelper >(data); +} + +void DoNothing(); + +template +void DeletePointer(T* obj) { + delete obj; +} + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_BIND_HELPERS_H_ diff --git a/include/base/cef_build.h b/include/base/cef_build.h new file mode 100644 index 000000000..594c6ff0a --- /dev/null +++ b/include/base/cef_build.h @@ -0,0 +1,186 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_BUILD_H_ +#define CEF_INCLUDE_BASE_CEF_BUILD_H_ +#pragma once + +#if defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/compiler_specific.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#if defined(_WIN32) +#ifndef OS_WIN +#define OS_WIN 1 +#endif +#elif defined(__APPLE__) +#ifndef OS_MACOSX +#define OS_MACOSX 1 +#endif +#elif defined(__linux__) +#ifndef OS_LINUX +#define OS_LINUX 1 +#endif +#else +#error Please add support for your platform in cef_build.h +#endif + +// For access to standard POSIXish features, use OS_POSIX instead of a +// more specific macro. +#if defined(OS_MACOSX) || defined(OS_LINUX) +#ifndef OS_POSIX +#define OS_POSIX 1 +#endif +#endif + +// Compiler detection. +#if defined(__GNUC__) +#ifndef COMPILER_GCC +#define COMPILER_GCC 1 +#endif +#elif defined(_MSC_VER) +#ifndef COMPILER_MSVC +#define COMPILER_MSVC 1 +#endif +#else +#error Please add support for your compiler in cef_build.h +#endif + +// Processor architecture detection. For more info on what's defined, see: +// http://msdn.microsoft.com/en-us/library/b0084kay.aspx +// http://www.agner.org/optimize/calling_conventions.pdf +// or with gcc, run: "echo | gcc -E -dM -" +#if defined(_M_X64) || defined(__x86_64__) +#define ARCH_CPU_X86_FAMILY 1 +#define ARCH_CPU_X86_64 1 +#define ARCH_CPU_64_BITS 1 +#define ARCH_CPU_LITTLE_ENDIAN 1 +#elif defined(_M_IX86) || defined(__i386__) +#define ARCH_CPU_X86_FAMILY 1 +#define ARCH_CPU_X86 1 +#define ARCH_CPU_32_BITS 1 +#define ARCH_CPU_LITTLE_ENDIAN 1 +#elif defined(__ARMEL__) +#define ARCH_CPU_ARM_FAMILY 1 +#define ARCH_CPU_ARMEL 1 +#define ARCH_CPU_32_BITS 1 +#define ARCH_CPU_LITTLE_ENDIAN 1 +#elif defined(__aarch64__) +#define ARCH_CPU_ARM_FAMILY 1 +#define ARCH_CPU_ARM64 1 +#define ARCH_CPU_64_BITS 1 +#define ARCH_CPU_LITTLE_ENDIAN 1 +#elif defined(__pnacl__) +#define ARCH_CPU_32_BITS 1 +#define ARCH_CPU_LITTLE_ENDIAN 1 +#elif defined(__MIPSEL__) +#define ARCH_CPU_MIPS_FAMILY 1 +#define ARCH_CPU_MIPSEL 1 +#define ARCH_CPU_32_BITS 1 +#define ARCH_CPU_LITTLE_ENDIAN 1 +#else +#error Please add support for your architecture in cef_build.h +#endif + +// Type detection for wchar_t. +#if defined(OS_WIN) +#define WCHAR_T_IS_UTF16 +#elif defined(OS_POSIX) && defined(COMPILER_GCC) && \ + defined(__WCHAR_MAX__) && \ + (__WCHAR_MAX__ == 0x7fffffff || __WCHAR_MAX__ == 0xffffffff) +#define WCHAR_T_IS_UTF32 +#elif defined(OS_POSIX) && defined(COMPILER_GCC) && \ + defined(__WCHAR_MAX__) && \ + (__WCHAR_MAX__ == 0x7fff || __WCHAR_MAX__ == 0xffff) +// On Posix, we'll detect short wchar_t, but projects aren't guaranteed to +// compile in this mode (in particular, Chrome doesn't). This is intended for +// other projects using base who manage their own dependencies and make sure +// short wchar works for them. +#define WCHAR_T_IS_UTF16 +#else +#error Please add support for your compiler in cef_build.h +#endif + +// Annotate a virtual method indicating it must be overriding a virtual +// method in the parent class. +// Use like: +// virtual void foo() OVERRIDE; +#ifndef OVERRIDE +#if defined(__clang__) || defined(COMPILER_MSVC) +#define OVERRIDE override +#elif defined(COMPILER_GCC) && __cplusplus >= 201103 && \ + (__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= 40700 +// GCC 4.7 supports explicit virtual overrides when C++11 support is enabled. +#define OVERRIDE override +#else +#define OVERRIDE +#endif +#endif // OVERRIDE + +// Annotate a function indicating the caller must examine the return value. +// Use like: +// int foo() WARN_UNUSED_RESULT; +// To explicitly ignore a result, see |ignore_result()| in . +#ifndef WARN_UNUSED_RESULT +#if defined(COMPILER_GCC) +#define WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#else +#define WARN_UNUSED_RESULT +#endif +#endif // WARN_UNUSED_RESULT + +// Annotate a typedef or function indicating it's ok if it's not used. +// Use like: +// typedef Foo Bar ALLOW_UNUSED_TYPE; +#ifndef ALLOW_UNUSED_TYPE +#if defined(COMPILER_GCC) +#define ALLOW_UNUSED_TYPE __attribute__((unused)) +#else +#define ALLOW_UNUSED_TYPE +#endif +#endif // ALLOW_UNUSED_TYPE + +// Annotate a variable indicating it's ok if the variable is not used. +// (Typically used to silence a compiler warning when the assignment +// is important for some other reason.) +// Use like: +// int x = ...; +// ALLOW_UNUSED_LOCAL(x); +#ifndef ALLOW_UNUSED_LOCAL +#define ALLOW_UNUSED_LOCAL(x) false ? (void)x : (void)0 +#endif + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_BUILD_H_ diff --git a/include/base/cef_callback.h b/include/base/cef_callback.h new file mode 100644 index 000000000..75783271d --- /dev/null +++ b/include/base/cef_callback.h @@ -0,0 +1,807 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_CALLBACK_H_ +#define CEF_INCLUDE_BASE_CEF_CALLBACK_H_ +#pragma once + +#if defined(BASE_CALLBACK_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/callback.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/internal/cef_callback_internal.h" +#include "include/base/cef_callback_forward.h" +#include "include/base/cef_template_util.h" + +// NOTE: Header files that do not require the full definition of Callback or +// Closure should #include "base/cef_callback_forward.h" instead of this file. + +// ----------------------------------------------------------------------------- +// Introduction +// ----------------------------------------------------------------------------- +// +// The templated Callback class is a generalized function object. Together +// with the Bind() function in bind.h, they provide a type-safe method for +// performing partial application of functions. +// +// Partial application (or "currying") is the process of binding a subset of +// a function's arguments to produce another function that takes fewer +// arguments. This can be used to pass around a unit of delayed execution, +// much like lexical closures are used in other languages. For example, it +// is used in Chromium code to schedule tasks on different MessageLoops. +// +// A callback with no unbound input parameters (base::Callback) +// is called a base::Closure. Note that this is NOT the same as what other +// languages refer to as a closure -- it does not retain a reference to its +// enclosing environment. +// +// MEMORY MANAGEMENT AND PASSING +// +// The Callback objects themselves should be passed by const-reference, and +// stored by copy. They internally store their state via a refcounted class +// and thus do not need to be deleted. +// +// The reason to pass via a const-reference is to avoid unnecessary +// AddRef/Release pairs to the internal state. +// +// +// ----------------------------------------------------------------------------- +// Quick reference for basic stuff +// ----------------------------------------------------------------------------- +// +// BINDING A BARE FUNCTION +// +// int Return5() { return 5; } +// base::Callback func_cb = base::Bind(&Return5); +// LOG(INFO) << func_cb.Run(); // Prints 5. +// +// BINDING A CLASS METHOD +// +// The first argument to bind is the member function to call, the second is +// the object on which to call it. +// +// class Ref : public base::RefCountedThreadSafe { +// public: +// int Foo() { return 3; } +// void PrintBye() { LOG(INFO) << "bye."; } +// }; +// scoped_refptr ref = new Ref(); +// base::Callback ref_cb = base::Bind(&Ref::Foo, ref); +// LOG(INFO) << ref_cb.Run(); // Prints out 3. +// +// By default the object must support RefCounted or you will get a compiler +// error. If you're passing between threads, be sure it's +// RefCountedThreadSafe! See "Advanced binding of member functions" below if +// you don't want to use reference counting. +// +// RUNNING A CALLBACK +// +// Callbacks can be run with their "Run" method, which has the same +// signature as the template argument to the callback. +// +// void DoSomething(const base::Callback& callback) { +// callback.Run(5, "hello"); +// } +// +// Callbacks can be run more than once (they don't get deleted or marked when +// run). However, this precludes using base::Passed (see below). +// +// void DoSomething(const base::Callback& callback) { +// double myresult = callback.Run(3.14159); +// myresult += callback.Run(2.71828); +// } +// +// PASSING UNBOUND INPUT PARAMETERS +// +// Unbound parameters are specified at the time a callback is Run(). They are +// specified in the Callback template type: +// +// void MyFunc(int i, const std::string& str) {} +// base::Callback cb = base::Bind(&MyFunc); +// cb.Run(23, "hello, world"); +// +// PASSING BOUND INPUT PARAMETERS +// +// Bound parameters are specified when you create thee callback as arguments +// to Bind(). They will be passed to the function and the Run()ner of the +// callback doesn't see those values or even know that the function it's +// calling. +// +// void MyFunc(int i, const std::string& str) {} +// base::Callback cb = base::Bind(&MyFunc, 23, "hello world"); +// cb.Run(); +// +// A callback with no unbound input parameters (base::Callback) +// is called a base::Closure. So we could have also written: +// +// base::Closure cb = base::Bind(&MyFunc, 23, "hello world"); +// +// When calling member functions, bound parameters just go after the object +// pointer. +// +// base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world"); +// +// PARTIAL BINDING OF PARAMETERS +// +// You can specify some parameters when you create the callback, and specify +// the rest when you execute the callback. +// +// void MyFunc(int i, const std::string& str) {} +// base::Callback cb = base::Bind(&MyFunc, 23); +// cb.Run("hello world"); +// +// When calling a function bound parameters are first, followed by unbound +// parameters. +// +// +// ----------------------------------------------------------------------------- +// Quick reference for advanced binding +// ----------------------------------------------------------------------------- +// +// BINDING A CLASS METHOD WITH WEAK POINTERS +// +// base::Bind(&MyClass::Foo, GetWeakPtr()); +// +// The callback will not be run if the object has already been destroyed. +// DANGER: weak pointers are not threadsafe, so don't use this +// when passing between threads! +// +// BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT +// +// base::Bind(&MyClass::Foo, base::Unretained(this)); +// +// This disables all lifetime management on the object. You're responsible +// for making sure the object is alive at the time of the call. You break it, +// you own it! +// +// BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS +// +// MyClass* myclass = new MyClass; +// base::Bind(&MyClass::Foo, base::Owned(myclass)); +// +// The object will be deleted when the callback is destroyed, even if it's +// not run (like if you post a task during shutdown). Potentially useful for +// "fire and forget" cases. +// +// IGNORING RETURN VALUES +// +// Sometimes you want to call a function that returns a value in a callback +// that doesn't expect a return value. +// +// int DoSomething(int arg) { cout << arg << endl; } +// base::Callback) cb = +// base::Bind(base::IgnoreResult(&DoSomething)); +// +// +// ----------------------------------------------------------------------------- +// Quick reference for binding parameters to Bind() +// ----------------------------------------------------------------------------- +// +// Bound parameters are specified as arguments to Bind() and are passed to the +// function. A callback with no parameters or no unbound parameters is called a +// Closure (base::Callback and base::Closure are the same thing). +// +// PASSING PARAMETERS OWNED BY THE CALLBACK +// +// void Foo(int* arg) { cout << *arg << endl; } +// int* pn = new int(1); +// base::Closure foo_callback = base::Bind(&foo, base::Owned(pn)); +// +// The parameter will be deleted when the callback is destroyed, even if it's +// not run (like if you post a task during shutdown). +// +// PASSING PARAMETERS AS A scoped_ptr +// +// void TakesOwnership(scoped_ptr arg) {} +// scoped_ptr f(new Foo); +// // f becomes null during the following call. +// base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f)); +// +// Ownership of the parameter will be with the callback until the it is run, +// when ownership is passed to the callback function. This means the callback +// can only be run once. If the callback is never run, it will delete the +// object when it's destroyed. +// +// PASSING PARAMETERS AS A scoped_refptr +// +// void TakesOneRef(scoped_refptr arg) {} +// scoped_refptr f(new Foo) +// base::Closure cb = base::Bind(&TakesOneRef, f); +// +// This should "just work." The closure will take a reference as long as it +// is alive, and another reference will be taken for the called function. +// +// PASSING PARAMETERS BY REFERENCE +// +// Const references are *copied* unless ConstRef is used. Example: +// +// void foo(const int& arg) { printf("%d %p\n", arg, &arg); } +// int n = 1; +// base::Closure has_copy = base::Bind(&foo, n); +// base::Closure has_ref = base::Bind(&foo, base::ConstRef(n)); +// n = 2; +// foo(n); // Prints "2 0xaaaaaaaaaaaa" +// has_copy.Run(); // Prints "1 0xbbbbbbbbbbbb" +// has_ref.Run(); // Prints "2 0xaaaaaaaaaaaa" +// +// Normally parameters are copied in the closure. DANGER: ConstRef stores a +// const reference instead, referencing the original parameter. This means +// that you must ensure the object outlives the callback! +// +// +// ----------------------------------------------------------------------------- +// Implementation notes +// ----------------------------------------------------------------------------- +// +// WHERE IS THIS DESIGN FROM: +// +// The design Callback and Bind is heavily influenced by C++'s +// tr1::function/tr1::bind, and by the "Google Callback" system used inside +// Google. +// +// +// HOW THE IMPLEMENTATION WORKS: +// +// There are three main components to the system: +// 1) The Callback classes. +// 2) The Bind() functions. +// 3) The arguments wrappers (e.g., Unretained() and ConstRef()). +// +// The Callback classes represent a generic function pointer. Internally, +// it stores a refcounted piece of state that represents the target function +// and all its bound parameters. Each Callback specialization has a templated +// constructor that takes an BindState<>*. In the context of the constructor, +// the static type of this BindState<> pointer uniquely identifies the +// function it is representing, all its bound parameters, and a Run() method +// that is capable of invoking the target. +// +// Callback's constructor takes the BindState<>* that has the full static type +// and erases the target function type as well as the types of the bound +// parameters. It does this by storing a pointer to the specific Run() +// function, and upcasting the state of BindState<>* to a +// BindStateBase*. This is safe as long as this BindStateBase pointer +// is only used with the stored Run() pointer. +// +// To BindState<> objects are created inside the Bind() functions. +// These functions, along with a set of internal templates, are responsible for +// +// - Unwrapping the function signature into return type, and parameters +// - Determining the number of parameters that are bound +// - Creating the BindState storing the bound parameters +// - Performing compile-time asserts to avoid error-prone behavior +// - Returning an Callback<> with an arity matching the number of unbound +// parameters and that knows the correct refcounting semantics for the +// target object if we are binding a method. +// +// The Bind functions do the above using type-inference, and template +// specializations. +// +// By default Bind() will store copies of all bound parameters, and attempt +// to refcount a target object if the function being bound is a class method. +// These copies are created even if the function takes parameters as const +// references. (Binding to non-const references is forbidden, see bind.h.) +// +// To change this behavior, we introduce a set of argument wrappers +// (e.g., Unretained(), and ConstRef()). These are simple container templates +// that are passed by value, and wrap a pointer to argument. See the +// file-level comment in base/bind_helpers.h for more info. +// +// These types are passed to the Unwrap() functions, and the MaybeRefcount() +// functions respectively to modify the behavior of Bind(). The Unwrap() +// and MaybeRefcount() functions change behavior by doing partial +// specialization based on whether or not a parameter is a wrapper type. +// +// ConstRef() is similar to tr1::cref. Unretained() is specific to Chromium. +// +// +// WHY NOT TR1 FUNCTION/BIND? +// +// Direct use of tr1::function and tr1::bind was considered, but ultimately +// rejected because of the number of copy constructors invocations involved +// in the binding of arguments during construction, and the forwarding of +// arguments during invocation. These copies will no longer be an issue in +// C++0x because C++0x will support rvalue reference allowing for the compiler +// to avoid these copies. However, waiting for C++0x is not an option. +// +// Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the +// tr1::bind call itself will invoke a non-trivial copy constructor three times +// for each bound parameter. Also, each when passing a tr1::function, each +// bound argument will be copied again. +// +// In addition to the copies taken at binding and invocation, copying a +// tr1::function causes a copy to be made of all the bound parameters and +// state. +// +// Furthermore, in Chromium, it is desirable for the Callback to take a +// reference on a target object when representing a class method call. This +// is not supported by tr1. +// +// Lastly, tr1::function and tr1::bind has a more general and flexible API. +// This includes things like argument reordering by use of +// tr1::bind::placeholder, support for non-const reference parameters, and some +// limited amount of subtyping of the tr1::function object (e.g., +// tr1::function is convertible to tr1::function). +// +// These are not features that are required in Chromium. Some of them, such as +// allowing for reference parameters, and subtyping of functions, may actually +// become a source of errors. Removing support for these features actually +// allows for a simpler implementation, and a terser Currying API. +// +// +// WHY NOT GOOGLE CALLBACKS? +// +// The Google callback system also does not support refcounting. Furthermore, +// its implementation has a number of strange edge cases with respect to type +// conversion of its arguments. In particular, the argument's constness must +// at times match exactly the function signature, or the type-inference might +// break. Given the above, writing a custom solution was easier. +// +// +// MISSING FUNCTIONALITY +// - Invoking the return of Bind. Bind(&foo).Run() does not work; +// - Binding arrays to functions that take a non-const pointer. +// Example: +// void Foo(const char* ptr); +// void Bar(char* ptr); +// Bind(&Foo, "test"); +// Bind(&Bar, "test"); // This fails because ptr is not const. + +namespace base { + +// First, we forward declare the Callback class template. This informs the +// compiler that the template only has 1 type parameter which is the function +// signature that the Callback is representing. +// +// After this, create template specializations for 0-7 parameters. Note that +// even though the template typelist grows, the specialization still +// only has one type: the function signature. +// +// If you are thinking of forward declaring Callback in your own header file, +// please include "base/callback_forward.h" instead. +template +class Callback; + +namespace cef_internal { +template +struct BindState; +} // namespace cef_internal + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run() const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get()); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1, A2); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1, A2, A3); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), + cef_internal::CallbackForward(a3)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1, A2, A3, A4); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), + cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1, A2, A3, A4, A5); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4, + typename cef_internal::CallbackParamTraits::ForwardType a5) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), + cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4), + cef_internal::CallbackForward(a5)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1, A2, A3, A4, A5, A6); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4, + typename cef_internal::CallbackParamTraits::ForwardType a5, + typename cef_internal::CallbackParamTraits::ForwardType a6) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), + cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4), + cef_internal::CallbackForward(a5), + cef_internal::CallbackForward(a6)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + +template +class Callback : public cef_internal::CallbackBase { + public: + typedef R(RunType)(A1, A2, A3, A4, A5, A6, A7); + + Callback() : CallbackBase(NULL) { } + + // Note that this constructor CANNOT be explicit, and that Bind() CANNOT + // return the exact Callback<> type. See base/bind.h for details. + template + Callback(cef_internal::BindState* bind_state) + : CallbackBase(bind_state) { + + // Force the assignment to a local variable of PolymorphicInvoke + // so the compiler will typecheck that the passed in Run() method has + // the correct type. + PolymorphicInvoke invoke_func = + &cef_internal::BindState + ::InvokerType::Run; + polymorphic_invoke_ = reinterpret_cast(invoke_func); + } + + bool Equals(const Callback& other) const { + return CallbackBase::Equals(other); + } + + R Run(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4, + typename cef_internal::CallbackParamTraits::ForwardType a5, + typename cef_internal::CallbackParamTraits::ForwardType a6, + typename cef_internal::CallbackParamTraits::ForwardType a7) const { + PolymorphicInvoke f = + reinterpret_cast(polymorphic_invoke_); + + return f(bind_state_.get(), cef_internal::CallbackForward(a1), + cef_internal::CallbackForward(a2), + cef_internal::CallbackForward(a3), + cef_internal::CallbackForward(a4), + cef_internal::CallbackForward(a5), + cef_internal::CallbackForward(a6), + cef_internal::CallbackForward(a7)); + } + + private: + typedef R(*PolymorphicInvoke)( + cef_internal::BindStateBase*, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType, + typename cef_internal::CallbackParamTraits::ForwardType); + +}; + + +// Syntactic sugar to make Callbacks easier to declare since it +// will be used in a lot of APIs with delayed execution. +typedef Callback Closure; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_CALLBACK_H_ diff --git a/include/base/cef_callback_forward.h b/include/base/cef_callback_forward.h new file mode 100644 index 000000000..4986b8f76 --- /dev/null +++ b/include/base/cef_callback_forward.h @@ -0,0 +1,59 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 INCLUDE_BASE_CEF_CALLBACK_FORWARD_H_ +#define INCLUDE_BASE_CEF_CALLBACK_FORWARD_H_ +#pragma once + +#if defined(BASE_CALLBACK_FORWARD_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/callback_forward.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +namespace base { + +template +class Callback; + +typedef Callback Closure; + +} // namespace base + +#endif // !!BUILDING_CEF_SHARED + +#endif // INCLUDE_BASE_CEF_CALLBACK_FORWARD_H_ diff --git a/include/base/cef_callback_helpers.h b/include/base/cef_callback_helpers.h new file mode 100644 index 000000000..62a0c8752 --- /dev/null +++ b/include/base/cef_callback_helpers.h @@ -0,0 +1,93 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// This defines helpful methods for dealing with Callbacks. Because Callbacks +// are implemented using templates, with a class per callback signature, adding +// methods to Callback<> itself is unattractive (lots of extra code gets +// generated). Instead, consider adding methods here. +// +// ResetAndReturn(&cb) is like cb.Reset() but allows executing a callback (via a +// copy) after the original callback is Reset(). This can be handy if Run() +// reads/writes the variable holding the Callback. + +#ifndef CEF_INCLUDE_BASE_CEF_CALLBACK_HELPERS_H_ +#define CEF_INCLUDE_BASE_CEF_CALLBACK_HELPERS_H_ +#pragma once + +#if defined(BASE_CALLBACK_HELPERS_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/callback_helpers.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_basictypes.h" +#include "include/base/cef_build.h" +#include "include/base/cef_callback.h" +#include "include/base/cef_macros.h" + +namespace base { + +template +base::Callback ResetAndReturn(base::Callback* cb) { + base::Callback ret(*cb); + cb->Reset(); + return ret; +} + +// ScopedClosureRunner is akin to scoped_ptr for Closures. It ensures that the +// Closure is executed and deleted no matter how the current scope exits. +class ScopedClosureRunner { + public: + ScopedClosureRunner(); + explicit ScopedClosureRunner(const Closure& closure); + ~ScopedClosureRunner(); + + void Reset(); + void Reset(const Closure& closure); + Closure Release() WARN_UNUSED_RESULT; + + private: + Closure closure_; + + DISALLOW_COPY_AND_ASSIGN(ScopedClosureRunner); +}; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_CALLBACK_HELPERS_H_ diff --git a/include/base/cef_callback_list.h b/include/base/cef_callback_list.h new file mode 100644 index 000000000..558b36f86 --- /dev/null +++ b/include/base/cef_callback_list.h @@ -0,0 +1,444 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2013 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_CALLBACK_LIST_H_ +#define CEF_INCLUDE_BASE_CEF_CALLBACK_LIST_H_ +#pragma once + +#if defined(BASE_CALLBACK_LIST_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/callback_list.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include + +#include "include/base/cef_basictypes.h" +#include "include/base/cef_callback.h" +#include "include/base/internal/cef_callback_internal.h" +#include "include/base/cef_build.h" +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/base/cef_scoped_ptr.h" + +// OVERVIEW: +// +// A container for a list of callbacks. Unlike a normal STL vector or list, +// this container can be modified during iteration without invalidating the +// iterator. It safely handles the case of a callback removing itself +// or another callback from the list while callbacks are being run. +// +// TYPICAL USAGE: +// +// class MyWidget { +// public: +// ... +// +// typedef base::Callback OnFooCallback; +// +// scoped_ptr::Subscription> +// RegisterCallback(const OnFooCallback& cb) { +// return callback_list_.Add(cb); +// } +// +// private: +// void NotifyFoo(const Foo& foo) { +// callback_list_.Notify(foo); +// } +// +// base::CallbackList callback_list_; +// +// DISALLOW_COPY_AND_ASSIGN(MyWidget); +// }; +// +// +// class MyWidgetListener { +// public: +// MyWidgetListener::MyWidgetListener() { +// foo_subscription_ = MyWidget::GetCurrent()->RegisterCallback( +// base::Bind(&MyWidgetListener::OnFoo, this))); +// } +// +// MyWidgetListener::~MyWidgetListener() { +// // Subscription gets deleted automatically and will deregister +// // the callback in the process. +// } +// +// private: +// void OnFoo(const Foo& foo) { +// // Do something. +// } +// +// scoped_ptr::Subscription> +// foo_subscription_; +// +// DISALLOW_COPY_AND_ASSIGN(MyWidgetListener); +// }; + +namespace base { + +namespace cef_internal { + +template +class CallbackListBase { + public: + class Subscription { + public: + Subscription(CallbackListBase* list, + typename std::list::iterator iter) + : list_(list), + iter_(iter) { + } + + ~Subscription() { + if (list_->active_iterator_count_) { + iter_->Reset(); + } else { + list_->callbacks_.erase(iter_); + if (!list_->removal_callback_.is_null()) + list_->removal_callback_.Run(); + } + } + + private: + CallbackListBase* list_; + typename std::list::iterator iter_; + + DISALLOW_COPY_AND_ASSIGN(Subscription); + }; + + // Add a callback to the list. The callback will remain registered until the + // returned Subscription is destroyed, which must occur before the + // CallbackList is destroyed. + scoped_ptr Add(const CallbackType& cb) WARN_UNUSED_RESULT { + DCHECK(!cb.is_null()); + return scoped_ptr( + new Subscription(this, callbacks_.insert(callbacks_.end(), cb))); + } + + // Sets a callback which will be run when a subscription list is changed. + void set_removal_callback(const Closure& callback) { + removal_callback_ = callback; + } + + // Returns true if there are no subscriptions. This is only valid to call when + // not looping through the list. + bool empty() { + DCHECK_EQ(0, active_iterator_count_); + return callbacks_.empty(); + } + + protected: + // An iterator class that can be used to access the list of callbacks. + class Iterator { + public: + explicit Iterator(CallbackListBase* list) + : list_(list), + list_iter_(list_->callbacks_.begin()) { + ++list_->active_iterator_count_; + } + + Iterator(const Iterator& iter) + : list_(iter.list_), + list_iter_(iter.list_iter_) { + ++list_->active_iterator_count_; + } + + ~Iterator() { + if (list_ && --list_->active_iterator_count_ == 0) { + list_->Compact(); + } + } + + CallbackType* GetNext() { + while ((list_iter_ != list_->callbacks_.end()) && list_iter_->is_null()) + ++list_iter_; + + CallbackType* cb = NULL; + if (list_iter_ != list_->callbacks_.end()) { + cb = &(*list_iter_); + ++list_iter_; + } + return cb; + } + + private: + CallbackListBase* list_; + typename std::list::iterator list_iter_; + }; + + CallbackListBase() : active_iterator_count_(0) {} + + ~CallbackListBase() { + DCHECK_EQ(0, active_iterator_count_); + DCHECK_EQ(0U, callbacks_.size()); + } + + // Returns an instance of a CallbackListBase::Iterator which can be used + // to run callbacks. + Iterator GetIterator() { + return Iterator(this); + } + + // Compact the list: remove any entries which were NULLed out during + // iteration. + void Compact() { + typename std::list::iterator it = callbacks_.begin(); + bool updated = false; + while (it != callbacks_.end()) { + if ((*it).is_null()) { + updated = true; + it = callbacks_.erase(it); + } else { + ++it; + } + + if (updated && !removal_callback_.is_null()) + removal_callback_.Run(); + } + } + + private: + std::list callbacks_; + int active_iterator_count_; + Closure removal_callback_; + + DISALLOW_COPY_AND_ASSIGN(CallbackListBase); +}; + +} // namespace cef_internal + +template class CallbackList; + +template <> +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify() { + cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1, a2); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1, a2, a3); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1, a2, a3, a4); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4, + typename cef_internal::CallbackParamTraits::ForwardType a5) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1, a2, a3, a4, a5); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4, + typename cef_internal::CallbackParamTraits::ForwardType a5, + typename cef_internal::CallbackParamTraits::ForwardType a6) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1, a2, a3, a4, a5, a6); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +template +class CallbackList + : public cef_internal::CallbackListBase > { + public: + typedef Callback CallbackType; + + CallbackList() {} + + void Notify(typename cef_internal::CallbackParamTraits::ForwardType a1, + typename cef_internal::CallbackParamTraits::ForwardType a2, + typename cef_internal::CallbackParamTraits::ForwardType a3, + typename cef_internal::CallbackParamTraits::ForwardType a4, + typename cef_internal::CallbackParamTraits::ForwardType a5, + typename cef_internal::CallbackParamTraits::ForwardType a6, + typename cef_internal::CallbackParamTraits::ForwardType a7) { + typename cef_internal::CallbackListBase::Iterator it = + this->GetIterator(); + CallbackType* cb; + while ((cb = it.GetNext()) != NULL) { + cb->Run(a1, a2, a3, a4, a5, a6, a7); + } + } + + private: + DISALLOW_COPY_AND_ASSIGN(CallbackList); +}; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_CALLBACK_LIST_H_ diff --git a/include/base/cef_cancelable_callback.h b/include/base/cef_cancelable_callback.h new file mode 100644 index 000000000..8ad3bf3bb --- /dev/null +++ b/include/base/cef_cancelable_callback.h @@ -0,0 +1,314 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// CancelableCallback is a wrapper around base::Callback that allows +// cancellation of a callback. CancelableCallback takes a reference on the +// wrapped callback until this object is destroyed or Reset()/Cancel() are +// called. +// +// NOTE: +// +// Calling CancelableCallback::Cancel() brings the object back to its natural, +// default-constructed state, i.e., CancelableCallback::callback() will return +// a null callback. +// +// THREAD-SAFETY: +// +// CancelableCallback objects must be created on, posted to, cancelled on, and +// destroyed on the same thread. +// +// +// EXAMPLE USAGE: +// +// In the following example, the test is verifying that RunIntensiveTest() +// Quit()s the message loop within 4 seconds. The cancelable callback is posted +// to the message loop, the intensive test runs, the message loop is run, +// then the callback is cancelled. +// +// void TimeoutCallback(const std::string& timeout_message) { +// FAIL() << timeout_message; +// MessageLoop::current()->QuitWhenIdle(); +// } +// +// CancelableClosure timeout(base::Bind(&TimeoutCallback, "Test timed out.")); +// MessageLoop::current()->PostDelayedTask(FROM_HERE, timeout.callback(), +// 4000) // 4 seconds to run. +// RunIntensiveTest(); +// MessageLoop::current()->Run(); +// timeout.Cancel(); // Hopefully this is hit before the timeout callback runs. +// + +#ifndef CEF_INCLUDE_BASE_CEF_CANCELABLE_CALLBACK_H_ +#define CEF_INCLUDE_BASE_CEF_CANCELABLE_CALLBACK_H_ +#pragma once + +#if defined(BASE_CANCELABLE_CALLBACK_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/cancelable_callback.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_bind.h" +#include "include/base/cef_callback.h" +#include "include/base/cef_build.h" +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/base/cef_weak_ptr.h" +#include "include/base/internal/cef_callback_internal.h" + +namespace base { + +template +class CancelableCallback; + +template <> +class CancelableCallback { + public: + CancelableCallback() : weak_factory_(this) {} + + // |callback| must not be null. + explicit CancelableCallback(const base::Callback& callback) + : weak_factory_(this), + callback_(callback) { + DCHECK(!callback.is_null()); + InitializeForwarder(); + } + + ~CancelableCallback() {} + + // Cancels and drops the reference to the wrapped callback. + void Cancel() { + weak_factory_.InvalidateWeakPtrs(); + forwarder_.Reset(); + callback_.Reset(); + } + + // Returns true if the wrapped callback has been cancelled. + bool IsCancelled() const { + return callback_.is_null(); + } + + // Sets |callback| as the closure that may be cancelled. |callback| may not + // be null. Outstanding and any previously wrapped callbacks are cancelled. + void Reset(const base::Callback& callback) { + DCHECK(!callback.is_null()); + + // Outstanding tasks (e.g., posted to a message loop) must not be called. + Cancel(); + + // |forwarder_| is no longer valid after Cancel(), so re-bind. + InitializeForwarder(); + + callback_ = callback; + } + + // Returns a callback that can be disabled by calling Cancel(). + const base::Callback& callback() const { + return forwarder_; + } + + private: + void Forward() { + callback_.Run(); + } + + // Helper method to bind |forwarder_| using a weak pointer from + // |weak_factory_|. + void InitializeForwarder() { + forwarder_ = base::Bind(&CancelableCallback::Forward, + weak_factory_.GetWeakPtr()); + } + + // Used to ensure Forward() is not run when this object is destroyed. + base::WeakPtrFactory > weak_factory_; + + // The wrapper closure. + base::Callback forwarder_; + + // The stored closure that may be cancelled. + base::Callback callback_; + + DISALLOW_COPY_AND_ASSIGN(CancelableCallback); +}; + +template +class CancelableCallback { + public: + CancelableCallback() : weak_factory_(this) {} + + // |callback| must not be null. + explicit CancelableCallback(const base::Callback& callback) + : weak_factory_(this), + callback_(callback) { + DCHECK(!callback.is_null()); + InitializeForwarder(); + } + + ~CancelableCallback() {} + + // Cancels and drops the reference to the wrapped callback. + void Cancel() { + weak_factory_.InvalidateWeakPtrs(); + forwarder_.Reset(); + callback_.Reset(); + } + + // Returns true if the wrapped callback has been cancelled. + bool IsCancelled() const { + return callback_.is_null(); + } + + // Sets |callback| as the closure that may be cancelled. |callback| may not + // be null. Outstanding and any previously wrapped callbacks are cancelled. + void Reset(const base::Callback& callback) { + DCHECK(!callback.is_null()); + + // Outstanding tasks (e.g., posted to a message loop) must not be called. + Cancel(); + + // |forwarder_| is no longer valid after Cancel(), so re-bind. + InitializeForwarder(); + + callback_ = callback; + } + + // Returns a callback that can be disabled by calling Cancel(). + const base::Callback& callback() const { + return forwarder_; + } + + private: + void Forward(A1 a1) const { + callback_.Run(a1); + } + + // Helper method to bind |forwarder_| using a weak pointer from + // |weak_factory_|. + void InitializeForwarder() { + forwarder_ = base::Bind(&CancelableCallback::Forward, + weak_factory_.GetWeakPtr()); + } + + // Used to ensure Forward() is not run when this object is destroyed. + base::WeakPtrFactory > weak_factory_; + + // The wrapper closure. + base::Callback forwarder_; + + // The stored closure that may be cancelled. + base::Callback callback_; + + DISALLOW_COPY_AND_ASSIGN(CancelableCallback); +}; + +template +class CancelableCallback { + public: + CancelableCallback() : weak_factory_(this) {} + + // |callback| must not be null. + explicit CancelableCallback(const base::Callback& callback) + : weak_factory_(this), + callback_(callback) { + DCHECK(!callback.is_null()); + InitializeForwarder(); + } + + ~CancelableCallback() {} + + // Cancels and drops the reference to the wrapped callback. + void Cancel() { + weak_factory_.InvalidateWeakPtrs(); + forwarder_.Reset(); + callback_.Reset(); + } + + // Returns true if the wrapped callback has been cancelled. + bool IsCancelled() const { + return callback_.is_null(); + } + + // Sets |callback| as the closure that may be cancelled. |callback| may not + // be null. Outstanding and any previously wrapped callbacks are cancelled. + void Reset(const base::Callback& callback) { + DCHECK(!callback.is_null()); + + // Outstanding tasks (e.g., posted to a message loop) must not be called. + Cancel(); + + // |forwarder_| is no longer valid after Cancel(), so re-bind. + InitializeForwarder(); + + callback_ = callback; + } + + // Returns a callback that can be disabled by calling Cancel(). + const base::Callback& callback() const { + return forwarder_; + } + + private: + void Forward(A1 a1, A2 a2) const { + callback_.Run(a1, a2); + } + + // Helper method to bind |forwarder_| using a weak pointer from + // |weak_factory_|. + void InitializeForwarder() { + forwarder_ = base::Bind(&CancelableCallback::Forward, + weak_factory_.GetWeakPtr()); + } + + // Used to ensure Forward() is not run when this object is destroyed. + base::WeakPtrFactory > weak_factory_; + + // The wrapper closure. + base::Callback forwarder_; + + // The stored closure that may be cancelled. + base::Callback callback_; + + DISALLOW_COPY_AND_ASSIGN(CancelableCallback); +}; + +typedef CancelableCallback CancelableClosure; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_CANCELABLE_CALLBACK_H_ diff --git a/include/base/cef_lock.h b/include/base/cef_lock.h new file mode 100644 index 000000000..febcc9a96 --- /dev/null +++ b/include/base/cef_lock.h @@ -0,0 +1,167 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_LOCK_H_ +#define CEF_INCLUDE_BASE_CEF_LOCK_H_ +#pragma once + +#if defined(BASE_SYNCHRONIZATION_LOCK_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/synchronization/lock.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_macros.h" +#include "include/base/cef_platform_thread.h" +#include "include/base/internal/cef_lock_impl.h" + +namespace base { + +// A convenient wrapper for an OS specific critical section. The only real +// intelligence in this class is in debug mode for the support for the +// AssertAcquired() method. +class Lock { + public: +#if defined(NDEBUG) // Optimized wrapper implementation + Lock() : lock_() {} + ~Lock() {} + void Acquire() { lock_.Lock(); } + void Release() { lock_.Unlock(); } + + // If the lock is not held, take it and return true. If the lock is already + // held by another thread, immediately return false. This must not be called + // by a thread already holding the lock (what happens is undefined and an + // assertion may fail). + bool Try() { return lock_.Try(); } + + // Null implementation if not debug. + void AssertAcquired() const {} +#else + Lock(); + ~Lock(); + + // NOTE: Although windows critical sections support recursive locks, we do not + // allow this, and we will commonly fire a DCHECK() if a thread attempts to + // acquire the lock a second time (while already holding it). + void Acquire() { + lock_.Lock(); + CheckUnheldAndMark(); + } + void Release() { + CheckHeldAndUnmark(); + lock_.Unlock(); + } + + bool Try() { + bool rv = lock_.Try(); + if (rv) { + CheckUnheldAndMark(); + } + return rv; + } + + void AssertAcquired() const; +#endif // NDEBUG + + private: +#if !defined(NDEBUG) + // Members and routines taking care of locks assertions. + // Note that this checks for recursive locks and allows them + // if the variable is set. This is allowed by the underlying implementation + // on windows but not on Posix, so we're doing unneeded checks on Posix. + // It's worth it to share the code. + void CheckHeldAndUnmark(); + void CheckUnheldAndMark(); + + // All private data is implicitly protected by lock_. + // Be VERY careful to only access members under that lock. + base::PlatformThreadRef owning_thread_ref_; +#endif // NDEBUG + + // Platform specific underlying lock implementation. + cef_internal::LockImpl lock_; + + DISALLOW_COPY_AND_ASSIGN(Lock); +}; + +// A helper class that acquires the given Lock while the AutoLock is in scope. +class AutoLock { + public: + struct AlreadyAcquired {}; + + explicit AutoLock(Lock& lock) : lock_(lock) { + lock_.Acquire(); + } + + AutoLock(Lock& lock, const AlreadyAcquired&) : lock_(lock) { + lock_.AssertAcquired(); + } + + ~AutoLock() { + lock_.AssertAcquired(); + lock_.Release(); + } + + private: + Lock& lock_; + DISALLOW_COPY_AND_ASSIGN(AutoLock); +}; + +// AutoUnlock is a helper that will Release() the |lock| argument in the +// constructor, and re-Acquire() it in the destructor. +class AutoUnlock { + public: + explicit AutoUnlock(Lock& lock) : lock_(lock) { + // We require our caller to have the lock. + lock_.AssertAcquired(); + lock_.Release(); + } + + ~AutoUnlock() { + lock_.Acquire(); + } + + private: + Lock& lock_; + DISALLOW_COPY_AND_ASSIGN(AutoUnlock); +}; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_LOCK_H_ diff --git a/include/base/cef_logging.h b/include/base/cef_logging.h new file mode 100644 index 000000000..b3951f12e --- /dev/null +++ b/include/base/cef_logging.h @@ -0,0 +1,746 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// +// WARNING: Logging macros should not be used in the main/browser process before +// calling CefInitialize or in sub-processes before calling CefExecuteProcess. +// +// Instructions +// ------------ +// +// Make a bunch of macros for logging. The way to log things is to stream +// things to LOG(). E.g., +// +// LOG(INFO) << "Found " << num_cookies << " cookies"; +// +// You can also do conditional logging: +// +// LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; +// +// The CHECK(condition) macro is active in both debug and release builds and +// effectively performs a LOG(FATAL) which terminates the process and +// generates a crashdump unless a debugger is attached. +// +// There are also "debug mode" logging macros like the ones above: +// +// DLOG(INFO) << "Found cookies"; +// +// DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies"; +// +// All "debug mode" logging is compiled away to nothing for non-debug mode +// compiles. LOG_IF and development flags also work well together +// because the code can be compiled away sometimes. +// +// We also have +// +// LOG_ASSERT(assertion); +// DLOG_ASSERT(assertion); +// +// which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion; +// +// There are "verbose level" logging macros. They look like +// +// VLOG(1) << "I'm printed when you run the program with --v=1 or more"; +// VLOG(2) << "I'm printed when you run the program with --v=2 or more"; +// +// These always log at the INFO log level (when they log at all). +// The verbose logging can also be turned on module-by-module. For instance, +// --vmodule=profile=2,icon_loader=1,browser_*=3,*/chromeos/*=4 --v=0 +// will cause: +// a. VLOG(2) and lower messages to be printed from profile.{h,cc} +// b. VLOG(1) and lower messages to be printed from icon_loader.{h,cc} +// c. VLOG(3) and lower messages to be printed from files prefixed with +// "browser" +// d. VLOG(4) and lower messages to be printed from files under a +// "chromeos" directory. +// e. VLOG(0) and lower messages to be printed from elsewhere +// +// The wildcarding functionality shown by (c) supports both '*' (match +// 0 or more characters) and '?' (match any single character) +// wildcards. Any pattern containing a forward or backward slash will +// be tested against the whole pathname and not just the module. +// E.g., "*/foo/bar/*=2" would change the logging level for all code +// in source files under a "foo/bar" directory. +// +// There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as +// +// if (VLOG_IS_ON(2)) { +// // do some logging preparation and logging +// // that can't be accomplished with just VLOG(2) << ...; +// } +// +// There is also a VLOG_IF "verbose level" condition macro for sample +// cases, when some extra computation and preparation for logs is not +// needed. +// +// VLOG_IF(1, (size > 1024)) +// << "I'm printed when size is more than 1024 and when you run the " +// "program with --v=1 or more"; +// +// We also override the standard 'assert' to use 'DLOG_ASSERT'. +// +// Lastly, there is: +// +// PLOG(ERROR) << "Couldn't do foo"; +// DPLOG(ERROR) << "Couldn't do foo"; +// PLOG_IF(ERROR, cond) << "Couldn't do foo"; +// DPLOG_IF(ERROR, cond) << "Couldn't do foo"; +// PCHECK(condition) << "Couldn't do foo"; +// DPCHECK(condition) << "Couldn't do foo"; +// +// which append the last system error to the message in string form (taken from +// GetLastError() on Windows and errno on POSIX). +// +// The supported severity levels for macros that allow you to specify one +// are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL. +// +// Very important: logging a message at the FATAL severity level causes +// the program to terminate (after the message is logged). +// +// There is the special severity of DFATAL, which logs FATAL in debug mode, +// ERROR in normal mode. +// + +#ifndef CEF_INCLUDE_BASE_CEF_LOGGING_H_ +#define CEF_INCLUDE_BASE_CEF_LOGGING_H_ +#pragma once + +#if defined(DCHECK) +// Do nothing if the macros provided by this header already exist. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/logging.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include +#include +#include +#include + +#include "include/base/cef_build.h" +#include "include/base/cef_macros.h" +#include "include/internal/cef_logging_internal.h" + +namespace cef { +namespace logging { + +// Gets the current log level. +inline int GetMinLogLevel() { + return cef_get_min_log_level(); +} + +// Gets the current vlog level for the given file (usually taken from +// __FILE__). Note that |N| is the size *with* the null terminator. +template +int GetVlogLevel(const char (&file)[N]) { + return cef_get_vlog_level(file, N); +} + +typedef int LogSeverity; +const LogSeverity LOG_VERBOSE = -1; // This is level 1 verbosity +// Note: the log severities are used to index into the array of names, +// see log_severity_names. +const LogSeverity LOG_INFO = 0; +const LogSeverity LOG_WARNING = 1; +const LogSeverity LOG_ERROR = 2; +const LogSeverity LOG_FATAL = 3; +const LogSeverity LOG_NUM_SEVERITIES = 4; + +// LOG_DFATAL is LOG_FATAL in debug mode, ERROR in normal mode +#ifdef NDEBUG +const LogSeverity LOG_DFATAL = LOG_ERROR; +#else +const LogSeverity LOG_DFATAL = LOG_FATAL; +#endif + +// A few definitions of macros that don't generate much code. These are used +// by LOG() and LOG_IF, etc. Since these are used all over our code, it's +// better to have compact code for these operations. +#define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_INFO , \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_WARNING , \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_ERROR , \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_FATAL , \ + ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \ + cef::logging::ClassName(__FILE__, __LINE__, cef::logging::LOG_DFATAL , \ + ##__VA_ARGS__) + +#define COMPACT_GOOGLE_LOG_INFO \ + COMPACT_GOOGLE_LOG_EX_INFO(LogMessage) +#define COMPACT_GOOGLE_LOG_WARNING \ + COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage) +#define COMPACT_GOOGLE_LOG_ERROR \ + COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage) +#define COMPACT_GOOGLE_LOG_FATAL \ + COMPACT_GOOGLE_LOG_EX_FATAL(LogMessage) +#define COMPACT_GOOGLE_LOG_DFATAL \ + COMPACT_GOOGLE_LOG_EX_DFATAL(LogMessage) + +#if defined(OS_WIN) +// wingdi.h defines ERROR to be 0. When we call LOG(ERROR), it gets +// substituted with 0, and it expands to COMPACT_GOOGLE_LOG_0. To allow us +// to keep using this syntax, we define this macro to do the same thing +// as COMPACT_GOOGLE_LOG_ERROR, and also define ERROR the same way that +// the Windows SDK does for consistency. +#define ERROR 0 +#define COMPACT_GOOGLE_LOG_EX_0(ClassName, ...) \ + COMPACT_GOOGLE_LOG_EX_ERROR(ClassName , ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_0 COMPACT_GOOGLE_LOG_ERROR +// Needed for LOG_IS_ON(ERROR). +const LogSeverity LOG_0 = LOG_ERROR; +#endif + +// As special cases, we can assume that LOG_IS_ON(FATAL) always holds. Also, +// LOG_IS_ON(DFATAL) always holds in debug mode. In particular, CHECK()s will +// always fire if they fail. +#define LOG_IS_ON(severity) \ + ((::cef::logging::LOG_ ## severity) >= ::cef::logging::GetMinLogLevel()) + +// We can't do any caching tricks with VLOG_IS_ON() like the +// google-glog version since it requires GCC extensions. This means +// that using the v-logging functions in conjunction with --vmodule +// may be slow. +#define VLOG_IS_ON(verboselevel) \ + ((verboselevel) <= ::cef::logging::GetVlogLevel(__FILE__)) + +// Helper macro which avoids evaluating the arguments to a stream if +// the condition doesn't hold. +#define LAZY_STREAM(stream, condition) \ + !(condition) ? (void) 0 : ::cef::logging::LogMessageVoidify() & (stream) + +// We use the preprocessor's merging operator, "##", so that, e.g., +// LOG(INFO) becomes the token COMPACT_GOOGLE_LOG_INFO. There's some funny +// subtle difference between ostream member streaming functions (e.g., +// ostream::operator<<(int) and ostream non-member streaming functions +// (e.g., ::operator<<(ostream&, string&): it turns out that it's +// impossible to stream something like a string directly to an unnamed +// ostream. We employ a neat hack by calling the stream() member +// function of LogMessage which seems to avoid the problem. +#define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream() + +#define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity)) +#define LOG_IF(severity, condition) \ + LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition)) + +#define SYSLOG(severity) LOG(severity) +#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition) + +// The VLOG macros log with negative verbosities. +#define VLOG_STREAM(verbose_level) \ + cef::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream() + +#define VLOG(verbose_level) \ + LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level)) + +#define VLOG_IF(verbose_level, condition) \ + LAZY_STREAM(VLOG_STREAM(verbose_level), \ + VLOG_IS_ON(verbose_level) && (condition)) + +#if defined (OS_WIN) +#define VPLOG_STREAM(verbose_level) \ + cef::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \ + ::cef::logging::GetLastSystemErrorCode()).stream() +#elif defined(OS_POSIX) +#define VPLOG_STREAM(verbose_level) \ + cef::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \ + ::cef::logging::GetLastSystemErrorCode()).stream() +#endif + +#define VPLOG(verbose_level) \ + LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level)) + +#define VPLOG_IF(verbose_level, condition) \ + LAZY_STREAM(VPLOG_STREAM(verbose_level), \ + VLOG_IS_ON(verbose_level) && (condition)) + +// TODO(akalin): Add more VLOG variants, e.g. VPLOG. + +#define LOG_ASSERT(condition) \ + LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " +#define SYSLOG_ASSERT(condition) \ + SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". " + +#if defined(OS_WIN) +#define PLOG_STREAM(severity) \ + COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \ + ::cef::logging::GetLastSystemErrorCode()).stream() +#elif defined(OS_POSIX) +#define PLOG_STREAM(severity) \ + COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \ + ::cef::logging::GetLastSystemErrorCode()).stream() +#endif + +#define PLOG(severity) \ + LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity)) + +#define PLOG_IF(severity, condition) \ + LAZY_STREAM(PLOG_STREAM(severity), LOG_IS_ON(severity) && (condition)) + +// The actual stream used isn't important. +#define EAT_STREAM_PARAMETERS \ + true ? (void) 0 : ::cef::logging::LogMessageVoidify() & LOG_STREAM(FATAL) + +// CHECK dies with a fatal error if condition is not true. It is *not* +// controlled by NDEBUG, so the check will be executed regardless of +// compilation mode. +// +// We make sure CHECK et al. always evaluates their arguments, as +// doing CHECK(FunctionWithSideEffect()) is a common idiom. + +#define CHECK(condition) \ + LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \ + << "Check failed: " #condition ". " + +#define PCHECK(condition) \ + LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \ + << "Check failed: " #condition ". " + +// Helper macro for binary operators. +// Don't use this macro directly in your code, use CHECK_EQ et al below. +// +// TODO(akalin): Rewrite this so that constructs like if (...) +// CHECK_EQ(...) else { ... } work properly. +#define CHECK_OP(name, op, val1, val2) \ + if (std::string* _result = \ + cef::logging::Check##name##Impl((val1), (val2), \ + #val1 " " #op " " #val2)) \ + cef::logging::LogMessage(__FILE__, __LINE__, _result).stream() + +// Build the error message string. This is separate from the "Impl" +// function template because it is not performance critical and so can +// be out of line, while the "Impl" code should be inline. Caller +// takes ownership of the returned string. +template +std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { + std::ostringstream ss; + ss << names << " (" << v1 << " vs. " << v2 << ")"; + std::string* msg = new std::string(ss.str()); + return msg; +} + +// MSVC doesn't like complex extern templates and DLLs. +#if !defined(COMPILER_MSVC) +// Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated +// in logging.cc. +extern template std::string* MakeCheckOpString( + const int&, const int&, const char* names); +extern template +std::string* MakeCheckOpString( + const unsigned long&, const unsigned long&, const char* names); +extern template +std::string* MakeCheckOpString( + const unsigned long&, const unsigned int&, const char* names); +extern template +std::string* MakeCheckOpString( + const unsigned int&, const unsigned long&, const char* names); +extern template +std::string* MakeCheckOpString( + const std::string&, const std::string&, const char* name); +#endif + +// Helper functions for CHECK_OP macro. +// The (int, int) specialization works around the issue that the compiler +// will not instantiate the template version of the function on values of +// unnamed enum type - see comment below. +#define DEFINE_CHECK_OP_IMPL(name, op) \ + template \ + inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \ + const char* names) { \ + if (v1 op v2) return NULL; \ + else return MakeCheckOpString(v1, v2, names); \ + } \ + inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \ + if (v1 op v2) return NULL; \ + else return MakeCheckOpString(v1, v2, names); \ + } +DEFINE_CHECK_OP_IMPL(EQ, ==) +DEFINE_CHECK_OP_IMPL(NE, !=) +DEFINE_CHECK_OP_IMPL(LE, <=) +DEFINE_CHECK_OP_IMPL(LT, < ) +DEFINE_CHECK_OP_IMPL(GE, >=) +DEFINE_CHECK_OP_IMPL(GT, > ) +#undef DEFINE_CHECK_OP_IMPL + +#define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2) +#define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2) +#define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2) +#define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2) +#define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2) +#define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2) + +#if defined(NDEBUG) +#define ENABLE_DLOG 0 +#else +#define ENABLE_DLOG 1 +#endif + +#if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON) +#define DCHECK_IS_ON 0 +#else +#define DCHECK_IS_ON 1 +#endif + +// Definitions for DLOG et al. + +#if ENABLE_DLOG + +#define DLOG_IS_ON(severity) LOG_IS_ON(severity) +#define DLOG_IF(severity, condition) LOG_IF(severity, condition) +#define DLOG_ASSERT(condition) LOG_ASSERT(condition) +#define DPLOG_IF(severity, condition) PLOG_IF(severity, condition) +#define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition) +#define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition) + +#else // ENABLE_DLOG + +// If ENABLE_DLOG is off, we want to avoid emitting any references to +// |condition| (which may reference a variable defined only if NDEBUG +// is not defined). Contrast this with DCHECK et al., which has +// different behavior. + +#define DLOG_IS_ON(severity) false +#define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS +#define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS +#define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS +#define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS +#define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS + +#endif // ENABLE_DLOG + +// DEBUG_MODE is for uses like +// if (DEBUG_MODE) foo.CheckThatFoo(); +// instead of +// #ifndef NDEBUG +// foo.CheckThatFoo(); +// #endif +// +// We tie its state to ENABLE_DLOG. +enum { DEBUG_MODE = ENABLE_DLOG }; + +#undef ENABLE_DLOG + +#define DLOG(severity) \ + LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity)) + +#define DPLOG(severity) \ + LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity)) + +#define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel)) + +#define DVPLOG(verboselevel) DVPLOG_IF(verboselevel, VLOG_IS_ON(verboselevel)) + +// Definitions for DCHECK et al. + +#if DCHECK_IS_ON + +#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ + COMPACT_GOOGLE_LOG_EX_FATAL(ClassName , ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_FATAL +const LogSeverity LOG_DCHECK = LOG_FATAL; + +#else // DCHECK_IS_ON + +// These are just dummy values. +#define COMPACT_GOOGLE_LOG_EX_DCHECK(ClassName, ...) \ + COMPACT_GOOGLE_LOG_EX_INFO(ClassName , ##__VA_ARGS__) +#define COMPACT_GOOGLE_LOG_DCHECK COMPACT_GOOGLE_LOG_INFO +const LogSeverity LOG_DCHECK = LOG_INFO; + +#endif // DCHECK_IS_ON + +// DCHECK et al. make sure to reference |condition| regardless of +// whether DCHECKs are enabled; this is so that we don't get unused +// variable warnings if the only use of a variable is in a DCHECK. +// This behavior is different from DLOG_IF et al. + +#define DCHECK(condition) \ + LAZY_STREAM(LOG_STREAM(DCHECK), DCHECK_IS_ON && !(condition)) \ + << "Check failed: " #condition ". " + +#define DPCHECK(condition) \ + LAZY_STREAM(PLOG_STREAM(DCHECK), DCHECK_IS_ON && !(condition)) \ + << "Check failed: " #condition ". " + +// Helper macro for binary operators. +// Don't use this macro directly in your code, use DCHECK_EQ et al below. +#define DCHECK_OP(name, op, val1, val2) \ + if (DCHECK_IS_ON) \ + if (std::string* _result = \ + cef::logging::Check##name##Impl((val1), (val2), \ + #val1 " " #op " " #val2)) \ + cef::logging::LogMessage( \ + __FILE__, __LINE__, ::cef::logging::LOG_DCHECK, \ + _result).stream() + +// Equality/Inequality checks - compare two values, and log a +// LOG_DCHECK message including the two values when the result is not +// as expected. The values must have operator<<(ostream, ...) +// defined. +// +// You may append to the error message like so: +// DCHECK_NE(1, 2) << ": The world must be ending!"; +// +// We are very careful to ensure that each argument is evaluated exactly +// once, and that anything which is legal to pass as a function argument is +// legal here. In particular, the arguments may be temporary expressions +// which will end up being destroyed at the end of the apparent statement, +// for example: +// DCHECK_EQ(string("abc")[1], 'b'); +// +// WARNING: These may not compile correctly if one of the arguments is a pointer +// and the other is NULL. To work around this, simply static_cast NULL to the +// type of the desired pointer. + +#define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2) +#define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2) +#define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2) +#define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2) +#define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2) +#define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2) + +#if defined(NDEBUG) && defined(OS_CHROMEOS) +#define NOTREACHED() LOG(ERROR) << "NOTREACHED() hit in " << \ + __FUNCTION__ << ". " +#else +#define NOTREACHED() DCHECK(false) +#endif + +// Redefine the standard assert to use our nice log files +#undef assert +#define assert(x) DLOG_ASSERT(x) + +// This class more or less represents a particular log message. You +// create an instance of LogMessage and then stream stuff to it. +// When you finish streaming to it, ~LogMessage is called and the +// full message gets streamed to the appropriate destination. +// +// You shouldn't actually use LogMessage's constructor to log things, +// though. You should use the LOG() macro (and variants thereof) +// above. +class LogMessage { + public: + // Used for LOG(severity). + LogMessage(const char* file, int line, LogSeverity severity); + + // Used for CHECK_EQ(), etc. Takes ownership of the given string. + // Implied severity = LOG_FATAL. + LogMessage(const char* file, int line, std::string* result); + + // Used for DCHECK_EQ(), etc. Takes ownership of the given string. + LogMessage(const char* file, int line, LogSeverity severity, + std::string* result); + + ~LogMessage(); + + std::ostream& stream() { return stream_; } + + private: + LogSeverity severity_; + std::ostringstream stream_; + + // The file and line information passed in to the constructor. + const char* file_; + const int line_; + +#if defined(OS_WIN) + // Stores the current value of GetLastError in the constructor and restores + // it in the destructor by calling SetLastError. + // This is useful since the LogMessage class uses a lot of Win32 calls + // that will lose the value of GLE and the code that called the log function + // will have lost the thread error value when the log call returns. + class SaveLastError { + public: + SaveLastError(); + ~SaveLastError(); + + unsigned long get_error() const { return last_error_; } + + protected: + unsigned long last_error_; + }; + + SaveLastError last_error_; +#endif + + DISALLOW_COPY_AND_ASSIGN(LogMessage); +}; + +// A non-macro interface to the log facility; (useful +// when the logging level is not a compile-time constant). +inline void LogAtLevel(int const log_level, std::string const &msg) { + LogMessage(__FILE__, __LINE__, log_level).stream() << msg; +} + +// This class is used to explicitly ignore values in the conditional +// logging macros. This avoids compiler warnings like "value computed +// is not used" and "statement has no effect". +class LogMessageVoidify { + public: + LogMessageVoidify() { } + // This has to be an operator with a precedence lower than << but + // higher than ?: + void operator&(std::ostream&) { } +}; + +#if defined(OS_WIN) +typedef unsigned long SystemErrorCode; +#elif defined(OS_POSIX) +typedef int SystemErrorCode; +#endif + +// Alias for ::GetLastError() on Windows and errno on POSIX. Avoids having to +// pull in windows.h just for GetLastError() and DWORD. +SystemErrorCode GetLastSystemErrorCode(); +std::string SystemErrorCodeToString(SystemErrorCode error_code); + +#if defined(OS_WIN) +// Appends a formatted system message of the GetLastError() type. +class Win32ErrorLogMessage { + public: + Win32ErrorLogMessage(const char* file, + int line, + LogSeverity severity, + SystemErrorCode err); + + // Appends the error message before destructing the encapsulated class. + ~Win32ErrorLogMessage(); + + std::ostream& stream() { return log_message_.stream(); } + + private: + SystemErrorCode err_; + LogMessage log_message_; + + DISALLOW_COPY_AND_ASSIGN(Win32ErrorLogMessage); +}; +#elif defined(OS_POSIX) +// Appends a formatted system message of the errno type +class ErrnoLogMessage { + public: + ErrnoLogMessage(const char* file, + int line, + LogSeverity severity, + SystemErrorCode err); + + // Appends the error message before destructing the encapsulated class. + ~ErrnoLogMessage(); + + std::ostream& stream() { return log_message_.stream(); } + + private: + SystemErrorCode err_; + LogMessage log_message_; + + DISALLOW_COPY_AND_ASSIGN(ErrnoLogMessage); +}; +#endif // OS_WIN + +} // namespace logging +} // namespace cef + +// These functions are provided as a convenience for logging, which is where we +// use streams (it is against Google style to use streams in other places). It +// is designed to allow you to emit non-ASCII Unicode strings to the log file, +// which is normally ASCII. It is relatively slow, so try not to use it for +// common cases. Non-ASCII characters will be converted to UTF-8 by these +// operators. +std::ostream& operator<<(std::ostream& out, const wchar_t* wstr); +inline std::ostream& operator<<(std::ostream& out, const std::wstring& wstr) { + return out << wstr.c_str(); +} + +// The NOTIMPLEMENTED() macro annotates codepaths which have +// not been implemented yet. +// +// The implementation of this macro is controlled by NOTIMPLEMENTED_POLICY: +// 0 -- Do nothing (stripped by compiler) +// 1 -- Warn at compile time +// 2 -- Fail at compile time +// 3 -- Fail at runtime (DCHECK) +// 4 -- [default] LOG(ERROR) at runtime +// 5 -- LOG(ERROR) at runtime, only once per call-site + +#ifndef NOTIMPLEMENTED_POLICY +#if defined(OS_ANDROID) && defined(OFFICIAL_BUILD) +#define NOTIMPLEMENTED_POLICY 0 +#else +// Select default policy: LOG(ERROR) +#define NOTIMPLEMENTED_POLICY 4 +#endif +#endif + +#if defined(COMPILER_GCC) +// On Linux, with GCC, we can use __PRETTY_FUNCTION__ to get the demangled name +// of the current function in the NOTIMPLEMENTED message. +#define NOTIMPLEMENTED_MSG "Not implemented reached in " << __PRETTY_FUNCTION__ +#else +#define NOTIMPLEMENTED_MSG "NOT IMPLEMENTED" +#endif + +#if NOTIMPLEMENTED_POLICY == 0 +#define NOTIMPLEMENTED() EAT_STREAM_PARAMETERS +#elif NOTIMPLEMENTED_POLICY == 1 +// TODO, figure out how to generate a warning +#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED) +#elif NOTIMPLEMENTED_POLICY == 2 +#define NOTIMPLEMENTED() COMPILE_ASSERT(false, NOT_IMPLEMENTED) +#elif NOTIMPLEMENTED_POLICY == 3 +#define NOTIMPLEMENTED() NOTREACHED() +#elif NOTIMPLEMENTED_POLICY == 4 +#define NOTIMPLEMENTED() LOG(ERROR) << NOTIMPLEMENTED_MSG +#elif NOTIMPLEMENTED_POLICY == 5 +#define NOTIMPLEMENTED() do {\ + static bool logged_once = false;\ + LOG_IF(ERROR, !logged_once) << NOTIMPLEMENTED_MSG;\ + logged_once = true;\ +} while(0);\ +EAT_STREAM_PARAMETERS +#endif + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_LOGGING_H_ diff --git a/include/base/cef_macros.h b/include/base/cef_macros.h new file mode 100644 index 000000000..83f0af941 --- /dev/null +++ b/include/base/cef_macros.h @@ -0,0 +1,218 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_MACROS_H_ +#define CEF_INCLUDE_BASE_CEF_MACROS_H_ +#pragma once + +#if defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/macros.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include // For size_t. + +#if !defined(ALLOW_THIS_IN_INITIALIZER_LIST) +#if defined(COMPILER_MSVC) + +// MSVC_PUSH_DISABLE_WARNING pushes |n| onto a stack of warnings to be disabled. +// The warning remains disabled until popped by MSVC_POP_WARNING. +#define MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \ + __pragma(warning(disable:n)) + +// MSVC_PUSH_WARNING_LEVEL pushes |n| as the global warning level. The level +// remains in effect until popped by MSVC_POP_WARNING(). Use 0 to disable all +// warnings. +#define MSVC_PUSH_WARNING_LEVEL(n) __pragma(warning(push, n)) + +// Pop effects of innermost MSVC_PUSH_* macro. +#define MSVC_POP_WARNING() __pragma(warning(pop)) + +// Allows |this| to be passed as an argument in constructor initializer lists. +// This uses push/pop instead of the seemingly simpler suppress feature to avoid +// having the warning be disabled for more than just |code|. +// +// Example usage: +// Foo::Foo() : x(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(y(this)), z(3) {} +// +// Compiler warning C4355: 'this': used in base member initializer list: +// http://msdn.microsoft.com/en-us/library/3c594ae3(VS.80).aspx +#define ALLOW_THIS_IN_INITIALIZER_LIST(code) MSVC_PUSH_DISABLE_WARNING(4355) \ + code \ + MSVC_POP_WARNING() +#else // !COMPILER_MSVC + +#define ALLOW_THIS_IN_INITIALIZER_LIST(code) code + +#endif // !COMPILER_MSVC +#endif // !ALLOW_THIS_IN_INITIALIZER_LIST + +#if !defined(arraysize) + +// The arraysize(arr) macro returns the # of elements in an array arr. +// The expression is a compile-time constant, and therefore can be +// used in defining new arrays, for example. If you use arraysize on +// a pointer by mistake, you will get a compile-time error. +// +// One caveat is that arraysize() doesn't accept any array of an +// anonymous type or a type defined inside a function. In these rare +// cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is +// due to a limitation in C++'s template system. The limitation might +// eventually be removed, but it hasn't happened yet. + +// This template function declaration is used in defining arraysize. +// Note that the function doesn't need an implementation, as we only +// use its type. +template +char (&ArraySizeHelper(T (&array)[N]))[N]; + +// That gcc wants both of these prototypes seems mysterious. VC, for +// its part, can't decide which to use (another mystery). Matching of +// template overloads: the final frontier. +#ifndef _MSC_VER +template +char (&ArraySizeHelper(const T (&array)[N]))[N]; +#endif + +#define arraysize(array) (sizeof(ArraySizeHelper(array))) + +#endif // !arraysize + +#if !defined(DISALLOW_COPY_AND_ASSIGN) + +// A macro to disallow the copy constructor and operator= functions +// This should be used in the private: declarations for a class +#define DISALLOW_COPY_AND_ASSIGN(TypeName) \ + TypeName(const TypeName&); \ + void operator=(const TypeName&) + +#endif // !DISALLOW_COPY_AND_ASSIGN + +#if !defined(DISALLOW_IMPLICIT_CONSTRUCTORS) + +// A macro to disallow all the implicit constructors, namely the +// default constructor, copy constructor and operator= functions. +// +// This should be used in the private: declarations for a class +// that wants to prevent anyone from instantiating it. This is +// especially useful for classes containing only static methods. +#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \ + TypeName(); \ + DISALLOW_COPY_AND_ASSIGN(TypeName) + +#endif // !DISALLOW_IMPLICIT_CONSTRUCTORS + +#if !defined(COMPILE_ASSERT) + +// The COMPILE_ASSERT macro can be used to verify that a compile time +// expression is true. For example, you could use it to verify the +// size of a static array: +// +// COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES, +// content_type_names_incorrect_size); +// +// or to make sure a struct is smaller than a certain size: +// +// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); +// +// The second argument to the macro is the name of the variable. If +// the expression is false, most compilers will issue a warning/error +// containing the name of the variable. + +#if __cplusplus >= 201103L + +// Under C++11, just use static_assert. +#define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg) + +#else + +namespace cef { + +template +struct CompileAssert { +}; + +} // namespace cef + +#define COMPILE_ASSERT(expr, msg) \ + typedef cef::CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] \ + ALLOW_UNUSED_TYPE + +// Implementation details of COMPILE_ASSERT: +// +// - COMPILE_ASSERT works by defining an array type that has -1 +// elements (and thus is invalid) when the expression is false. +// +// - The simpler definition +// +// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] +// +// does not work, as gcc supports variable-length arrays whose sizes +// are determined at run-time (this is gcc's extension and not part +// of the C++ standard). As a result, gcc fails to reject the +// following code with the simple definition: +// +// int foo; +// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is +// // not a compile-time constant. +// +// - By using the type CompileAssert<(bool(expr))>, we ensures that +// expr is a compile-time constant. (Template arguments must be +// determined at compile-time.) +// +// - The outer parentheses in CompileAssert<(bool(expr))> are necessary +// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written +// +// CompileAssert +// +// instead, these compilers will refuse to compile +// +// COMPILE_ASSERT(5 > 0, some_message); +// +// (They seem to think the ">" in "5 > 0" marks the end of the +// template argument list.) +// +// - The array size is (bool(expr) ? 1 : -1), instead of simply +// +// ((expr) ? 1 : -1). +// +// This is to avoid running into a bug in MS VC 7.1, which +// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. + +#endif // !(__cplusplus >= 201103L) + +#endif // !defined(COMPILE_ASSERT) + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_MACROS_H_ diff --git a/include/base/cef_move.h b/include/base/cef_move.h new file mode 100644 index 000000000..91069297d --- /dev/null +++ b/include/base/cef_move.h @@ -0,0 +1,259 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_MOVE_H_ +#define CEF_INCLUDE_BASE_CEF_MOVE_H_ + +#if defined(MOVE_ONLY_TYPE_FOR_CPP_03) +// Do nothing if the macro in this header has already been defined. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/move.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +// Macro with the boilerplate that makes a type move-only in C++03. +// +// USAGE +// +// This macro should be used instead of DISALLOW_COPY_AND_ASSIGN to create +// a "move-only" type. Unlike DISALLOW_COPY_AND_ASSIGN, this macro should be +// the first line in a class declaration. +// +// A class using this macro must call .Pass() (or somehow be an r-value already) +// before it can be: +// +// * Passed as a function argument +// * Used as the right-hand side of an assignment +// * Returned from a function +// +// Each class will still need to define their own "move constructor" and "move +// operator=" to make this useful. Here's an example of the macro, the move +// constructor, and the move operator= from the scoped_ptr class: +// +// template +// class scoped_ptr { +// MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) +// public: +// scoped_ptr(RValue& other) : ptr_(other.release()) { } +// scoped_ptr& operator=(RValue& other) { +// swap(other); +// return *this; +// } +// }; +// +// Note that the constructor must NOT be marked explicit. +// +// For consistency, the second parameter to the macro should always be RValue +// unless you have a strong reason to do otherwise. It is only exposed as a +// macro parameter so that the move constructor and move operator= don't look +// like they're using a phantom type. +// +// +// HOW THIS WORKS +// +// For a thorough explanation of this technique, see: +// +// http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Move_Constructor +// +// The summary is that we take advantage of 2 properties: +// +// 1) non-const references will not bind to r-values. +// 2) C++ can apply one user-defined conversion when initializing a +// variable. +// +// The first lets us disable the copy constructor and assignment operator +// by declaring private version of them with a non-const reference parameter. +// +// For l-values, direct initialization still fails like in +// DISALLOW_COPY_AND_ASSIGN because the copy constructor and assignment +// operators are private. +// +// For r-values, the situation is different. The copy constructor and +// assignment operator are not viable due to (1), so we are trying to call +// a non-existent constructor and non-existing operator= rather than a private +// one. Since we have not committed an error quite yet, we can provide an +// alternate conversion sequence and a constructor. We add +// +// * a private struct named "RValue" +// * a user-defined conversion "operator RValue()" +// * a "move constructor" and "move operator=" that take the RValue& as +// their sole parameter. +// +// Only r-values will trigger this sequence and execute our "move constructor" +// or "move operator=." L-values will match the private copy constructor and +// operator= first giving a "private in this context" error. This combination +// gives us a move-only type. +// +// For signaling a destructive transfer of data from an l-value, we provide a +// method named Pass() which creates an r-value for the current instance +// triggering the move constructor or move operator=. +// +// Other ways to get r-values is to use the result of an expression like a +// function call. +// +// Here's an example with comments explaining what gets triggered where: +// +// class Foo { +// MOVE_ONLY_TYPE_FOR_CPP_03(Foo, RValue); +// +// public: +// ... API ... +// Foo(RValue other); // Move constructor. +// Foo& operator=(RValue rhs); // Move operator= +// }; +// +// Foo MakeFoo(); // Function that returns a Foo. +// +// Foo f; +// Foo f_copy(f); // ERROR: Foo(Foo&) is private in this context. +// Foo f_assign; +// f_assign = f; // ERROR: operator=(Foo&) is private in this context. +// +// +// Foo f(MakeFoo()); // R-value so alternate conversion executed. +// Foo f_copy(f.Pass()); // R-value so alternate conversion executed. +// f = f_copy.Pass(); // R-value so alternate conversion executed. +// +// +// IMPLEMENTATION SUBTLETIES WITH RValue +// +// The RValue struct is just a container for a pointer back to the original +// object. It should only ever be created as a temporary, and no external +// class should ever declare it or use it in a parameter. +// +// It is tempting to want to use the RValue type in function parameters, but +// excluding the limited usage here for the move constructor and move +// operator=, doing so would mean that the function could take both r-values +// and l-values equially which is unexpected. See COMPARED To Boost.Move for +// more details. +// +// An alternate, and incorrect, implementation of the RValue class used by +// Boost.Move makes RValue a fieldless child of the move-only type. RValue& +// is then used in place of RValue in the various operators. The RValue& is +// "created" by doing *reinterpret_cast(this). This has the appeal +// of never creating a temporary RValue struct even with optimizations +// disabled. Also, by virtue of inheritance you can treat the RValue +// reference as if it were the move-only type itself. Unfortunately, +// using the result of this reinterpret_cast<> is actually undefined behavior +// due to C++98 5.2.10.7. In certain compilers (e.g., NaCl) the optimizer +// will generate non-working code. +// +// In optimized builds, both implementations generate the same assembly so we +// choose the one that adheres to the standard. +// +// +// WHY HAVE typedef void MoveOnlyTypeForCPP03 +// +// Callback<>/Bind() needs to understand movable-but-not-copyable semantics +// to call .Pass() appropriately when it is expected to transfer the value. +// The cryptic typedef MoveOnlyTypeForCPP03 is added to make this check +// easy and automatic in helper templates for Callback<>/Bind(). +// See IsMoveOnlyType template and its usage in base/callback_internal.h +// for more details. +// +// +// COMPARED TO C++11 +// +// In C++11, you would implement this functionality using an r-value reference +// and our .Pass() method would be replaced with a call to std::move(). +// +// This emulation also has a deficiency where it uses up the single +// user-defined conversion allowed by C++ during initialization. This can +// cause problems in some API edge cases. For instance, in scoped_ptr, it is +// impossible to make a function "void Foo(scoped_ptr p)" accept a +// value of type scoped_ptr even if you add a constructor to +// scoped_ptr<> that would make it look like it should work. C++11 does not +// have this deficiency. +// +// +// COMPARED TO Boost.Move +// +// Our implementation similar to Boost.Move, but we keep the RValue struct +// private to the move-only type, and we don't use the reinterpret_cast<> hack. +// +// In Boost.Move, RValue is the boost::rv<> template. This type can be used +// when writing APIs like: +// +// void MyFunc(boost::rv& f) +// +// that can take advantage of rv<> to avoid extra copies of a type. However you +// would still be able to call this version of MyFunc with an l-value: +// +// Foo f; +// MyFunc(f); // Uh oh, we probably just destroyed |f| w/o calling Pass(). +// +// unless someone is very careful to also declare a parallel override like: +// +// void MyFunc(const Foo& f) +// +// that would catch the l-values first. This was declared unsafe in C++11 and +// a C++11 compiler will explicitly fail MyFunc(f). Unfortunately, we cannot +// ensure this in C++03. +// +// Since we have no need for writing such APIs yet, our implementation keeps +// RValue private and uses a .Pass() method to do the conversion instead of +// trying to write a version of "std::move()." Writing an API like std::move() +// would require the RValue struct to be public. +// +// +// CAVEATS +// +// If you include a move-only type as a field inside a class that does not +// explicitly declare a copy constructor, the containing class's implicit +// copy constructor will change from Containing(const Containing&) to +// Containing(Containing&). This can cause some unexpected errors. +// +// http://llvm.org/bugs/show_bug.cgi?id=11528 +// +// The workaround is to explicitly declare your copy constructor. +// +#define MOVE_ONLY_TYPE_FOR_CPP_03(type, rvalue_type) \ + private: \ + struct rvalue_type { \ + explicit rvalue_type(type* object) : object(object) {} \ + type* object; \ + }; \ + type(type&); \ + void operator=(type&); \ + public: \ + operator rvalue_type() { return rvalue_type(this); } \ + type Pass() { return type(rvalue_type(this)); } \ + typedef void MoveOnlyTypeForCPP03; \ + private: + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_MOVE_H_ diff --git a/include/base/cef_platform_thread.h b/include/base/cef_platform_thread.h new file mode 100644 index 000000000..cda1dc45b --- /dev/null +++ b/include/base/cef_platform_thread.h @@ -0,0 +1,113 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// WARNING: You should *NOT* be using this class directly. PlatformThread is +// the low-level platform-specific abstraction to the OS's threading interface. +// You should instead be using a message-loop driven Thread, see thread.h. + +#ifndef CEF_INCLUDE_BASE_PLATFORM_THREAD_H_ +#define CEF_INCLUDE_BASE_PLATFORM_THREAD_H_ + +#if defined(BASE_THREADING_PLATFORM_THREAD_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/threading/platform_thread.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_basictypes.h" +#include "include/base/cef_build.h" +#include "include/internal/cef_thread_internal.h" + +namespace base { + +// Used for logging. Always an integer value. +typedef cef_platform_thread_id_t PlatformThreadId; + +// Used for thread checking and debugging. +// Meant to be as fast as possible. +// These are produced by PlatformThread::CurrentRef(), and used to later +// check if we are on the same thread or not by using ==. These are safe +// to copy between threads, but can't be copied to another process as they +// have no meaning there. Also, the internal identifier can be re-used +// after a thread dies, so a PlatformThreadRef cannot be reliably used +// to distinguish a new thread from an old, dead thread. +class PlatformThreadRef { + public: + typedef cef_platform_thread_handle_t RefType; + + PlatformThreadRef() + : id_(0) { + } + + explicit PlatformThreadRef(RefType id) + : id_(id) { + } + + bool operator==(PlatformThreadRef other) const { + return id_ == other.id_; + } + + bool is_null() const { + return id_ == 0; + } + private: + RefType id_; +}; + +// A namespace for low-level thread functions. +// Chromium uses a class with static methods but CEF uses an actual namespace +// to avoid linker problems with the sandbox libaries on Windows. +namespace PlatformThread { + +// Gets the current thread id, which may be useful for logging purposes. +inline PlatformThreadId CurrentId() { + return cef_get_current_platform_thread_id(); +} + +// Gets the current thread reference, which can be used to check if +// we're on the right thread quickly. +inline PlatformThreadRef CurrentRef() { + return PlatformThreadRef(cef_get_current_platform_thread_handle()); +} + +} // namespace PlatformThread + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_PLATFORM_THREAD_H_ diff --git a/include/base/cef_ref_counted.h b/include/base/cef_ref_counted.h new file mode 100644 index 000000000..55d41e1b4 --- /dev/null +++ b/include/base/cef_ref_counted.h @@ -0,0 +1,386 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_REF_COUNTED_H_ +#define CEF_INCLUDE_BASE_CEF_REF_COUNTED_H_ +#pragma once + +#if defined(BASE_MEMORY_REF_COUNTED_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/memory/ref_counted.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include + +#include "include/base/cef_atomic_ref_count.h" +#include "include/base/cef_build.h" +#ifndef NDEBUG +#include "include/base/cef_logging.h" +#endif +#include "include/base/cef_thread_collision_warner.h" + +namespace base { + +namespace subtle { + +class RefCountedBase { + public: + bool HasOneRef() const { return ref_count_ == 1; } + + protected: + RefCountedBase() + : ref_count_(0) + #ifndef NDEBUG + , in_dtor_(false) + #endif + { + } + + ~RefCountedBase() { + #ifndef NDEBUG + DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()"; + #endif + } + + + void AddRef() const { + // TODO(maruel): Add back once it doesn't assert 500 times/sec. + // Current thread books the critical section "AddRelease" + // without release it. + // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); + #ifndef NDEBUG + DCHECK(!in_dtor_); + #endif + ++ref_count_; + } + + // Returns true if the object should self-delete. + bool Release() const { + // TODO(maruel): Add back once it doesn't assert 500 times/sec. + // Current thread books the critical section "AddRelease" + // without release it. + // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_); + #ifndef NDEBUG + DCHECK(!in_dtor_); + #endif + if (--ref_count_ == 0) { + #ifndef NDEBUG + in_dtor_ = true; + #endif + return true; + } + return false; + } + + private: + mutable int ref_count_; +#ifndef NDEBUG + mutable bool in_dtor_; +#endif + + DFAKE_MUTEX(add_release_); + + DISALLOW_COPY_AND_ASSIGN(RefCountedBase); +}; + +class RefCountedThreadSafeBase { + public: + bool HasOneRef() const; + + protected: + RefCountedThreadSafeBase(); + ~RefCountedThreadSafeBase(); + + void AddRef() const; + + // Returns true if the object should self-delete. + bool Release() const; + + private: + mutable AtomicRefCount ref_count_; +#ifndef NDEBUG + mutable bool in_dtor_; +#endif + + DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase); +}; + +} // namespace subtle + +// +// A base class for reference counted classes. Otherwise, known as a cheap +// knock-off of WebKit's RefCounted class. To use this guy just extend your +// class from it like so: +// +// class MyFoo : public base::RefCounted { +// ... +// private: +// friend class base::RefCounted; +// ~MyFoo(); +// }; +// +// You should always make your destructor private, to avoid any code deleting +// the object accidently while there are references to it. +template +class RefCounted : public subtle::RefCountedBase { + public: + RefCounted() {} + + void AddRef() const { + subtle::RefCountedBase::AddRef(); + } + + void Release() const { + if (subtle::RefCountedBase::Release()) { + delete static_cast(this); + } + } + + protected: + ~RefCounted() {} + + private: + DISALLOW_COPY_AND_ASSIGN(RefCounted); +}; + +// Forward declaration. +template class RefCountedThreadSafe; + +// Default traits for RefCountedThreadSafe. Deletes the object when its ref +// count reaches 0. Overload to delete it on a different thread etc. +template +struct DefaultRefCountedThreadSafeTraits { + static void Destruct(const T* x) { + // Delete through RefCountedThreadSafe to make child classes only need to be + // friend with RefCountedThreadSafe instead of this struct, which is an + // implementation detail. + RefCountedThreadSafe::DeleteInternal(x); + } +}; + +// +// A thread-safe variant of RefCounted +// +// class MyFoo : public base::RefCountedThreadSafe { +// ... +// }; +// +// If you're using the default trait, then you should add compile time +// asserts that no one else is deleting your object. i.e. +// private: +// friend class base::RefCountedThreadSafe; +// ~MyFoo(); +template > +class RefCountedThreadSafe : public subtle::RefCountedThreadSafeBase { + public: + RefCountedThreadSafe() {} + + void AddRef() const { + subtle::RefCountedThreadSafeBase::AddRef(); + } + + void Release() const { + if (subtle::RefCountedThreadSafeBase::Release()) { + Traits::Destruct(static_cast(this)); + } + } + + protected: + ~RefCountedThreadSafe() {} + + private: + friend struct DefaultRefCountedThreadSafeTraits; + static void DeleteInternal(const T* x) { delete x; } + + DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafe); +}; + +// +// A thread-safe wrapper for some piece of data so we can place other +// things in scoped_refptrs<>. +// +template +class RefCountedData + : public base::RefCountedThreadSafe< base::RefCountedData > { + public: + RefCountedData() : data() {} + RefCountedData(const T& in_value) : data(in_value) {} + + T data; + + private: + friend class base::RefCountedThreadSafe >; + ~RefCountedData() {} +}; + +} // namespace base + +// +// A smart pointer class for reference counted objects. Use this class instead +// of calling AddRef and Release manually on a reference counted object to +// avoid common memory leaks caused by forgetting to Release an object +// reference. Sample usage: +// +// class MyFoo : public RefCounted { +// ... +// }; +// +// void some_function() { +// scoped_refptr foo = new MyFoo(); +// foo->Method(param); +// // |foo| is released when this function returns +// } +// +// void some_other_function() { +// scoped_refptr foo = new MyFoo(); +// ... +// foo = NULL; // explicitly releases |foo| +// ... +// if (foo) +// foo->Method(param); +// } +// +// The above examples show how scoped_refptr acts like a pointer to T. +// Given two scoped_refptr classes, it is also possible to exchange +// references between the two objects, like so: +// +// { +// scoped_refptr a = new MyFoo(); +// scoped_refptr b; +// +// b.swap(a); +// // now, |b| references the MyFoo object, and |a| references NULL. +// } +// +// To make both |a| and |b| in the above example reference the same MyFoo +// object, simply use the assignment operator: +// +// { +// scoped_refptr a = new MyFoo(); +// scoped_refptr b; +// +// b = a; +// // now, |a| and |b| each own a reference to the same MyFoo object. +// } +// +template +class scoped_refptr { + public: + typedef T element_type; + + scoped_refptr() : ptr_(NULL) { + } + + scoped_refptr(T* p) : ptr_(p) { + if (ptr_) + ptr_->AddRef(); + } + + scoped_refptr(const scoped_refptr& r) : ptr_(r.ptr_) { + if (ptr_) + ptr_->AddRef(); + } + + template + scoped_refptr(const scoped_refptr& r) : ptr_(r.get()) { + if (ptr_) + ptr_->AddRef(); + } + + ~scoped_refptr() { + if (ptr_) + ptr_->Release(); + } + + T* get() const { return ptr_; } + + // Allow scoped_refptr to be used in boolean expression + // and comparison operations. + operator T*() const { return ptr_; } + + T* operator->() const { + assert(ptr_ != NULL); + return ptr_; + } + + scoped_refptr& operator=(T* p) { + // AddRef first so that self assignment should work + if (p) + p->AddRef(); + T* old_ptr = ptr_; + ptr_ = p; + if (old_ptr) + old_ptr->Release(); + return *this; + } + + scoped_refptr& operator=(const scoped_refptr& r) { + return *this = r.ptr_; + } + + template + scoped_refptr& operator=(const scoped_refptr& r) { + return *this = r.get(); + } + + void swap(T** pp) { + T* p = ptr_; + ptr_ = *pp; + *pp = p; + } + + void swap(scoped_refptr& r) { + swap(&r.ptr_); + } + + protected: + T* ptr_; +}; + +// Handy utility for creating a scoped_refptr out of a T* explicitly without +// having to retype all the template arguments +template +scoped_refptr make_scoped_refptr(T* t) { + return scoped_refptr(t); +} + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_REF_COUNTED_H_ diff --git a/include/base/cef_scoped_ptr.h b/include/base/cef_scoped_ptr.h new file mode 100644 index 000000000..ed6c706f7 --- /dev/null +++ b/include/base/cef_scoped_ptr.h @@ -0,0 +1,624 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Scopers help you manage ownership of a pointer, helping you easily manage a +// pointer within a scope, and automatically destroying the pointer at the end +// of a scope. There are two main classes you will use, which correspond to the +// operators new/delete and new[]/delete[]. +// +// Example usage (scoped_ptr): +// { +// scoped_ptr foo(new Foo("wee")); +// } // foo goes out of scope, releasing the pointer with it. +// +// { +// scoped_ptr foo; // No pointer managed. +// foo.reset(new Foo("wee")); // Now a pointer is managed. +// foo.reset(new Foo("wee2")); // Foo("wee") was destroyed. +// foo.reset(new Foo("wee3")); // Foo("wee2") was destroyed. +// foo->Method(); // Foo::Method() called. +// foo.get()->Method(); // Foo::Method() called. +// SomeFunc(foo.release()); // SomeFunc takes ownership, foo no longer +// // manages a pointer. +// foo.reset(new Foo("wee4")); // foo manages a pointer again. +// foo.reset(); // Foo("wee4") destroyed, foo no longer +// // manages a pointer. +// } // foo wasn't managing a pointer, so nothing was destroyed. +// +// Example usage (scoped_ptr): +// { +// scoped_ptr foo(new Foo[100]); +// foo.get()->Method(); // Foo::Method on the 0th element. +// foo[10].Method(); // Foo::Method on the 10th element. +// } +// +// These scopers also implement part of the functionality of C++11 unique_ptr +// in that they are "movable but not copyable." You can use the scopers in +// the parameter and return types of functions to signify ownership transfer +// in to and out of a function. When calling a function that has a scoper +// as the argument type, it must be called with the result of an analogous +// scoper's Pass() function or another function that generates a temporary; +// passing by copy will NOT work. Here is an example using scoped_ptr: +// +// void TakesOwnership(scoped_ptr arg) { +// // Do something with arg +// } +// scoped_ptr CreateFoo() { +// // No need for calling Pass() because we are constructing a temporary +// // for the return value. +// return scoped_ptr(new Foo("new")); +// } +// scoped_ptr PassThru(scoped_ptr arg) { +// return arg.Pass(); +// } +// +// { +// scoped_ptr ptr(new Foo("yay")); // ptr manages Foo("yay"). +// TakesOwnership(ptr.Pass()); // ptr no longer owns Foo("yay"). +// scoped_ptr ptr2 = CreateFoo(); // ptr2 owns the return Foo. +// scoped_ptr ptr3 = // ptr3 now owns what was in ptr2. +// PassThru(ptr2.Pass()); // ptr2 is correspondingly NULL. +// } +// +// Notice that if you do not call Pass() when returning from PassThru(), or +// when invoking TakesOwnership(), the code will not compile because scopers +// are not copyable; they only implement move semantics which require calling +// the Pass() function to signify a destructive transfer of state. CreateFoo() +// is different though because we are constructing a temporary on the return +// line and thus can avoid needing to call Pass(). +// +// Pass() properly handles upcast in initialization, i.e. you can use a +// scoped_ptr to initialize a scoped_ptr: +// +// scoped_ptr foo(new Foo()); +// scoped_ptr parent(foo.Pass()); +// +// PassAs<>() should be used to upcast return value in return statement: +// +// scoped_ptr CreateFoo() { +// scoped_ptr result(new FooChild()); +// return result.PassAs(); +// } +// +// Note that PassAs<>() is implemented only for scoped_ptr, but not for +// scoped_ptr. This is because casting array pointers may not be safe. + +#ifndef CEF_INCLUDE_BASE_CEF_MEMORY_SCOPED_PTR_H_ +#define CEF_INCLUDE_BASE_CEF_MEMORY_SCOPED_PTR_H_ +#pragma once + +#if defined(BASE_MEMORY_SCOPED_PTR_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/memory/scoped_ptr.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +// This is an implementation designed to match the anticipated future TR2 +// implementation of the scoped_ptr class. + +#include +#include +#include + +#include // For std::swap(). + +#include "include/base/cef_basictypes.h" +#include "include/base/cef_build.h" +#include "include/base/cef_macros.h" +#include "include/base/cef_move.h" +#include "include/base/cef_template_util.h" + +namespace base { + +namespace subtle { +class RefCountedBase; +class RefCountedThreadSafeBase; +} // namespace subtle + +// Function object which deletes its parameter, which must be a pointer. +// If C is an array type, invokes 'delete[]' on the parameter; otherwise, +// invokes 'delete'. The default deleter for scoped_ptr. +template +struct DefaultDeleter { + DefaultDeleter() {} + template DefaultDeleter(const DefaultDeleter& other) { + // IMPLEMENTATION NOTE: C++11 20.7.1.1.2p2 only provides this constructor + // if U* is implicitly convertible to T* and U is not an array type. + // + // Correct implementation should use SFINAE to disable this + // constructor. However, since there are no other 1-argument constructors, + // using a COMPILE_ASSERT() based on is_convertible<> and requiring + // complete types is simpler and will cause compile failures for equivalent + // misuses. + // + // Note, the is_convertible check also ensures that U is not an + // array. T is guaranteed to be a non-array, so any U* where U is an array + // cannot convert to T*. + enum { T_must_be_complete = sizeof(T) }; + enum { U_must_be_complete = sizeof(U) }; + COMPILE_ASSERT((base::is_convertible::value), + U_ptr_must_implicitly_convert_to_T_ptr); + } + inline void operator()(T* ptr) const { + enum { type_must_be_complete = sizeof(T) }; + delete ptr; + } +}; + +// Specialization of DefaultDeleter for array types. +template +struct DefaultDeleter { + inline void operator()(T* ptr) const { + enum { type_must_be_complete = sizeof(T) }; + delete[] ptr; + } + + private: + // Disable this operator for any U != T because it is undefined to execute + // an array delete when the static type of the array mismatches the dynamic + // type. + // + // References: + // C++98 [expr.delete]p3 + // http://cplusplus.github.com/LWG/lwg-defects.html#938 + template void operator()(U* array) const; +}; + +template +struct DefaultDeleter { + // Never allow someone to declare something like scoped_ptr. + COMPILE_ASSERT(sizeof(T) == -1, do_not_use_array_with_size_as_type); +}; + +// Function object which invokes 'free' on its parameter, which must be +// a pointer. Can be used to store malloc-allocated pointers in scoped_ptr: +// +// scoped_ptr foo_ptr( +// static_cast(malloc(sizeof(int)))); +struct FreeDeleter { + inline void operator()(void* ptr) const { + free(ptr); + } +}; + +namespace cef_internal { + +template struct IsNotRefCounted { + enum { + value = !base::is_convertible::value && + !base::is_convertible:: + value + }; +}; + +// Minimal implementation of the core logic of scoped_ptr, suitable for +// reuse in both scoped_ptr and its specializations. +template +class scoped_ptr_impl { + public: + explicit scoped_ptr_impl(T* p) : data_(p) { } + + // Initializer for deleters that have data parameters. + scoped_ptr_impl(T* p, const D& d) : data_(p, d) {} + + // Templated constructor that destructively takes the value from another + // scoped_ptr_impl. + template + scoped_ptr_impl(scoped_ptr_impl* other) + : data_(other->release(), other->get_deleter()) { + // We do not support move-only deleters. We could modify our move + // emulation to have base::subtle::move() and base::subtle::forward() + // functions that are imperfect emulations of their C++11 equivalents, + // but until there's a requirement, just assume deleters are copyable. + } + + template + void TakeState(scoped_ptr_impl* other) { + // See comment in templated constructor above regarding lack of support + // for move-only deleters. + reset(other->release()); + get_deleter() = other->get_deleter(); + } + + ~scoped_ptr_impl() { + if (data_.ptr != NULL) { + // Not using get_deleter() saves one function call in non-optimized + // builds. + static_cast(data_)(data_.ptr); + } + } + + void reset(T* p) { + // This is a self-reset, which is no longer allowed: http://crbug.com/162971 + if (p != NULL && p == data_.ptr) + abort(); + + // Note that running data_.ptr = p can lead to undefined behavior if + // get_deleter()(get()) deletes this. In order to prevent this, reset() + // should update the stored pointer before deleting its old value. + // + // However, changing reset() to use that behavior may cause current code to + // break in unexpected ways. If the destruction of the owned object + // dereferences the scoped_ptr when it is destroyed by a call to reset(), + // then it will incorrectly dispatch calls to |p| rather than the original + // value of |data_.ptr|. + // + // During the transition period, set the stored pointer to NULL while + // deleting the object. Eventually, this safety check will be removed to + // prevent the scenario initially described from occuring and + // http://crbug.com/176091 can be closed. + T* old = data_.ptr; + data_.ptr = NULL; + if (old != NULL) + static_cast(data_)(old); + data_.ptr = p; + } + + T* get() const { return data_.ptr; } + + D& get_deleter() { return data_; } + const D& get_deleter() const { return data_; } + + void swap(scoped_ptr_impl& p2) { + // Standard swap idiom: 'using std::swap' ensures that std::swap is + // present in the overload set, but we call swap unqualified so that + // any more-specific overloads can be used, if available. + using std::swap; + swap(static_cast(data_), static_cast(p2.data_)); + swap(data_.ptr, p2.data_.ptr); + } + + T* release() { + T* old_ptr = data_.ptr; + data_.ptr = NULL; + return old_ptr; + } + + private: + // Needed to allow type-converting constructor. + template friend class scoped_ptr_impl; + + // Use the empty base class optimization to allow us to have a D + // member, while avoiding any space overhead for it when D is an + // empty class. See e.g. http://www.cantrip.org/emptyopt.html for a good + // discussion of this technique. + struct Data : public D { + explicit Data(T* ptr_in) : ptr(ptr_in) {} + Data(T* ptr_in, const D& other) : D(other), ptr(ptr_in) {} + T* ptr; + }; + + Data data_; + + DISALLOW_COPY_AND_ASSIGN(scoped_ptr_impl); +}; + +} // namespace cef_internal + +} // namespace base + +// A scoped_ptr is like a T*, except that the destructor of scoped_ptr +// automatically deletes the pointer it holds (if any). +// That is, scoped_ptr owns the T object that it points to. +// Like a T*, a scoped_ptr may hold either NULL or a pointer to a T object. +// Also like T*, scoped_ptr is thread-compatible, and once you +// dereference it, you get the thread safety guarantees of T. +// +// The size of scoped_ptr is small. On most compilers, when using the +// DefaultDeleter, sizeof(scoped_ptr) == sizeof(T*). Custom deleters will +// increase the size proportional to whatever state they need to have. See +// comments inside scoped_ptr_impl<> for details. +// +// Current implementation targets having a strict subset of C++11's +// unique_ptr<> features. Known deficiencies include not supporting move-only +// deleteres, function pointers as deleters, and deleters with reference +// types. +template > +class scoped_ptr { + MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) + + COMPILE_ASSERT(base::cef_internal::IsNotRefCounted::value, + T_is_refcounted_type_and_needs_scoped_refptr); + + public: + // The element and deleter types. + typedef T element_type; + typedef D deleter_type; + + // Constructor. Defaults to initializing with NULL. + scoped_ptr() : impl_(NULL) { } + + // Constructor. Takes ownership of p. + explicit scoped_ptr(element_type* p) : impl_(p) { } + + // Constructor. Allows initialization of a stateful deleter. + scoped_ptr(element_type* p, const D& d) : impl_(p, d) { } + + // Constructor. Allows construction from a scoped_ptr rvalue for a + // convertible type and deleter. + // + // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this constructor distinct + // from the normal move constructor. By C++11 20.7.1.2.1.21, this constructor + // has different post-conditions if D is a reference type. Since this + // implementation does not support deleters with reference type, + // we do not need a separate move constructor allowing us to avoid one + // use of SFINAE. You only need to care about this if you modify the + // implementation of scoped_ptr. + template + scoped_ptr(scoped_ptr other) : impl_(&other.impl_) { + COMPILE_ASSERT(!base::is_array::value, U_cannot_be_an_array); + } + + // Constructor. Move constructor for C++03 move emulation of this type. + scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } + + // operator=. Allows assignment from a scoped_ptr rvalue for a convertible + // type and deleter. + // + // IMPLEMENTATION NOTE: C++11 unique_ptr<> keeps this operator= distinct from + // the normal move assignment operator. By C++11 20.7.1.2.3.4, this templated + // form has different requirements on for move-only Deleters. Since this + // implementation does not support move-only Deleters, we do not need a + // separate move assignment operator allowing us to avoid one use of SFINAE. + // You only need to care about this if you modify the implementation of + // scoped_ptr. + template + scoped_ptr& operator=(scoped_ptr rhs) { + COMPILE_ASSERT(!base::is_array::value, U_cannot_be_an_array); + impl_.TakeState(&rhs.impl_); + return *this; + } + + // Reset. Deletes the currently owned object, if any. + // Then takes ownership of a new object, if given. + void reset(element_type* p = NULL) { impl_.reset(p); } + + // Accessors to get the owned object. + // operator* and operator-> will assert() if there is no current object. + element_type& operator*() const { + assert(impl_.get() != NULL); + return *impl_.get(); + } + element_type* operator->() const { + assert(impl_.get() != NULL); + return impl_.get(); + } + element_type* get() const { return impl_.get(); } + + // Access to the deleter. + deleter_type& get_deleter() { return impl_.get_deleter(); } + const deleter_type& get_deleter() const { return impl_.get_deleter(); } + + // Allow scoped_ptr to be used in boolean expressions, but not + // implicitly convertible to a real bool (which is dangerous). + // + // Note that this trick is only safe when the == and != operators + // are declared explicitly, as otherwise "scoped_ptr1 == + // scoped_ptr2" will compile but do the wrong thing (i.e., convert + // to Testable and then do the comparison). + private: + typedef base::cef_internal::scoped_ptr_impl + scoped_ptr::*Testable; + + public: + operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; } + + // Comparison operators. + // These return whether two scoped_ptr refer to the same object, not just to + // two different but equal objects. + bool operator==(const element_type* p) const { return impl_.get() == p; } + bool operator!=(const element_type* p) const { return impl_.get() != p; } + + // Swap two scoped pointers. + void swap(scoped_ptr& p2) { + impl_.swap(p2.impl_); + } + + // Release a pointer. + // The return value is the current pointer held by this object. + // If this object holds a NULL pointer, the return value is NULL. + // After this operation, this object will hold a NULL pointer, + // and will not own the object any more. + element_type* release() WARN_UNUSED_RESULT { + return impl_.release(); + } + + // C++98 doesn't support functions templates with default parameters which + // makes it hard to write a PassAs() that understands converting the deleter + // while preserving simple calling semantics. + // + // Until there is a use case for PassAs() with custom deleters, just ignore + // the custom deleter. + template + scoped_ptr PassAs() { + return scoped_ptr(Pass()); + } + + private: + // Needed to reach into |impl_| in the constructor. + template friend class scoped_ptr; + base::cef_internal::scoped_ptr_impl impl_; + + // Forbidden for API compatibility with std::unique_ptr. + explicit scoped_ptr(int disallow_construction_from_null); + + // Forbid comparison of scoped_ptr types. If U != T, it totally + // doesn't make sense, and if U == T, it still doesn't make sense + // because you should never have the same object owned by two different + // scoped_ptrs. + template bool operator==(scoped_ptr const& p2) const; + template bool operator!=(scoped_ptr const& p2) const; +}; + +template +class scoped_ptr { + MOVE_ONLY_TYPE_FOR_CPP_03(scoped_ptr, RValue) + + public: + // The element and deleter types. + typedef T element_type; + typedef D deleter_type; + + // Constructor. Defaults to initializing with NULL. + scoped_ptr() : impl_(NULL) { } + + // Constructor. Stores the given array. Note that the argument's type + // must exactly match T*. In particular: + // - it cannot be a pointer to a type derived from T, because it is + // inherently unsafe in the general case to access an array through a + // pointer whose dynamic type does not match its static type (eg., if + // T and the derived types had different sizes access would be + // incorrectly calculated). Deletion is also always undefined + // (C++98 [expr.delete]p3). If you're doing this, fix your code. + // - it cannot be NULL, because NULL is an integral expression, not a + // pointer to T. Use the no-argument version instead of explicitly + // passing NULL. + // - it cannot be const-qualified differently from T per unique_ptr spec + // (http://cplusplus.github.com/LWG/lwg-active.html#2118). Users wanting + // to work around this may use implicit_cast(). + // However, because of the first bullet in this comment, users MUST + // NOT use implicit_cast() to upcast the static type of the array. + explicit scoped_ptr(element_type* array) : impl_(array) { } + + // Constructor. Move constructor for C++03 move emulation of this type. + scoped_ptr(RValue rvalue) : impl_(&rvalue.object->impl_) { } + + // operator=. Move operator= for C++03 move emulation of this type. + scoped_ptr& operator=(RValue rhs) { + impl_.TakeState(&rhs.object->impl_); + return *this; + } + + // Reset. Deletes the currently owned array, if any. + // Then takes ownership of a new object, if given. + void reset(element_type* array = NULL) { impl_.reset(array); } + + // Accessors to get the owned array. + element_type& operator[](size_t i) const { + assert(impl_.get() != NULL); + return impl_.get()[i]; + } + element_type* get() const { return impl_.get(); } + + // Access to the deleter. + deleter_type& get_deleter() { return impl_.get_deleter(); } + const deleter_type& get_deleter() const { return impl_.get_deleter(); } + + // Allow scoped_ptr to be used in boolean expressions, but not + // implicitly convertible to a real bool (which is dangerous). + private: + typedef base::cef_internal::scoped_ptr_impl + scoped_ptr::*Testable; + + public: + operator Testable() const { return impl_.get() ? &scoped_ptr::impl_ : NULL; } + + // Comparison operators. + // These return whether two scoped_ptr refer to the same object, not just to + // two different but equal objects. + bool operator==(element_type* array) const { return impl_.get() == array; } + bool operator!=(element_type* array) const { return impl_.get() != array; } + + // Swap two scoped pointers. + void swap(scoped_ptr& p2) { + impl_.swap(p2.impl_); + } + + // Release a pointer. + // The return value is the current pointer held by this object. + // If this object holds a NULL pointer, the return value is NULL. + // After this operation, this object will hold a NULL pointer, + // and will not own the object any more. + element_type* release() WARN_UNUSED_RESULT { + return impl_.release(); + } + + private: + // Force element_type to be a complete type. + enum { type_must_be_complete = sizeof(element_type) }; + + // Actually hold the data. + base::cef_internal::scoped_ptr_impl impl_; + + // Disable initialization from any type other than element_type*, by + // providing a constructor that matches such an initialization, but is + // private and has no definition. This is disabled because it is not safe to + // call delete[] on an array whose static type does not match its dynamic + // type. + template explicit scoped_ptr(U* array); + explicit scoped_ptr(int disallow_construction_from_null); + + // Disable reset() from any type other than element_type*, for the same + // reasons as the constructor above. + template void reset(U* array); + void reset(int disallow_reset_from_null); + + // Forbid comparison of scoped_ptr types. If U != T, it totally + // doesn't make sense, and if U == T, it still doesn't make sense + // because you should never have the same object owned by two different + // scoped_ptrs. + template bool operator==(scoped_ptr const& p2) const; + template bool operator!=(scoped_ptr const& p2) const; +}; + +// Free functions +template +void swap(scoped_ptr& p1, scoped_ptr& p2) { + p1.swap(p2); +} + +template +bool operator==(T* p1, const scoped_ptr& p2) { + return p1 == p2.get(); +} + +template +bool operator!=(T* p1, const scoped_ptr& p2) { + return p1 != p2.get(); +} + +// A function to convert T* into scoped_ptr +// Doing e.g. make_scoped_ptr(new FooBarBaz(arg)) is a shorter notation +// for scoped_ptr >(new FooBarBaz(arg)) +template +scoped_ptr make_scoped_ptr(T* ptr) { + return scoped_ptr(ptr); +} + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_MEMORY_SCOPED_PTR_H_ diff --git a/include/base/cef_string16.h b/include/base/cef_string16.h new file mode 100644 index 000000000..0d642b2df --- /dev/null +++ b/include/base/cef_string16.h @@ -0,0 +1,227 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2013 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_STRING16_H_ +#define CEF_INCLUDE_BASE_CEF_STRING16_H_ +#pragma once + +#if defined(BASE_STRINGS_STRING16_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/strings/string16.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. +// WHAT: +// A version of std::basic_string that provides 2-byte characters even when +// wchar_t is not implemented as a 2-byte type. You can access this class as +// string16. We also define char16, which string16 is based upon. +// +// WHY: +// On Windows, wchar_t is 2 bytes, and it can conveniently handle UTF-16/UCS-2 +// data. Plenty of existing code operates on strings encoded as UTF-16. +// +// On many other platforms, sizeof(wchar_t) is 4 bytes by default. We can make +// it 2 bytes by using the GCC flag -fshort-wchar. But then std::wstring fails +// at run time, because it calls some functions (like wcslen) that come from +// the system's native C library -- which was built with a 4-byte wchar_t! +// It's wasteful to use 4-byte wchar_t strings to carry UTF-16 data, and it's +// entirely improper on those systems where the encoding of wchar_t is defined +// as UTF-32. +// +// Here, we define string16, which is similar to std::wstring but replaces all +// libc functions with custom, 2-byte-char compatible routines. It is capable +// of carrying UTF-16-encoded data. + +#include +#include + +#include "include/base/cef_basictypes.h" + +#if defined(WCHAR_T_IS_UTF16) + +namespace base { + +typedef wchar_t char16; +typedef std::wstring string16; +typedef std::char_traits string16_char_traits; + +} // namespace base + +#elif defined(WCHAR_T_IS_UTF32) + +#include // For uint16_t + +#include "include/base/cef_macros.h" + +namespace base { + +typedef uint16_t char16; + +// char16 versions of the functions required by string16_char_traits; these +// are based on the wide character functions of similar names ("w" or "wcs" +// instead of "c16"). +int c16memcmp(const char16* s1, const char16* s2, size_t n); +size_t c16len(const char16* s); +const char16* c16memchr(const char16* s, char16 c, size_t n); +char16* c16memmove(char16* s1, const char16* s2, size_t n); +char16* c16memcpy(char16* s1, const char16* s2, size_t n); +char16* c16memset(char16* s, char16 c, size_t n); + +struct string16_char_traits { + typedef char16 char_type; + typedef int int_type; + + // int_type needs to be able to hold each possible value of char_type, and in + // addition, the distinct value of eof(). + COMPILE_ASSERT(sizeof(int_type) > sizeof(char_type), unexpected_type_width); + + typedef std::streamoff off_type; + typedef mbstate_t state_type; + typedef std::fpos pos_type; + + static void assign(char_type& c1, const char_type& c2) { + c1 = c2; + } + + static bool eq(const char_type& c1, const char_type& c2) { + return c1 == c2; + } + static bool lt(const char_type& c1, const char_type& c2) { + return c1 < c2; + } + + static int compare(const char_type* s1, const char_type* s2, size_t n) { + return c16memcmp(s1, s2, n); + } + + static size_t length(const char_type* s) { + return c16len(s); + } + + static const char_type* find(const char_type* s, size_t n, + const char_type& a) { + return c16memchr(s, a, n); + } + + static char_type* move(char_type* s1, const char_type* s2, int_type n) { + return c16memmove(s1, s2, n); + } + + static char_type* copy(char_type* s1, const char_type* s2, size_t n) { + return c16memcpy(s1, s2, n); + } + + static char_type* assign(char_type* s, size_t n, char_type a) { + return c16memset(s, a, n); + } + + static int_type not_eof(const int_type& c) { + return eq_int_type(c, eof()) ? 0 : c; + } + + static char_type to_char_type(const int_type& c) { + return char_type(c); + } + + static int_type to_int_type(const char_type& c) { + return int_type(c); + } + + static bool eq_int_type(const int_type& c1, const int_type& c2) { + return c1 == c2; + } + + static int_type eof() { + return static_cast(EOF); + } +}; + +typedef std::basic_string string16; + +extern std::ostream& operator<<(std::ostream& out, const string16& str); + +// This is required by googletest to print a readable output on test failures. +extern void PrintTo(const string16& str, std::ostream* out); + +} // namespace base + +// The string class will be explicitly instantiated only once, in string16.cc. +// +// std::basic_string<> in GNU libstdc++ contains a static data member, +// _S_empty_rep_storage, to represent empty strings. When an operation such +// as assignment or destruction is performed on a string, causing its existing +// data member to be invalidated, it must not be freed if this static data +// member is being used. Otherwise, it counts as an attempt to free static +// (and not allocated) data, which is a memory error. +// +// Generally, due to C++ template magic, _S_empty_rep_storage will be marked +// as a coalesced symbol, meaning that the linker will combine multiple +// instances into a single one when generating output. +// +// If a string class is used by multiple shared libraries, a problem occurs. +// Each library will get its own copy of _S_empty_rep_storage. When strings +// are passed across a library boundary for alteration or destruction, memory +// errors will result. GNU libstdc++ contains a configuration option, +// --enable-fully-dynamic-string (_GLIBCXX_FULLY_DYNAMIC_STRING), which +// disables the static data member optimization, but it's a good optimization +// and non-STL code is generally at the mercy of the system's STL +// configuration. Fully-dynamic strings are not the default for GNU libstdc++ +// libstdc++ itself or for the libstdc++ installations on the systems we care +// about, such as Mac OS X and relevant flavors of Linux. +// +// See also http://gcc.gnu.org/bugzilla/show_bug.cgi?id=24196 . +// +// To avoid problems, string classes need to be explicitly instantiated only +// once, in exactly one library. All other string users see it via an "extern" +// declaration. This is precisely how GNU libstdc++ handles +// std::basic_string (string) and std::basic_string (wstring). +// +// This also works around a Mac OS X linker bug in ld64-85.2.1 (Xcode 3.1.2), +// in which the linker does not fully coalesce symbols when dead code +// stripping is enabled. This bug causes the memory errors described above +// to occur even when a std::basic_string<> does not cross shared library +// boundaries, such as in statically-linked executables. +// +// TODO(mark): File this bug with Apple and update this note with a bug number. + +extern template +class std::basic_string; + +#endif // WCHAR_T_IS_UTF32 + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_STRING16_H_ diff --git a/include/base/cef_template_util.h b/include/base/cef_template_util.h new file mode 100644 index 000000000..5fa228b5f --- /dev/null +++ b/include/base/cef_template_util.h @@ -0,0 +1,192 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_TEMPLATE_UTIL_H_ +#define CEF_INCLUDE_BASE_CEF_TEMPLATE_UTIL_H_ +#pragma once + +#if defined(BASE_TEMPLATE_UTIL_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/template_util.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include // For size_t. + +#include "include/base/cef_build.h" + +namespace base { + +// template definitions from tr1 + +template +struct integral_constant { + static const T value = v; + typedef T value_type; + typedef integral_constant type; +}; + +template const T integral_constant::value; + +typedef integral_constant true_type; +typedef integral_constant false_type; + +template struct is_pointer : false_type {}; +template struct is_pointer : true_type {}; + +// Member function pointer detection up to four params. Add more as needed +// below. This is built-in to C++ 11, and we can remove this when we switch. +template +struct is_member_function_pointer : false_type {}; + +template +struct is_member_function_pointer : true_type {}; +template +struct is_member_function_pointer : true_type {}; + +template +struct is_member_function_pointer : true_type {}; +template +struct is_member_function_pointer : true_type {}; + +template +struct is_member_function_pointer : true_type {}; +template +struct is_member_function_pointer : true_type {}; + +template +struct is_member_function_pointer : true_type {}; +template +struct is_member_function_pointer : true_type {}; + +template +struct is_member_function_pointer : true_type {}; +template +struct is_member_function_pointer : true_type {}; + + +template struct is_same : public false_type {}; +template struct is_same : true_type {}; + +template struct is_array : public false_type {}; +template struct is_array : public true_type {}; +template struct is_array : public true_type {}; + +template struct is_non_const_reference : false_type {}; +template struct is_non_const_reference : true_type {}; +template struct is_non_const_reference : false_type {}; + +template struct is_const : false_type {}; +template struct is_const : true_type {}; + +template struct is_void : false_type {}; +template <> struct is_void : true_type {}; + +namespace cef_internal { + +// Types YesType and NoType are guaranteed such that sizeof(YesType) < +// sizeof(NoType). +typedef char YesType; + +struct NoType { + YesType dummy[2]; +}; + +// This class is an implementation detail for is_convertible, and you +// don't need to know how it works to use is_convertible. For those +// who care: we declare two different functions, one whose argument is +// of type To and one with a variadic argument list. We give them +// return types of different size, so we can use sizeof to trick the +// compiler into telling us which function it would have chosen if we +// had called it with an argument of type From. See Alexandrescu's +// _Modern C++ Design_ for more details on this sort of trick. + +struct ConvertHelper { + template + static YesType Test(To); + + template + static NoType Test(...); + + template + static From& Create(); +}; + +// Used to determine if a type is a struct/union/class. Inspired by Boost's +// is_class type_trait implementation. +struct IsClassHelper { + template + static YesType Test(void(C::*)(void)); + + template + static NoType Test(...); +}; + +} // namespace cef_internal + +// Inherits from true_type if From is convertible to To, false_type otherwise. +// +// Note that if the type is convertible, this will be a true_type REGARDLESS +// of whether or not the conversion would emit a warning. +template +struct is_convertible + : integral_constant( + cef_internal::ConvertHelper::Create())) == + sizeof(cef_internal::YesType)> { +}; + +template +struct is_class + : integral_constant(0)) == + sizeof(cef_internal::YesType)> { +}; + +template +struct enable_if {}; + +template +struct enable_if { typedef T type; }; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_TEMPLATE_UTIL_H_ diff --git a/include/base/cef_thread_checker.h b/include/base/cef_thread_checker.h new file mode 100644 index 000000000..2fd4f271a --- /dev/null +++ b/include/base/cef_thread_checker.h @@ -0,0 +1,125 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_THREAD_CHECKER_H_ +#define CEF_INCLUDE_BASE_THREAD_CHECKER_H_ +#pragma once + +#if defined(BASE_THREADING_THREAD_CHECKER_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/threading/thread_checker.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +// Apart from debug builds, we also enable the thread checker in +// builds with DCHECK_ALWAYS_ON so that trybots and waterfall bots +// with this define will get the same level of thread checking as +// debug bots. +// +// Note that this does not perfectly match situations where DCHECK is +// enabled. For example a non-official release build may have +// DCHECK_ALWAYS_ON undefined (and therefore ThreadChecker would be +// disabled) but have DCHECKs enabled at runtime. +#if (!defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)) +#define ENABLE_THREAD_CHECKER 1 +#else +#define ENABLE_THREAD_CHECKER 0 +#endif + +#include "include/base/internal/cef_thread_checker_impl.h" + +namespace base { + +// Do nothing implementation, for use in release mode. +// +// Note: You should almost always use the ThreadChecker class to get the +// right version for your build configuration. +class ThreadCheckerDoNothing { + public: + bool CalledOnValidThread() const { + return true; + } + + void DetachFromThread() {} +}; + +// ThreadChecker is a helper class used to help verify that some methods of a +// class are called from the same thread. It provides identical functionality to +// base::NonThreadSafe, but it is meant to be held as a member variable, rather +// than inherited from base::NonThreadSafe. +// +// While inheriting from base::NonThreadSafe may give a clear indication about +// the thread-safety of a class, it may also lead to violations of the style +// guide with regard to multiple inheritance. The choice between having a +// ThreadChecker member and inheriting from base::NonThreadSafe should be based +// on whether: +// - Derived classes need to know the thread they belong to, as opposed to +// having that functionality fully encapsulated in the base class. +// - Derived classes should be able to reassign the base class to another +// thread, via DetachFromThread. +// +// If neither of these are true, then having a ThreadChecker member and calling +// CalledOnValidThread is the preferable solution. +// +// Example: +// class MyClass { +// public: +// void Foo() { +// DCHECK(thread_checker_.CalledOnValidThread()); +// ... (do stuff) ... +// } +// +// private: +// ThreadChecker thread_checker_; +// } +// +// In Release mode, CalledOnValidThread will always return true. +#if ENABLE_THREAD_CHECKER +class ThreadChecker : public ThreadCheckerImpl { +}; +#else +class ThreadChecker : public ThreadCheckerDoNothing { +}; +#endif // ENABLE_THREAD_CHECKER + +#undef ENABLE_THREAD_CHECKER + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_THREAD_CHECKER_H_ diff --git a/include/base/cef_thread_collision_warner.h b/include/base/cef_thread_collision_warner.h new file mode 100644 index 000000000..bbc88759c --- /dev/null +++ b/include/base/cef_thread_collision_warner.h @@ -0,0 +1,287 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_BASE_CEF_THREAD_COLLISION_WARNER_H_ +#define CEF_INCLUDE_BASE_CEF_THREAD_COLLISION_WARNER_H_ +#pragma once + +#if defined(BASE_THREADING_THREAD_COLLISION_WARNER_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/threading/thread_collision_warner.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include + +#include "include/base/cef_atomicops.h" +#include "include/base/cef_basictypes.h" +#include "include/base/cef_build.h" +#include "include/base/cef_macros.h" + +// A helper class alongside macros to be used to verify assumptions about thread +// safety of a class. +// +// Example: Queue implementation non thread-safe but still usable if clients +// are synchronized somehow. +// +// In this case the macro DFAKE_SCOPED_LOCK has to be +// used, it checks that if a thread is inside the push/pop then +// noone else is still inside the pop/push +// +// class NonThreadSafeQueue { +// public: +// ... +// void push(int) { DFAKE_SCOPED_LOCK(push_pop_); ... } +// int pop() { DFAKE_SCOPED_LOCK(push_pop_); ... } +// ... +// private: +// DFAKE_MUTEX(push_pop_); +// }; +// +// +// Example: Queue implementation non thread-safe but still usable if clients +// are synchronized somehow, it calls a method to "protect" from +// a "protected" method +// +// In this case the macro DFAKE_SCOPED_RECURSIVE_LOCK +// has to be used, it checks that if a thread is inside the push/pop +// then noone else is still inside the pop/push +// +// class NonThreadSafeQueue { +// public: +// void push(int) { +// DFAKE_SCOPED_LOCK(push_pop_); +// ... +// } +// int pop() { +// DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); +// bar(); +// ... +// } +// void bar() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); ... } +// ... +// private: +// DFAKE_MUTEX(push_pop_); +// }; +// +// +// Example: Queue implementation not usable even if clients are synchronized, +// so only one thread in the class life cycle can use the two members +// push/pop. +// +// In this case the macro DFAKE_SCOPED_LOCK_THREAD_LOCKED pins the +// specified +// critical section the first time a thread enters push or pop, from +// that time on only that thread is allowed to execute push or pop. +// +// class NonThreadSafeQueue { +// public: +// ... +// void push(int) { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); ... } +// int pop() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); ... } +// ... +// private: +// DFAKE_MUTEX(push_pop_); +// }; +// +// +// Example: Class that has to be contructed/destroyed on same thread, it has +// a "shareable" method (with external synchronization) and a not +// shareable method (even with external synchronization). +// +// In this case 3 Critical sections have to be defined +// +// class ExoticClass { +// public: +// ExoticClass() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... } +// ~ExoticClass() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... } +// +// void Shareable() { DFAKE_SCOPED_LOCK(shareable_section_); ... } +// void NotShareable() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... } +// ... +// private: +// DFAKE_MUTEX(ctor_dtor_); +// DFAKE_MUTEX(shareable_section_); +// }; + + +#if !defined(NDEBUG) + +// Defines a class member that acts like a mutex. It is used only as a +// verification tool. +#define DFAKE_MUTEX(obj) \ + mutable base::ThreadCollisionWarner obj +// Asserts the call is never called simultaneously in two threads. Used at +// member function scope. +#define DFAKE_SCOPED_LOCK(obj) \ + base::ThreadCollisionWarner::ScopedCheck s_check_##obj(&obj) +// Asserts the call is never called simultaneously in two threads. Used at +// member function scope. Same as DFAKE_SCOPED_LOCK but allows recursive locks. +#define DFAKE_SCOPED_RECURSIVE_LOCK(obj) \ + base::ThreadCollisionWarner::ScopedRecursiveCheck sr_check_##obj(&obj) +// Asserts the code is always executed in the same thread. +#define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) \ + base::ThreadCollisionWarner::Check check_##obj(&obj) + +#else + +#define DFAKE_MUTEX(obj) typedef void InternalFakeMutexType##obj +#define DFAKE_SCOPED_LOCK(obj) ((void)0) +#define DFAKE_SCOPED_RECURSIVE_LOCK(obj) ((void)0) +#define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) ((void)0) + +#endif + +namespace base { + +// The class ThreadCollisionWarner uses an Asserter to notify the collision +// AsserterBase is the interfaces and DCheckAsserter is the default asserter +// used. During the unit tests is used another class that doesn't "DCHECK" +// in case of collision (check thread_collision_warner_unittests.cc) +struct AsserterBase { + virtual ~AsserterBase() {} + virtual void warn() = 0; +}; + +struct DCheckAsserter : public AsserterBase { + virtual ~DCheckAsserter() {} + virtual void warn() OVERRIDE; +}; + +class ThreadCollisionWarner { + public: + // The parameter asserter is there only for test purpose + explicit ThreadCollisionWarner(AsserterBase* asserter = new DCheckAsserter()) + : valid_thread_id_(0), + counter_(0), + asserter_(asserter) {} + + ~ThreadCollisionWarner() { + delete asserter_; + } + + // This class is meant to be used through the macro + // DFAKE_SCOPED_LOCK_THREAD_LOCKED + // it doesn't leave the critical section, as opposed to ScopedCheck, + // because the critical section being pinned is allowed to be used only + // from one thread + class Check { + public: + explicit Check(ThreadCollisionWarner* warner) + : warner_(warner) { + warner_->EnterSelf(); + } + + ~Check() {} + + private: + ThreadCollisionWarner* warner_; + + DISALLOW_COPY_AND_ASSIGN(Check); + }; + + // This class is meant to be used through the macro + // DFAKE_SCOPED_LOCK + class ScopedCheck { + public: + explicit ScopedCheck(ThreadCollisionWarner* warner) + : warner_(warner) { + warner_->Enter(); + } + + ~ScopedCheck() { + warner_->Leave(); + } + + private: + ThreadCollisionWarner* warner_; + + DISALLOW_COPY_AND_ASSIGN(ScopedCheck); + }; + + // This class is meant to be used through the macro + // DFAKE_SCOPED_RECURSIVE_LOCK + class ScopedRecursiveCheck { + public: + explicit ScopedRecursiveCheck(ThreadCollisionWarner* warner) + : warner_(warner) { + warner_->EnterSelf(); + } + + ~ScopedRecursiveCheck() { + warner_->Leave(); + } + + private: + ThreadCollisionWarner* warner_; + + DISALLOW_COPY_AND_ASSIGN(ScopedRecursiveCheck); + }; + + private: + // This method stores the current thread identifier and does a DCHECK + // if a another thread has already done it, it is safe if same thread + // calls this multiple time (recursion allowed). + void EnterSelf(); + + // Same as EnterSelf but recursion is not allowed. + void Enter(); + + // Removes the thread_id stored in order to allow other threads to + // call EnterSelf or Enter. + void Leave(); + + // This stores the thread id that is inside the critical section, if the + // value is 0 then no thread is inside. + volatile subtle::Atomic32 valid_thread_id_; + + // Counter to trace how many time a critical section was "pinned" + // (when allowed) in order to unpin it when counter_ reaches 0. + volatile subtle::Atomic32 counter_; + + // Here only for class unit tests purpose, during the test I need to not + // DCHECK but notify the collision with something else. + AsserterBase* asserter_; + + DISALLOW_COPY_AND_ASSIGN(ThreadCollisionWarner); +}; + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_THREAD_COLLISION_WARNER_H_ diff --git a/include/base/cef_trace_event.h b/include/base/cef_trace_event.h new file mode 100644 index 000000000..a24146cd0 --- /dev/null +++ b/include/base/cef_trace_event.h @@ -0,0 +1,427 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +/// +// Trace events are for tracking application performance and resource usage. +// Macros are provided to track: +// Begin and end of function calls +// Counters +// +// Events are issued against categories. Whereas LOG's categories are statically +// defined, TRACE categories are created implicitly with a string. For example: +// TRACE_EVENT_INSTANT0("MY_SUBSYSTEM", "SomeImportantEvent") +// +// Events can be INSTANT, or can be pairs of BEGIN and END in the same scope: +// TRACE_EVENT_BEGIN0("MY_SUBSYSTEM", "SomethingCostly") +// doSomethingCostly() +// TRACE_EVENT_END0("MY_SUBSYSTEM", "SomethingCostly") +// Note: Our tools can't always determine the correct BEGIN/END pairs unless +// these are used in the same scope. Use ASYNC_BEGIN/ASYNC_END macros if you +// need them to be in separate scopes. +// +// A common use case is to trace entire function scopes. This issues a trace +// BEGIN and END automatically: +// void doSomethingCostly() { +// TRACE_EVENT0("MY_SUBSYSTEM", "doSomethingCostly"); +// ... +// } +// +// Additional parameters can be associated with an event: +// void doSomethingCostly2(int howMuch) { +// TRACE_EVENT1("MY_SUBSYSTEM", "doSomethingCostly", +// "howMuch", howMuch); +// ... +// } +// +// The trace system will automatically add to this information the current +// process id, thread id, and a timestamp in microseconds. +// +// To trace an asynchronous procedure such as an IPC send/receive, use +// ASYNC_BEGIN and ASYNC_END: +// [single threaded sender code] +// static int send_count = 0; +// ++send_count; +// TRACE_EVENT_ASYNC_BEGIN0("ipc", "message", send_count); +// Send(new MyMessage(send_count)); +// [receive code] +// void OnMyMessage(send_count) { +// TRACE_EVENT_ASYNC_END0("ipc", "message", send_count); +// } +// The third parameter is a unique ID to match ASYNC_BEGIN/ASYNC_END pairs. +// ASYNC_BEGIN and ASYNC_END can occur on any thread of any traced process. +// Pointers can be used for the ID parameter, and they will be mangled +// internally so that the same pointer on two different processes will not +// match. For example: +// class MyTracedClass { +// public: +// MyTracedClass() { +// TRACE_EVENT_ASYNC_BEGIN0("category", "MyTracedClass", this); +// } +// ~MyTracedClass() { +// TRACE_EVENT_ASYNC_END0("category", "MyTracedClass", this); +// } +// } +// +// The trace event also supports counters, which is a way to track a quantity +// as it varies over time. Counters are created with the following macro: +// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter", g_myCounterValue); +// +// Counters are process-specific. The macro itself can be issued from any +// thread, however. +// +// Sometimes, you want to track two counters at once. You can do this with two +// counter macros: +// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter0", g_myCounterValue[0]); +// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter1", g_myCounterValue[1]); +// Or you can do it with a combined macro: +// TRACE_COUNTER2("MY_SUBSYSTEM", "myCounter", +// "bytesPinned", g_myCounterValue[0], +// "bytesAllocated", g_myCounterValue[1]); +// This indicates to the tracing UI that these counters should be displayed +// in a single graph, as a summed area chart. +// +// Since counters are in a global namespace, you may want to disembiguate with a +// unique ID, by using the TRACE_COUNTER_ID* variations. +// +// By default, trace collection is compiled in, but turned off at runtime. +// Collecting trace data is the responsibility of the embedding application. In +// CEF's case, calling BeginTracing will turn on tracing on all active +// processes. +// +// +// Memory scoping note: +// Tracing copies the pointers, not the string content, of the strings passed +// in for category, name, and arg_names. Thus, the following code will cause +// problems: +// char* str = strdup("impprtantName"); +// TRACE_EVENT_INSTANT0("SUBSYSTEM", str); // BAD! +// free(str); // Trace system now has dangling pointer +// +// To avoid this issue with the |name| and |arg_name| parameters, use the +// TRACE_EVENT_COPY_XXX overloads of the macros at additional runtime +// overhead. +// Notes: The category must always be in a long-lived char* (i.e. static const). +// The |arg_values|, when used, are always deep copied with the _COPY +// macros. +// +// +// Thread Safety: +// All macros are thread safe and can be used from any process. +/// + +#ifndef CEF_INCLUDE_BASE_CEF_TRACE_EVENT_H_ +#define CEF_INCLUDE_BASE_CEF_TRACE_EVENT_H_ +#pragma once + +#if defined(TRACE_EVENT0) +// Do nothing if the macros provided by this header already exist. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/debug/trace_event.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/internal/cef_trace_event_internal.h" + +// Records a pair of begin and end events called "name" for the current +// scope, with 0, 1 or 2 associated arguments. If the category is not +// enabled, then this does nothing. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +#define TRACE_EVENT0(category, name) \ + cef_trace_event_begin(category, name, NULL, 0, NULL, 0, false); \ + CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) +#define TRACE_EVENT1(category, name, arg1_name, arg1_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, NULL, 0, false); \ + CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) +#define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val, false); \ + CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) + +// Implementation detail: trace event macros create temporary variable names. +// These macros give each temporary variable a unique name based on the line +// number to prevent name collisions. +#define CEF_INTERNAL_TRACE_EVENT_UID3(a,b) \ + cef_trace_event_unique_##a##b +#define CEF_INTERNAL_TRACE_EVENT_UID2(a,b) \ + CEF_INTERNAL_TRACE_EVENT_UID3(a,b) +#define CEF_INTERNAL_TRACE_EVENT_UID(name_prefix) \ + CEF_INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__) + +// Implementation detail: internal macro to end end event when the scope ends. +#define CEF_INTERNAL_TRACE_END_ON_SCOPE_CLOSE(category, name) \ + cef_trace_event::CefTraceEndOnScopeClose \ + CEF_INTERNAL_TRACE_EVENT_UID(profileScope)(category, name) + +// Records a single event called "name" immediately, with 0, 1 or 2 +// associated arguments. If the category is not enabled, then this +// does nothing. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +#define TRACE_EVENT_INSTANT0(category, name) \ + cef_trace_event_instant(category, name, NULL, 0, NULL, 0, false) +#define TRACE_EVENT_INSTANT1(category, name, arg1_name, arg1_val) \ + cef_trace_event_instant(category, name, arg1_name, arg1_val, NULL, 0, false) +#define TRACE_EVENT_INSTANT2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_instant(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false) +#define TRACE_EVENT_COPY_INSTANT0(category, name) \ + cef_trace_event_instant(category, name, NULL, 0, NULL, 0, true) +#define TRACE_EVENT_COPY_INSTANT1(category, name, arg1_name, arg1_val) \ + cef_trace_event_instant(category, name, arg1_name, arg1_val, NULL, 0, true) +#define TRACE_EVENT_COPY_INSTANT2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_instant(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, true) + +// Records a single BEGIN event called "name" immediately, with 0, 1 or 2 +// associated arguments. If the category is not enabled, then this +// does nothing. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +#define TRACE_EVENT_BEGIN0(category, name) \ + cef_trace_event_begin(category, name, NULL, 0, NULL, 0, false) +#define TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, NULL, 0, false) +#define TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false) +#define TRACE_EVENT_COPY_BEGIN0(category, name) \ + cef_trace_event_begin(category, name, NULL, 0, NULL, 0, true) +#define TRACE_EVENT_COPY_BEGIN1(category, name, arg1_name, arg1_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, NULL, 0, true) +#define TRACE_EVENT_COPY_BEGIN2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_begin(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, true) + +// Records a single END event for "name" immediately. If the category +// is not enabled, then this does nothing. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +#define TRACE_EVENT_END0(category, name) \ + cef_trace_event_end(category, name, NULL, 0, NULL, 0, false) +#define TRACE_EVENT_END1(category, name, arg1_name, arg1_val) \ + cef_trace_event_end(category, name, arg1_name, arg1_val, NULL, 0, false) +#define TRACE_EVENT_END2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_end(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, false) +#define TRACE_EVENT_COPY_END0(category, name) \ + cef_trace_event_end(category, name, NULL, 0, NULL, 0, true) +#define TRACE_EVENT_COPY_END1(category, name, arg1_name, arg1_val) \ + cef_trace_event_end(category, name, arg1_name, arg1_val, NULL, 0, true) +#define TRACE_EVENT_COPY_END2(category, name, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_end(category, name, arg1_name, arg1_val, arg2_name, \ + arg2_val, true) + +// Records the value of a counter called "name" immediately. Value +// must be representable as a 32 bit integer. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +#define TRACE_COUNTER1(category, name, value) \ + cef_trace_counter(category, name, NULL, value, NULL, 0, false) +#define TRACE_COPY_COUNTER1(category, name, value) \ + cef_trace_counter(category, name, NULL, value, NULL, 0, true) + +// Records the values of a multi-parted counter called "name" immediately. +// The UI will treat value1 and value2 as parts of a whole, displaying their +// values as a stacked-bar chart. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +#define TRACE_COUNTER2(category, name, value1_name, value1_val, \ + value2_name, value2_val) \ + cef_trace_counter(category, name, value1_name, value1_val, value2_name, \ + value2_val, false) +#define TRACE_COPY_COUNTER2(category, name, value1_name, value1_val, \ + value2_name, value2_val) \ + cef_trace_counter(category, name, value1_name, value1_val, value2_name, \ + value2_val, true) + +// Records the value of a counter called "name" immediately. Value +// must be representable as a 32 bit integer. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +// - |id| is used to disambiguate counters with the same name. It must either +// be a pointer or an integer value up to 64 bits. If it's a pointer, the +// bits will be xored with a hash of the process ID so that the same pointer +// on two different processes will not collide. +#define TRACE_COUNTER_ID1(category, name, id, value) \ + cef_trace_counter_id(category, name, id, NULL, value, NULL, 0, false) +#define TRACE_COPY_COUNTER_ID1(category, name, id, value) \ + cef_trace_counter_id(category, name, id, NULL, value, NULL, 0, true) + +// Records the values of a multi-parted counter called "name" immediately. +// The UI will treat value1 and value2 as parts of a whole, displaying their +// values as a stacked-bar chart. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +// - |id| is used to disambiguate counters with the same name. It must either +// be a pointer or an integer value up to 64 bits. If it's a pointer, the +// bits will be xored with a hash of the process ID so that the same pointer +// on two different processes will not collide. +#define TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val, \ + value2_name, value2_val) \ + cef_trace_counter_id(category, name, id, value1_name, value1_val, \ + value2_name, value2_val, false) +#define TRACE_COPY_COUNTER_ID2(category, name, id, value1_name, \ + value1_val, value2_name, value2_val) \ + cef_trace_counter_id(category, name, id, value1_name, value1_val, \ + value2_name, value2_val, true) + + +// Records a single ASYNC_BEGIN event called "name" immediately, with 0, 1 or 2 +// associated arguments. If the category is not enabled, then this +// does nothing. +// - category and name strings must have application lifetime (statics or +// literals). They may not include " chars. +// - |id| is used to match the ASYNC_BEGIN event with the ASYNC_END event. +// ASYNC events are considered to match if their category, name and id values +// all match. |id| must either be a pointer or an integer value up to 64 +// bits. If it's a pointer, the bits will be xored with a hash of the process +// ID sothat the same pointer on two different processes will not collide. +// An asynchronous operation can consist of multiple phases. The first phase is +// defined by the ASYNC_BEGIN calls. Additional phases can be defined using the +// ASYNC_STEP_BEGIN macros. When the operation completes, call ASYNC_END. +// An async operation can span threads and processes, but all events in that +// operation must use the same |name| and |id|. Each event can have its own +// args. +#define TRACE_EVENT_ASYNC_BEGIN0(category, name, id) \ + cef_trace_event_async_begin(category, name, id, NULL, 0, NULL, 0, false) +#define TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, NULL, \ + 0, false) +#define TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, false) +#define TRACE_EVENT_COPY_ASYNC_BEGIN0(category, name, id) \ + cef_trace_event_async_begin(category, name, id, NULL, 0, NULL, 0, true) +#define TRACE_EVENT_COPY_ASYNC_BEGIN1(category, name, id, arg1_name, \ + arg1_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, NULL, \ + 0, true) +#define TRACE_EVENT_COPY_ASYNC_BEGIN2(category, name, id, arg1_name, \ + arg1_val, arg2_name, arg2_val) \ + cef_trace_event_async_begin(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, true) + +// Records a single ASYNC_STEP_INTO event for |step| immediately. If the +// category is not enabled, then this does nothing. The |name| and |id| must +// match the ASYNC_BEGIN event above. The |step| param identifies this step +// within the async event. This should be called at the beginning of the next +// phase of an asynchronous operation. The ASYNC_BEGIN event must not have any +// ASYNC_STEP_PAST events. +#define TRACE_EVENT_ASYNC_STEP_INTO0(category, name, id, step) \ + cef_trace_event_async_step_into(category, name, id, step, NULL, 0, false) +#define TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step, \ + arg1_name, arg1_val) \ + cef_trace_event_async_step_into(category, name, id, step, arg1_name, \ + arg1_val, false) +#define TRACE_EVENT_COPY_ASYNC_STEP_INTO0(category, name, id, step) \ + cef_trace_event_async_step_into(category, name, id, step, NULL, 0, true) +#define TRACE_EVENT_COPY_ASYNC_STEP_INTO1(category, name, id, step, \ + arg1_name, arg1_val) \ + cef_trace_event_async_step_into(category, name, id, step, arg1_name, \ + arg1_val, true) + +// Records a single ASYNC_STEP_PAST event for |step| immediately. If the +// category is not enabled, then this does nothing. The |name| and |id| must +// match the ASYNC_BEGIN event above. The |step| param identifies this step +// within the async event. This should be called at the beginning of the next +// phase of an asynchronous operation. The ASYNC_BEGIN event must not have any +// ASYNC_STEP_INTO events. +#define TRACE_EVENT_ASYNC_STEP_PAST0(category, name, id, step) \ + cef_trace_event_async_step_past(category, name, id, step, NULL, 0, false) +#define TRACE_EVENT_ASYNC_STEP_PAST1(category, name, id, step, \ + arg1_name, arg1_val) \ + cef_trace_event_async_step_past(category, name, id, step, arg1_name, \ + arg1_val, false) +#define TRACE_EVENT_COPY_ASYNC_STEP_PAST0(category, name, id, step) \ + cef_trace_event_async_step_past(category, name, id, step, NULL, 0, true) +#define TRACE_EVENT_COPY_ASYNC_STEP_PAST1(category, name, id, step, \ + arg1_name, arg1_val) \ + cef_trace_event_async_step_past(category, name, id, step, arg1_name, \ + arg1_val, true) + +// Records a single ASYNC_END event for "name" immediately. If the category +// is not enabled, then this does nothing. +#define TRACE_EVENT_ASYNC_END0(category, name, id) \ + cef_trace_event_async_end(category, name, id, NULL, 0, NULL, 0, false) +#define TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, arg1_val) \ + cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, NULL, 0, \ + false) +#define TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val) \ + cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, false) +#define TRACE_EVENT_COPY_ASYNC_END0(category, name, id) \ + cef_trace_event_async_end(category, name, id, NULL, 0, NULL, 0, true) +#define TRACE_EVENT_COPY_ASYNC_END1(category, name, id, arg1_name, \ + arg1_val) \ + cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, NULL, 0, \ + true) +#define TRACE_EVENT_COPY_ASYNC_END2(category, name, id, arg1_name, \ + arg1_val, arg2_name, arg2_val) \ + cef_trace_event_async_end(category, name, id, arg1_name, arg1_val, \ + arg2_name, arg2_val, true) + +namespace cef_trace_event { + +// Used by TRACE_EVENTx macro. Do not use directly. +class CefTraceEndOnScopeClose { + public: + CefTraceEndOnScopeClose(const char* category, const char* name) + : category_(category), name_(name) { + } + ~CefTraceEndOnScopeClose() { + cef_trace_event_end(category_, name_, NULL, 0, NULL, 0, false); + } + + private: + const char* category_; + const char* name_; +}; + +} // cef_trace_event + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_TRACE_EVENT_H_ diff --git a/include/base/cef_tuple.h b/include/base/cef_tuple.h new file mode 100644 index 000000000..7f4b2b156 --- /dev/null +++ b/include/base/cef_tuple.h @@ -0,0 +1,1399 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2011 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// A Tuple is a generic templatized container, similar in concept to std::pair. +// There are classes Tuple0 to Tuple6, cooresponding to the number of elements +// it contains. The convenient MakeTuple() function takes 0 to 6 arguments, +// and will construct and return the appropriate Tuple object. The functions +// DispatchToMethod and DispatchToFunction take a function pointer or instance +// and method pointer, and unpack a tuple into arguments to the call. +// +// Tuple elements are copied by value, and stored in the tuple. See the unit +// tests for more details of how/when the values are copied. +// +// Example usage: +// // These two methods of creating a Tuple are identical. +// Tuple2 tuple_a(1, "wee"); +// Tuple2 tuple_b = MakeTuple(1, "wee"); +// +// void SomeFunc(int a, const char* b) { } +// DispatchToFunction(&SomeFunc, tuple_a); // SomeFunc(1, "wee") +// DispatchToFunction( +// &SomeFunc, MakeTuple(10, "foo")); // SomeFunc(10, "foo") +// +// struct { void SomeMeth(int a, int b, int c) { } } foo; +// DispatchToMethod(&foo, &Foo::SomeMeth, MakeTuple(1, 2, 3)); +// // foo->SomeMeth(1, 2, 3); + +#ifndef CEF_INCLUDE_BASE_CEF_TUPLE_H_ +#define CEF_INCLUDE_BASE_CEF_TUPLE_H_ +#pragma once + +#if defined(BASE_TUPLE_H__) +// The Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. + +// For legacy compatibility, we name the first 8 tuple elements "a", "b", ... +// TODO(cef): Remove this code when cef_runnable.h is deleted. + +#define DEFINE_TUPLE_LEAF(N, x) \ + template \ + struct TupleLeaf { \ + TupleLeaf() {} \ + explicit TupleLeaf(typename TupleTraits::ParamType x) : x(x) {} \ + \ + T& get() { return x; } \ + const T& get() const { return x; } \ + \ + T x; \ + } + +DEFINE_TUPLE_LEAF(0, a); +DEFINE_TUPLE_LEAF(1, b); +DEFINE_TUPLE_LEAF(2, c); +DEFINE_TUPLE_LEAF(3, d); +DEFINE_TUPLE_LEAF(4, e); +DEFINE_TUPLE_LEAF(5, f); +DEFINE_TUPLE_LEAF(6, g); +DEFINE_TUPLE_LEAF(7, h); + +#undef DEFINE_TUPLE_LEAF + +// Deprecated compat aliases +// TODO(cef): Remove this code when cef_runnable.h is deleted. + +using Tuple0 = Tuple<>; +template +using Tuple1 = Tuple; +template +using Tuple2 = Tuple; +template +using Tuple3 = Tuple; +template +using Tuple4 = Tuple; +template +using Tuple5 = Tuple; +template +using Tuple6 = Tuple; +template +using Tuple7 = Tuple; +template +using Tuple8 = Tuple; + +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/tuple.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_bind_helpers.h" + +// Traits ---------------------------------------------------------------------- +// +// A simple traits class for tuple arguments. +// +// ValueType: the bare, nonref version of a type (same as the type for nonrefs). +// RefType: the ref version of a type (same as the type for refs). +// ParamType: what type to pass to functions (refs should not be constified). + +template +struct TupleTraits { + typedef P ValueType; + typedef P& RefType; + typedef const P& ParamType; +}; + +template +struct TupleTraits { + typedef P ValueType; + typedef P& RefType; + typedef P& ParamType; +}; + +template +struct TupleTypes { }; + +// Tuple ----------------------------------------------------------------------- +// +// This set of classes is useful for bundling 0 or more heterogeneous data types +// into a single variable. The advantage of this is that it greatly simplifies +// function objects that need to take an arbitrary number of parameters; see +// RunnableMethod and IPC::MessageWithTuple. +// +// Tuple0 is supplied to act as a 'void' type. It can be used, for example, +// when dispatching to a function that accepts no arguments (see the +// Dispatchers below). +// Tuple1 is rarely useful. One such use is when A is non-const ref that you +// want filled by the dispatchee, and the tuple is merely a container for that +// output (a "tier"). See MakeRefTuple and its usages. + +struct Tuple0 { + typedef Tuple0 ValueTuple; + typedef Tuple0 RefTuple; + typedef Tuple0 ParamTuple; +}; + +template +struct Tuple1 { + public: + typedef A TypeA; + + Tuple1() {} + explicit Tuple1(typename TupleTraits::ParamType a) : a(a) {} + + A a; +}; + +template +struct Tuple2 { + public: + typedef A TypeA; + typedef B TypeB; + + Tuple2() {} + Tuple2(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b) + : a(a), b(b) { + } + + A a; + B b; +}; + +template +struct Tuple3 { + public: + typedef A TypeA; + typedef B TypeB; + typedef C TypeC; + + Tuple3() {} + Tuple3(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c) + : a(a), b(b), c(c){ + } + + A a; + B b; + C c; +}; + +template +struct Tuple4 { + public: + typedef A TypeA; + typedef B TypeB; + typedef C TypeC; + typedef D TypeD; + + Tuple4() {} + Tuple4(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d) + : a(a), b(b), c(c), d(d) { + } + + A a; + B b; + C c; + D d; +}; + +template +struct Tuple5 { + public: + typedef A TypeA; + typedef B TypeB; + typedef C TypeC; + typedef D TypeD; + typedef E TypeE; + + Tuple5() {} + Tuple5(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e) + : a(a), b(b), c(c), d(d), e(e) { + } + + A a; + B b; + C c; + D d; + E e; +}; + +template +struct Tuple6 { + public: + typedef A TypeA; + typedef B TypeB; + typedef C TypeC; + typedef D TypeD; + typedef E TypeE; + typedef F TypeF; + + Tuple6() {} + Tuple6(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e, + typename TupleTraits::ParamType f) + : a(a), b(b), c(c), d(d), e(e), f(f) { + } + + A a; + B b; + C c; + D d; + E e; + F f; +}; + +template +struct Tuple7 { + public: + typedef A TypeA; + typedef B TypeB; + typedef C TypeC; + typedef D TypeD; + typedef E TypeE; + typedef F TypeF; + typedef G TypeG; + + Tuple7() {} + Tuple7(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e, + typename TupleTraits::ParamType f, + typename TupleTraits::ParamType g) + : a(a), b(b), c(c), d(d), e(e), f(f), g(g) { + } + + A a; + B b; + C c; + D d; + E e; + F f; + G g; +}; + +template +struct Tuple8 { + public: + typedef A TypeA; + typedef B TypeB; + typedef C TypeC; + typedef D TypeD; + typedef E TypeE; + typedef F TypeF; + typedef G TypeG; + typedef H TypeH; + + Tuple8() {} + Tuple8(typename TupleTraits::ParamType a, + typename TupleTraits::ParamType b, + typename TupleTraits::ParamType c, + typename TupleTraits::ParamType d, + typename TupleTraits::ParamType e, + typename TupleTraits::ParamType f, + typename TupleTraits::ParamType g, + typename TupleTraits::ParamType h) + : a(a), b(b), c(c), d(d), e(e), f(f), g(g), h(h) { + } + + A a; + B b; + C c; + D d; + E e; + F f; + G g; + H h; +}; + +// Tuple types ---------------------------------------------------------------- +// +// Allows for selection of ValueTuple/RefTuple/ParamTuple without needing the +// definitions of class types the tuple takes as parameters. + +template <> +struct TupleTypes< Tuple0 > { + typedef Tuple0 ValueTuple; + typedef Tuple0 RefTuple; + typedef Tuple0 ParamTuple; +}; + +template +struct TupleTypes< Tuple1 > { + typedef Tuple1::ValueType> ValueTuple; + typedef Tuple1::RefType> RefTuple; + typedef Tuple1::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple2 > { + typedef Tuple2::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple2::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple2::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple3 > { + typedef Tuple3::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple3::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple3::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple4 > { + typedef Tuple4::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple4::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple4::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple5 > { + typedef Tuple5::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple5::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple5::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple6 > { + typedef Tuple6::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple6::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple6::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple7 > { + typedef Tuple7::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple7::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple7::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +template +struct TupleTypes< Tuple8 > { + typedef Tuple8::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType, + typename TupleTraits::ValueType> ValueTuple; +typedef Tuple8::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType, + typename TupleTraits::RefType> RefTuple; + typedef Tuple8::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType, + typename TupleTraits::ParamType> ParamTuple; +}; + +// Tuple creators ------------------------------------------------------------- +// +// Helper functions for constructing tuples while inferring the template +// argument types. + +inline Tuple0 MakeTuple() { + return Tuple0(); +} + +template +inline Tuple1 MakeTuple(const A& a) { + return Tuple1(a); +} + +template +inline Tuple2 MakeTuple(const A& a, const B& b) { + return Tuple2(a, b); +} + +template +inline Tuple3 MakeTuple(const A& a, const B& b, const C& c) { + return Tuple3(a, b, c); +} + +template +inline Tuple4 MakeTuple(const A& a, const B& b, const C& c, + const D& d) { + return Tuple4(a, b, c, d); +} + +template +inline Tuple5 MakeTuple(const A& a, const B& b, const C& c, + const D& d, const E& e) { + return Tuple5(a, b, c, d, e); +} + +template +inline Tuple6 MakeTuple(const A& a, const B& b, const C& c, + const D& d, const E& e, const F& f) { + return Tuple6(a, b, c, d, e, f); +} + +template +inline Tuple7 MakeTuple(const A& a, const B& b, const C& c, + const D& d, const E& e, const F& f, + const G& g) { + return Tuple7(a, b, c, d, e, f, g); +} + +template +inline Tuple8 MakeTuple(const A& a, const B& b, + const C& c, const D& d, + const E& e, const F& f, + const G& g, const H& h) { + return Tuple8(a, b, c, d, e, f, g, h); +} + +// The following set of helpers make what Boost refers to as "Tiers" - a tuple +// of references. + +template +inline Tuple1 MakeRefTuple(A& a) { + return Tuple1(a); +} + +template +inline Tuple2 MakeRefTuple(A& a, B& b) { + return Tuple2(a, b); +} + +template +inline Tuple3 MakeRefTuple(A& a, B& b, C& c) { + return Tuple3(a, b, c); +} + +template +inline Tuple4 MakeRefTuple(A& a, B& b, C& c, D& d) { + return Tuple4(a, b, c, d); +} + +template +inline Tuple5 MakeRefTuple(A& a, B& b, C& c, D& d, E& e) { + return Tuple5(a, b, c, d, e); +} + +template +inline Tuple6 MakeRefTuple(A& a, B& b, C& c, D& d, E& e, + F& f) { + return Tuple6(a, b, c, d, e, f); +} + +template +inline Tuple7 MakeRefTuple(A& a, B& b, C& c, D& d, + E& e, F& f, G& g) { + return Tuple7(a, b, c, d, e, f, g); +} + +template +inline Tuple8 MakeRefTuple(A& a, B& b, C& c, + D& d, E& e, F& f, + G& g, H& h) { + return Tuple8(a, b, c, d, e, f, g, h); +} + +// Dispatchers ---------------------------------------------------------------- +// +// Helper functions that call the given method on an object, with the unpacked +// tuple arguments. Notice that they all have the same number of arguments, +// so you need only write: +// DispatchToMethod(object, &Object::method, args); +// This is very useful for templated dispatchers, since they don't need to know +// what type |args| is. + +// Non-Static Dispatchers with no out params. + +template +inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& arg) { + (obj->*method)(); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, const A& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a)); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple2& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple7& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f), + base::cef_internal::UnwrapTraits::Unwrap(arg.g)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple8& arg) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f), + base::cef_internal::UnwrapTraits::Unwrap(arg.g), + base::cef_internal::UnwrapTraits::Unwrap(arg.h)); +} + +// Static Dispatchers with no out params. + +template +inline void DispatchToFunction(Function function, const Tuple0& arg) { + (*function)(); +} + +template +inline void DispatchToFunction(Function function, const A& arg) { + (*function)(arg); +} + +template +inline void DispatchToFunction(Function function, const Tuple1& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a)); +} + +template +inline void DispatchToFunction(Function function, const Tuple2& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b)); +} + +template +inline void DispatchToFunction(Function function, const Tuple3& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c)); +} + +template +inline void DispatchToFunction(Function function, + const Tuple4& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d)); +} + +template +inline void DispatchToFunction(Function function, + const Tuple5& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e)); +} + +template +inline void DispatchToFunction(Function function, + const Tuple6& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f)); +} + +template +inline void DispatchToFunction(Function function, + const Tuple7& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f), + base::cef_internal::UnwrapTraits::Unwrap(arg.g)); +} + +template +inline void DispatchToFunction(Function function, + const Tuple8& arg) { + (*function)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f), + base::cef_internal::UnwrapTraits::Unwrap(arg.g), + base::cef_internal::UnwrapTraits::Unwrap(arg.h)); +} + +// Dispatchers with 0 out param (as a Tuple0). + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple0& arg, Tuple0*) { + (obj->*method)(); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, const A& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg)); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple1& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a)); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple2& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e)); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& arg, Tuple0*) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(arg.a), + base::cef_internal::UnwrapTraits::Unwrap(arg.b), + base::cef_internal::UnwrapTraits::Unwrap(arg.c), + base::cef_internal::UnwrapTraits::Unwrap(arg.d), + base::cef_internal::UnwrapTraits::Unwrap(arg.e), + base::cef_internal::UnwrapTraits::Unwrap(arg.f)); +} + +// Dispatchers with 1 out param. + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple0& in, + Tuple1* out) { + (obj->*method)(&out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const InA& in, + Tuple1* out) { + (obj->*method)(in, &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple1& in, + Tuple1* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple1* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple1* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple1* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple1* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple1* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + base::cef_internal::UnwrapTraits::Unwrap(in.f), + &out->a); +} + +// Dispatchers with 2 out params. + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple0& in, + Tuple2* out) { + (obj->*method)(&out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const InA& in, + Tuple2* out) { + (obj->*method)(in, &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple1& in, + Tuple2* out) { + (obj->*method)( + base::cef_internal::UnwrapTraits::Unwrap(in.a), &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple2* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + &out->a, + &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple2* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + &out->a, + &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple2* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + &out->a, + &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple2* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + &out->a, + &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple2* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + base::cef_internal::UnwrapTraits::Unwrap(in.f), + &out->a, + &out->b); +} + +// Dispatchers with 3 out params. + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple0& in, + Tuple3* out) { + (obj->*method)(&out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const InA& in, + Tuple3* out) { + (obj->*method)(in, &out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple1& in, + Tuple3* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + &out->a, + &out->b, + &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple3* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + &out->a, + &out->b, + &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple3* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + &out->a, + &out->b, + &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple3* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + &out->a, + &out->b, + &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple3* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + &out->a, + &out->b, + &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple3* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + base::cef_internal::UnwrapTraits::Unwrap(in.f), + &out->a, + &out->b, + &out->c); +} + +// Dispatchers with 4 out params. + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple0& in, + Tuple4* out) { + (obj->*method)(&out->a, &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const InA& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in), + &out->a, + &out->b, + &out->c, + &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple1& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + &out->a, + &out->b, + &out->c, + &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + &out->a, + &out->b, + &out->c, + &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + &out->a, + &out->b, + &out->c, + &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + &out->a, + &out->b, + &out->c, + &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + &out->a, + &out->b, + &out->c, + &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple4* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + base::cef_internal::UnwrapTraits::Unwrap(in.f), + &out->a, + &out->b, + &out->c, + &out->d); +} + +// Dispatchers with 5 out params. + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple0& in, + Tuple5* out) { + (obj->*method)(&out->a, &out->b, &out->c, &out->d, &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const InA& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple1& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple5* out) { + (obj->*method)(base::cef_internal::UnwrapTraits::Unwrap(in.a), + base::cef_internal::UnwrapTraits::Unwrap(in.b), + base::cef_internal::UnwrapTraits::Unwrap(in.c), + base::cef_internal::UnwrapTraits::Unwrap(in.d), + base::cef_internal::UnwrapTraits::Unwrap(in.e), + base::cef_internal::UnwrapTraits::Unwrap(in.f), + &out->a, + &out->b, + &out->c, + &out->d, + &out->e); +} + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_TUPLE_H_ diff --git a/include/base/cef_weak_ptr.h b/include/base/cef_weak_ptr.h new file mode 100644 index 000000000..f2a50fc66 --- /dev/null +++ b/include/base/cef_weak_ptr.h @@ -0,0 +1,382 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. Portions copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Weak pointers are pointers to an object that do not affect its lifetime, +// and which may be invalidated (i.e. reset to NULL) by the object, or its +// owner, at any time, most commonly when the object is about to be deleted. + +// Weak pointers are useful when an object needs to be accessed safely by one +// or more objects other than its owner, and those callers can cope with the +// object vanishing and e.g. tasks posted to it being silently dropped. +// Reference-counting such an object would complicate the ownership graph and +// make it harder to reason about the object's lifetime. + +// EXAMPLE: +// +// class Controller { +// public: +// void SpawnWorker() { Worker::StartNew(weak_factory_.GetWeakPtr()); } +// void WorkComplete(const Result& result) { ... } +// private: +// // Member variables should appear before the WeakPtrFactory, to ensure +// // that any WeakPtrs to Controller are invalidated before its members +// // variable's destructors are executed, rendering them invalid. +// WeakPtrFactory weak_factory_; +// }; +// +// class Worker { +// public: +// static void StartNew(const WeakPtr& controller) { +// Worker* worker = new Worker(controller); +// // Kick off asynchronous processing... +// } +// private: +// Worker(const WeakPtr& controller) +// : controller_(controller) {} +// void DidCompleteAsynchronousProcessing(const Result& result) { +// if (controller_) +// controller_->WorkComplete(result); +// } +// WeakPtr controller_; +// }; +// +// With this implementation a caller may use SpawnWorker() to dispatch multiple +// Workers and subsequently delete the Controller, without waiting for all +// Workers to have completed. + +// ------------------------- IMPORTANT: Thread-safety ------------------------- + +// Weak pointers may be passed safely between threads, but must always be +// dereferenced and invalidated on the same thread otherwise checking the +// pointer would be racey. +// +// To ensure correct use, the first time a WeakPtr issued by a WeakPtrFactory +// is dereferenced, the factory and its WeakPtrs become bound to the calling +// thread, and cannot be dereferenced or invalidated on any other thread. Bound +// WeakPtrs can still be handed off to other threads, e.g. to use to post tasks +// back to object on the bound thread. +// +// Invalidating the factory's WeakPtrs un-binds it from the thread, allowing it +// to be passed for a different thread to use or delete it. + +#ifndef CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_ +#define CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_ +#pragma once + +#if defined(BASE_MEMORY_WEAK_PTR_H_) +// Do nothing if the Chromium header has already been included. +// This can happen in cases where Chromium code is used directly by the +// client application. When using Chromium code directly always include +// the Chromium header first to avoid type conflicts. +#elif defined(BUILDING_CEF_SHARED) +// When building CEF include the Chromium header directly. +#include "base/memory/weak_ptr.h" +#else // !BUILDING_CEF_SHARED +// The following is substantially similar to the Chromium implementation. +// If the Chromium implementation diverges the below implementation should be +// updated to match. + +#include "include/base/cef_basictypes.h" +#include "include/base/cef_logging.h" +#include "include/base/cef_ref_counted.h" +#include "include/base/cef_template_util.h" +#include "include/base/cef_thread_checker.h" + +namespace base { + +template class SupportsWeakPtr; +template class WeakPtr; + +namespace cef_internal { +// These classes are part of the WeakPtr implementation. +// DO NOT USE THESE CLASSES DIRECTLY YOURSELF. + +class WeakReference { + public: + // Although Flag is bound to a specific thread, it may be deleted from another + // via base::WeakPtr::~WeakPtr(). + class Flag : public RefCountedThreadSafe { + public: + Flag(); + + void Invalidate(); + bool IsValid() const; + + private: + friend class base::RefCountedThreadSafe; + + ~Flag(); + + // The current Chromium implementation uses SequenceChecker instead of + // ThreadChecker to support SequencedWorkerPools. CEF does not yet expose + // the concept of SequencedWorkerPools. + ThreadChecker thread_checker_; + bool is_valid_; + }; + + WeakReference(); + explicit WeakReference(const Flag* flag); + ~WeakReference(); + + bool is_valid() const; + + private: + scoped_refptr flag_; +}; + +class WeakReferenceOwner { + public: + WeakReferenceOwner(); + ~WeakReferenceOwner(); + + WeakReference GetRef() const; + + bool HasRefs() const { + return flag_.get() && !flag_->HasOneRef(); + } + + void Invalidate(); + + private: + mutable scoped_refptr flag_; +}; + +// This class simplifies the implementation of WeakPtr's type conversion +// constructor by avoiding the need for a public accessor for ref_. A +// WeakPtr cannot access the private members of WeakPtr, so this +// base class gives us a way to access ref_ in a protected fashion. +class WeakPtrBase { + public: + WeakPtrBase(); + ~WeakPtrBase(); + + protected: + explicit WeakPtrBase(const WeakReference& ref); + + WeakReference ref_; +}; + +// This class provides a common implementation of common functions that would +// otherwise get instantiated separately for each distinct instantiation of +// SupportsWeakPtr<>. +class SupportsWeakPtrBase { + public: + // A safe static downcast of a WeakPtr to WeakPtr. This + // conversion will only compile if there is exists a Base which inherits + // from SupportsWeakPtr. See base::AsWeakPtr() below for a helper + // function that makes calling this easier. + template + static WeakPtr StaticAsWeakPtr(Derived* t) { + typedef + is_convertible convertible; + COMPILE_ASSERT(convertible::value, + AsWeakPtr_argument_inherits_from_SupportsWeakPtr); + return AsWeakPtrImpl(t, *t); + } + + private: + // This template function uses type inference to find a Base of Derived + // which is an instance of SupportsWeakPtr. We can then safely + // static_cast the Base* to a Derived*. + template + static WeakPtr AsWeakPtrImpl( + Derived* t, const SupportsWeakPtr&) { + WeakPtr ptr = t->Base::AsWeakPtr(); + return WeakPtr(ptr.ref_, static_cast(ptr.ptr_)); + } +}; + +} // namespace cef_internal + +template class WeakPtrFactory; + +// The WeakPtr class holds a weak reference to |T*|. +// +// This class is designed to be used like a normal pointer. You should always +// null-test an object of this class before using it or invoking a method that +// may result in the underlying object being destroyed. +// +// EXAMPLE: +// +// class Foo { ... }; +// WeakPtr foo; +// if (foo) +// foo->method(); +// +template +class WeakPtr : public cef_internal::WeakPtrBase { + public: + WeakPtr() : ptr_(NULL) { + } + + // Allow conversion from U to T provided U "is a" T. Note that this + // is separate from the (implicit) copy constructor. + template + WeakPtr(const WeakPtr& other) : WeakPtrBase(other), ptr_(other.ptr_) { + } + + T* get() const { return ref_.is_valid() ? ptr_ : NULL; } + + T& operator*() const { + DCHECK(get() != NULL); + return *get(); + } + T* operator->() const { + DCHECK(get() != NULL); + return get(); + } + + // Allow WeakPtr to be used in boolean expressions, but not + // implicitly convertible to a real bool (which is dangerous). + // + // Note that this trick is only safe when the == and != operators + // are declared explicitly, as otherwise "weak_ptr1 == weak_ptr2" + // will compile but do the wrong thing (i.e., convert to Testable + // and then do the comparison). + private: + typedef T* WeakPtr::*Testable; + + public: + operator Testable() const { return get() ? &WeakPtr::ptr_ : NULL; } + + void reset() { + ref_ = cef_internal::WeakReference(); + ptr_ = NULL; + } + + private: + // Explicitly declare comparison operators as required by the bool + // trick, but keep them private. + template bool operator==(WeakPtr const&) const; + template bool operator!=(WeakPtr const&) const; + + friend class cef_internal::SupportsWeakPtrBase; + template friend class WeakPtr; + friend class SupportsWeakPtr; + friend class WeakPtrFactory; + + WeakPtr(const cef_internal::WeakReference& ref, T* ptr) + : WeakPtrBase(ref), + ptr_(ptr) { + } + + // This pointer is only valid when ref_.is_valid() is true. Otherwise, its + // value is undefined (as opposed to NULL). + T* ptr_; +}; + +// A class may be composed of a WeakPtrFactory and thereby +// control how it exposes weak pointers to itself. This is helpful if you only +// need weak pointers within the implementation of a class. This class is also +// useful when working with primitive types. For example, you could have a +// WeakPtrFactory that is used to pass around a weak reference to a bool. +template +class WeakPtrFactory { + public: + explicit WeakPtrFactory(T* ptr) : ptr_(ptr) { + } + + ~WeakPtrFactory() { + ptr_ = NULL; + } + + WeakPtr GetWeakPtr() { + DCHECK(ptr_); + return WeakPtr(weak_reference_owner_.GetRef(), ptr_); + } + + // Call this method to invalidate all existing weak pointers. + void InvalidateWeakPtrs() { + DCHECK(ptr_); + weak_reference_owner_.Invalidate(); + } + + // Call this method to determine if any weak pointers exist. + bool HasWeakPtrs() const { + DCHECK(ptr_); + return weak_reference_owner_.HasRefs(); + } + + private: + cef_internal::WeakReferenceOwner weak_reference_owner_; + T* ptr_; + DISALLOW_IMPLICIT_CONSTRUCTORS(WeakPtrFactory); +}; + +// A class may extend from SupportsWeakPtr to let others take weak pointers to +// it. This avoids the class itself implementing boilerplate to dispense weak +// pointers. However, since SupportsWeakPtr's destructor won't invalidate +// weak pointers to the class until after the derived class' members have been +// destroyed, its use can lead to subtle use-after-destroy issues. +template +class SupportsWeakPtr : public cef_internal::SupportsWeakPtrBase { + public: + SupportsWeakPtr() {} + + WeakPtr AsWeakPtr() { + return WeakPtr(weak_reference_owner_.GetRef(), static_cast(this)); + } + + protected: + ~SupportsWeakPtr() {} + + private: + cef_internal::WeakReferenceOwner weak_reference_owner_; + DISALLOW_COPY_AND_ASSIGN(SupportsWeakPtr); +}; + +// Helper function that uses type deduction to safely return a WeakPtr +// when Derived doesn't directly extend SupportsWeakPtr, instead it +// extends a Base that extends SupportsWeakPtr. +// +// EXAMPLE: +// class Base : public base::SupportsWeakPtr {}; +// class Derived : public Base {}; +// +// Derived derived; +// base::WeakPtr ptr = base::AsWeakPtr(&derived); +// +// Note that the following doesn't work (invalid type conversion) since +// Derived::AsWeakPtr() is WeakPtr SupportsWeakPtr::AsWeakPtr(), +// and there's no way to safely cast WeakPtr to WeakPtr at +// the caller. +// +// base::WeakPtr ptr = derived.AsWeakPtr(); // Fails. + +template +WeakPtr AsWeakPtr(Derived* t) { + return cef_internal::SupportsWeakPtrBase::StaticAsWeakPtr(t); +} + +} // namespace base + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_BASE_CEF_WEAK_PTR_H_ diff --git a/include/base/internal/cef_atomicops_atomicword_compat.h b/include/base/internal/cef_atomicops_atomicword_compat.h new file mode 100644 index 000000000..985f0f9b9 --- /dev/null +++ b/include/base/internal/cef_atomicops_atomicword_compat.h @@ -0,0 +1,126 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_atomicops.h +// instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_ATOMICWORD_COMPAT_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_ATOMICWORD_COMPAT_H_ + +// AtomicWord is a synonym for intptr_t, and Atomic32 is a synonym for int32, +// which in turn means int. On some LP32 platforms, intptr_t is an int, but +// on others, it's a long. When AtomicWord and Atomic32 are based on different +// fundamental types, their pointers are incompatible. +// +// This file defines function overloads to allow both AtomicWord and Atomic32 +// data to be used with this interface. +// +// On LP64 platforms, AtomicWord and Atomic64 are both always long, +// so this problem doesn't occur. + +#if !defined(ARCH_CPU_64_BITS) + +namespace base { +namespace subtle { + +inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr, + AtomicWord old_value, + AtomicWord new_value) { + return NoBarrier_CompareAndSwap( + reinterpret_cast(ptr), old_value, new_value); +} + +inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr, + AtomicWord new_value) { + return NoBarrier_AtomicExchange( + reinterpret_cast(ptr), new_value); +} + +inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr, + AtomicWord increment) { + return NoBarrier_AtomicIncrement( + reinterpret_cast(ptr), increment); +} + +inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr, + AtomicWord increment) { + return Barrier_AtomicIncrement( + reinterpret_cast(ptr), increment); +} + +inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, + AtomicWord old_value, + AtomicWord new_value) { + return base::subtle::Acquire_CompareAndSwap( + reinterpret_cast(ptr), old_value, new_value); +} + +inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, + AtomicWord old_value, + AtomicWord new_value) { + return base::subtle::Release_CompareAndSwap( + reinterpret_cast(ptr), old_value, new_value); +} + +inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) { + NoBarrier_Store( + reinterpret_cast(ptr), value); +} + +inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { + return base::subtle::Acquire_Store( + reinterpret_cast(ptr), value); +} + +inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { + return base::subtle::Release_Store( + reinterpret_cast(ptr), value); +} + +inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) { + return NoBarrier_Load( + reinterpret_cast(ptr)); +} + +inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { + return base::subtle::Acquire_Load( + reinterpret_cast(ptr)); +} + +inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { + return base::subtle::Release_Load( + reinterpret_cast(ptr)); +} + +} // namespace base::subtle +} // namespace base + +#endif // !defined(ARCH_CPU_64_BITS) + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_ATOMICWORD_COMPAT_H_ diff --git a/include/base/internal/cef_atomicops_mac.h b/include/base/internal/cef_atomicops_mac.h new file mode 100644 index 000000000..9f268dd67 --- /dev/null +++ b/include/base/internal/cef_atomicops_mac.h @@ -0,0 +1,223 @@ +// Copyright (c) 2012 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_atomicops.h +// instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_MAC_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_MAC_H_ + +#include + +namespace base { +namespace subtle { + +inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + Atomic32 prev_value; + do { + if (OSAtomicCompareAndSwap32(old_value, new_value, + const_cast(ptr))) { + return old_value; + } + prev_value = *ptr; + } while (prev_value == old_value); + return prev_value; +} + +inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, + Atomic32 new_value) { + Atomic32 old_value; + do { + old_value = *ptr; + } while (!OSAtomicCompareAndSwap32(old_value, new_value, + const_cast(ptr))); + return old_value; +} + +inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment) { + return OSAtomicAdd32(increment, const_cast(ptr)); +} + +inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment) { + return OSAtomicAdd32Barrier(increment, const_cast(ptr)); +} + +inline void MemoryBarrier() { + OSMemoryBarrier(); +} + +inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + Atomic32 prev_value; + do { + if (OSAtomicCompareAndSwap32Barrier(old_value, new_value, + const_cast(ptr))) { + return old_value; + } + prev_value = *ptr; + } while (prev_value == old_value); + return prev_value; +} + +inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + return Acquire_CompareAndSwap(ptr, old_value, new_value); +} + +inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { + *ptr = value; +} + +inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { + *ptr = value; + MemoryBarrier(); +} + +inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { + MemoryBarrier(); + *ptr = value; +} + +inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { + return *ptr; +} + +inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { + Atomic32 value = *ptr; + MemoryBarrier(); + return value; +} + +inline Atomic32 Release_Load(volatile const Atomic32* ptr) { + MemoryBarrier(); + return *ptr; +} + +#ifdef __LP64__ + +// 64-bit implementation on 64-bit platform + +inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + Atomic64 prev_value; + do { + if (OSAtomicCompareAndSwap64(old_value, new_value, + reinterpret_cast(ptr))) { + return old_value; + } + prev_value = *ptr; + } while (prev_value == old_value); + return prev_value; +} + +inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, + Atomic64 new_value) { + Atomic64 old_value; + do { + old_value = *ptr; + } while (!OSAtomicCompareAndSwap64(old_value, new_value, + reinterpret_cast(ptr))); + return old_value; +} + +inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, + Atomic64 increment) { + return OSAtomicAdd64(increment, reinterpret_cast(ptr)); +} + +inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, + Atomic64 increment) { + return OSAtomicAdd64Barrier(increment, + reinterpret_cast(ptr)); +} + +inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + Atomic64 prev_value; + do { + if (OSAtomicCompareAndSwap64Barrier( + old_value, new_value, reinterpret_cast(ptr))) { + return old_value; + } + prev_value = *ptr; + } while (prev_value == old_value); + return prev_value; +} + +inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + // The lib kern interface does not distinguish between + // Acquire and Release memory barriers; they are equivalent. + return Acquire_CompareAndSwap(ptr, old_value, new_value); +} + +inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { + *ptr = value; +} + +inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { + *ptr = value; + MemoryBarrier(); +} + +inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { + MemoryBarrier(); + *ptr = value; +} + +inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { + return *ptr; +} + +inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { + Atomic64 value = *ptr; + MemoryBarrier(); + return value; +} + +inline Atomic64 Release_Load(volatile const Atomic64* ptr) { + MemoryBarrier(); + return *ptr; +} + +#endif // defined(__LP64__) + +} // namespace base::subtle +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_MAC_H_ diff --git a/include/base/internal/cef_atomicops_x86_gcc.h b/include/base/internal/cef_atomicops_x86_gcc.h new file mode 100644 index 000000000..0e2139d95 --- /dev/null +++ b/include/base/internal/cef_atomicops_x86_gcc.h @@ -0,0 +1,265 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_atomicops.h +// instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_ + +// This struct is not part of the public API of this module; clients may not +// use it. +// Features of this x86. Values may not be correct before main() is run, +// but are set conservatively. +struct AtomicOps_x86CPUFeatureStruct { + bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence + // after acquire compare-and-swap. +}; +extern struct AtomicOps_x86CPUFeatureStruct + AtomicOps_Internalx86CPUFeatures; + +#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory") + +namespace base { +namespace subtle { + +// 32-bit low-level operations on any platform. + +inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + Atomic32 prev; + __asm__ __volatile__("lock; cmpxchgl %1,%2" + : "=a" (prev) + : "q" (new_value), "m" (*ptr), "0" (old_value) + : "memory"); + return prev; +} + +inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, + Atomic32 new_value) { + __asm__ __volatile__("xchgl %1,%0" // The lock prefix is implicit for xchg. + : "=r" (new_value) + : "m" (*ptr), "0" (new_value) + : "memory"); + return new_value; // Now it's the previous value. +} + +inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment) { + Atomic32 temp = increment; + __asm__ __volatile__("lock; xaddl %0,%1" + : "+r" (temp), "+m" (*ptr) + : : "memory"); + // temp now holds the old value of *ptr + return temp + increment; +} + +inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment) { + Atomic32 temp = increment; + __asm__ __volatile__("lock; xaddl %0,%1" + : "+r" (temp), "+m" (*ptr) + : : "memory"); + // temp now holds the old value of *ptr + if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { + __asm__ __volatile__("lfence" : : : "memory"); + } + return temp + increment; +} + +inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); + if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { + __asm__ __volatile__("lfence" : : : "memory"); + } + return x; +} + +inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + return NoBarrier_CompareAndSwap(ptr, old_value, new_value); +} + +inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { + *ptr = value; +} + +inline void MemoryBarrier() { + __asm__ __volatile__("mfence" : : : "memory"); +} + +inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { + *ptr = value; + MemoryBarrier(); +} + +inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { + ATOMICOPS_COMPILER_BARRIER(); + *ptr = value; // An x86 store acts as a release barrier. + // See comments in Atomic64 version of Release_Store(), below. +} + +inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { + return *ptr; +} + +inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { + Atomic32 value = *ptr; // An x86 load acts as a acquire barrier. + // See comments in Atomic64 version of Release_Store(), below. + ATOMICOPS_COMPILER_BARRIER(); + return value; +} + +inline Atomic32 Release_Load(volatile const Atomic32* ptr) { + MemoryBarrier(); + return *ptr; +} + +#if defined(__x86_64__) + +// 64-bit low-level operations on 64-bit platform. + +inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + Atomic64 prev; + __asm__ __volatile__("lock; cmpxchgq %1,%2" + : "=a" (prev) + : "q" (new_value), "m" (*ptr), "0" (old_value) + : "memory"); + return prev; +} + +inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, + Atomic64 new_value) { + __asm__ __volatile__("xchgq %1,%0" // The lock prefix is implicit for xchg. + : "=r" (new_value) + : "m" (*ptr), "0" (new_value) + : "memory"); + return new_value; // Now it's the previous value. +} + +inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, + Atomic64 increment) { + Atomic64 temp = increment; + __asm__ __volatile__("lock; xaddq %0,%1" + : "+r" (temp), "+m" (*ptr) + : : "memory"); + // temp now contains the previous value of *ptr + return temp + increment; +} + +inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, + Atomic64 increment) { + Atomic64 temp = increment; + __asm__ __volatile__("lock; xaddq %0,%1" + : "+r" (temp), "+m" (*ptr) + : : "memory"); + // temp now contains the previous value of *ptr + if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { + __asm__ __volatile__("lfence" : : : "memory"); + } + return temp + increment; +} + +inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { + *ptr = value; +} + +inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { + *ptr = value; + MemoryBarrier(); +} + +inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { + ATOMICOPS_COMPILER_BARRIER(); + + *ptr = value; // An x86 store acts as a release barrier + // for current AMD/Intel chips as of Jan 2008. + // See also Acquire_Load(), below. + + // When new chips come out, check: + // IA-32 Intel Architecture Software Developer's Manual, Volume 3: + // System Programming Guide, Chatper 7: Multiple-processor management, + // Section 7.2, Memory Ordering. + // Last seen at: + // http://developer.intel.com/design/pentium4/manuals/index_new.htm + // + // x86 stores/loads fail to act as barriers for a few instructions (clflush + // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are + // not generated by the compiler, and are rare. Users of these instructions + // need to know about cache behaviour in any case since all of these involve + // either flushing cache lines or non-temporal cache hints. +} + +inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { + return *ptr; +} + +inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { + Atomic64 value = *ptr; // An x86 load acts as a acquire barrier, + // for current AMD/Intel chips as of Jan 2008. + // See also Release_Store(), above. + ATOMICOPS_COMPILER_BARRIER(); + return value; +} + +inline Atomic64 Release_Load(volatile const Atomic64* ptr) { + MemoryBarrier(); + return *ptr; +} + +inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value); + if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) { + __asm__ __volatile__("lfence" : : : "memory"); + } + return x; +} + +inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + return NoBarrier_CompareAndSwap(ptr, old_value, new_value); +} + +#endif // defined(__x86_64__) + +} // namespace base::subtle +} // namespace base + +#undef ATOMICOPS_COMPILER_BARRIER + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_ diff --git a/include/base/internal/cef_atomicops_x86_msvc.h b/include/base/internal/cef_atomicops_x86_msvc.h new file mode 100644 index 000000000..12bb0f468 --- /dev/null +++ b/include/base/internal/cef_atomicops_x86_msvc.h @@ -0,0 +1,224 @@ +// Copyright (c) 2008 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_atomicops.h +// instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_MSVC_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_MSVC_H_ + +#include + +#include + +#include "include/base/cef_macros.h" + +#if defined(ARCH_CPU_64_BITS) +// windows.h #defines this (only on x64). This causes problems because the +// public API also uses MemoryBarrier at the public name for this fence. So, on +// X64, undef it, and call its documented +// (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx) +// implementation directly. +#undef MemoryBarrier +#endif + +namespace base { +namespace subtle { + +inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + LONG result = _InterlockedCompareExchange( + reinterpret_cast(ptr), + static_cast(new_value), + static_cast(old_value)); + return static_cast(result); +} + +inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr, + Atomic32 new_value) { + LONG result = _InterlockedExchange( + reinterpret_cast(ptr), + static_cast(new_value)); + return static_cast(result); +} + +inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment) { + return _InterlockedExchangeAdd( + reinterpret_cast(ptr), + static_cast(increment)) + increment; +} + +inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr, + Atomic32 increment) { + return Barrier_AtomicIncrement(ptr, increment); +} + +#if !(defined(_MSC_VER) && _MSC_VER >= 1400) +#error "We require at least vs2005 for MemoryBarrier" +#endif +inline void MemoryBarrier() { +#if defined(ARCH_CPU_64_BITS) + // See #undef and note at the top of this file. + __faststorefence(); +#else + // We use MemoryBarrier from WinNT.h + ::MemoryBarrier(); +#endif +} + +inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + return NoBarrier_CompareAndSwap(ptr, old_value, new_value); +} + +inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr, + Atomic32 old_value, + Atomic32 new_value) { + return NoBarrier_CompareAndSwap(ptr, old_value, new_value); +} + +inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) { + *ptr = value; +} + +inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) { + NoBarrier_AtomicExchange(ptr, value); + // acts as a barrier in this implementation +} + +inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) { + *ptr = value; // works w/o barrier for current Intel chips as of June 2005 + // See comments in Atomic64 version of Release_Store() below. +} + +inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { + return *ptr; +} + +inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) { + Atomic32 value = *ptr; + return value; +} + +inline Atomic32 Release_Load(volatile const Atomic32* ptr) { + MemoryBarrier(); + return *ptr; +} + +#if defined(_WIN64) + +// 64-bit low-level operations on 64-bit platform. + +COMPILE_ASSERT(sizeof(Atomic64) == sizeof(PVOID), atomic_word_is_atomic); + +inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + PVOID result = InterlockedCompareExchangePointer( + reinterpret_cast(ptr), + reinterpret_cast(new_value), reinterpret_cast(old_value)); + return reinterpret_cast(result); +} + +inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr, + Atomic64 new_value) { + PVOID result = InterlockedExchangePointer( + reinterpret_cast(ptr), + reinterpret_cast(new_value)); + return reinterpret_cast(result); +} + +inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr, + Atomic64 increment) { + return InterlockedExchangeAdd64( + reinterpret_cast(ptr), + static_cast(increment)) + increment; +} + +inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr, + Atomic64 increment) { + return Barrier_AtomicIncrement(ptr, increment); +} + +inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) { + *ptr = value; +} + +inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) { + NoBarrier_AtomicExchange(ptr, value); + // acts as a barrier in this implementation +} + +inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) { + *ptr = value; // works w/o barrier for current Intel chips as of June 2005 + + // When new chips come out, check: + // IA-32 Intel Architecture Software Developer's Manual, Volume 3: + // System Programming Guide, Chatper 7: Multiple-processor management, + // Section 7.2, Memory Ordering. + // Last seen at: + // http://developer.intel.com/design/pentium4/manuals/index_new.htm +} + +inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) { + return *ptr; +} + +inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) { + Atomic64 value = *ptr; + return value; +} + +inline Atomic64 Release_Load(volatile const Atomic64* ptr) { + MemoryBarrier(); + return *ptr; +} + +inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + return NoBarrier_CompareAndSwap(ptr, old_value, new_value); +} + +inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr, + Atomic64 old_value, + Atomic64 new_value) { + return NoBarrier_CompareAndSwap(ptr, old_value, new_value); +} + + +#endif // defined(_WIN64) + +} // namespace base::subtle +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_MSVC_H_ diff --git a/include/base/internal/cef_bind_internal.h b/include/base/internal/cef_bind_internal.h new file mode 100644 index 000000000..cd32d256d --- /dev/null +++ b/include/base/internal/cef_bind_internal.h @@ -0,0 +1,2811 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_bind.h instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ + +#include "include/base/cef_bind_helpers.h" +#include "include/base/cef_build.h" +#include "include/base/cef_template_util.h" +#include "include/base/cef_weak_ptr.h" +#include "include/base/internal/cef_callback_internal.h" +#include "include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h" + +#if defined(OS_WIN) +#include "include/base/internal/cef_bind_internal_win.h" +#endif + +namespace base { +namespace cef_internal { + +// See base/callback.h for user documentation. +// +// +// CONCEPTS: +// Runnable -- A type (really a type class) that has a single Run() method +// and a RunType typedef that corresponds to the type of Run(). +// A Runnable can declare that it should treated like a method +// call by including a typedef named IsMethod. The value of +// this typedef is NOT inspected, only the existence. When a +// Runnable declares itself a method, Bind() will enforce special +// refcounting + WeakPtr handling semantics for the first +// parameter which is expected to be an object. +// Functor -- A copyable type representing something that should be called. +// All function pointers, Callback<>, and Runnables are functors +// even if the invocation syntax differs. +// RunType -- A function type (as opposed to function _pointer_ type) for +// a Run() function. Usually just a convenience typedef. +// (Bound)ArgsType -- A function type that is being (ab)used to store the +// types of set of arguments. The "return" type is always +// void here. We use this hack so that we do not need +// a new type name for each arity of type. (eg., +// BindState1, BindState2). This makes forward +// declarations and friending much much easier. +// +// Types: +// RunnableAdapter<> -- Wraps the various "function" pointer types into an +// object that adheres to the Runnable interface. +// There are |3*ARITY| RunnableAdapter types. +// FunctionTraits<> -- Type traits that unwrap a function signature into a +// a set of easier to use typedefs. Used mainly for +// compile time asserts. +// There are |ARITY| FunctionTraits types. +// ForceVoidReturn<> -- Helper class for translating function signatures to +// equivalent forms with a "void" return type. +// There are |ARITY| ForceVoidReturn types. +// FunctorTraits<> -- Type traits used determine the correct RunType and +// RunnableType for a Functor. This is where function +// signature adapters are applied. +// There are |ARITY| ForceVoidReturn types. +// MakeRunnable<> -- Takes a Functor and returns an object in the Runnable +// type class that represents the underlying Functor. +// There are |O(1)| MakeRunnable types. +// InvokeHelper<> -- Take a Runnable + arguments and actully invokes it. +// Handle the differing syntaxes needed for WeakPtr<> support, +// and for ignoring return values. This is separate from +// Invoker to avoid creating multiple version of Invoker<> +// which grows at O(n^2) with the arity. +// There are |k*ARITY| InvokeHelper types. +// Invoker<> -- Unwraps the curried parameters and executes the Runnable. +// There are |(ARITY^2 + ARITY)/2| Invoketypes. +// BindState<> -- Stores the curried parameters, and is the main entry point +// into the Bind() system, doing most of the type resolution. +// There are ARITY BindState types. + +// RunnableAdapter<> +// +// The RunnableAdapter<> templates provide a uniform interface for invoking +// a function pointer, method pointer, or const method pointer. The adapter +// exposes a Run() method with an appropriate signature. Using this wrapper +// allows for writing code that supports all three pointer types without +// undue repetition. Without it, a lot of code would need to be repeated 3 +// times. +// +// For method pointers and const method pointers the first argument to Run() +// is considered to be the received of the method. This is similar to STL's +// mem_fun(). +// +// This class also exposes a RunType typedef that is the function type of the +// Run() function. +// +// If and only if the wrapper contains a method or const method pointer, an +// IsMethod typedef is exposed. The existence of this typedef (NOT the value) +// marks that the wrapper should be considered a method wrapper. + +template +class RunnableAdapter; + +// Function: Arity 0. +template +class RunnableAdapter { + public: + typedef R (RunType)(); + + explicit RunnableAdapter(R(*function)()) + : function_(function) { + } + + R Run() { + return function_(); + } + + private: + R (*function_)(); +}; + +// Method: Arity 0. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)()) + : method_(method) { + } + + R Run(T* object) { + return (object->*method_)(); + } + + private: + R (T::*method_)(); +}; + +// Const Method: Arity 0. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)() const) + : method_(method) { + } + + R Run(const T* object) { + return (object->*method_)(); + } + + private: + R (T::*method_)() const; +}; + +// Function: Arity 1. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1); + + explicit RunnableAdapter(R(*function)(A1)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1) { + return function_(CallbackForward(a1)); + } + + private: + R (*function_)(A1); +}; + +// Method: Arity 1. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1) { + return (object->*method_)(CallbackForward(a1)); + } + + private: + R (T::*method_)(A1); +}; + +// Const Method: Arity 1. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1) { + return (object->*method_)(CallbackForward(a1)); + } + + private: + R (T::*method_)(A1) const; +}; + +// Function: Arity 2. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2); + + explicit RunnableAdapter(R(*function)(A1, A2)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { + return function_(CallbackForward(a1), CallbackForward(a2)); + } + + private: + R (*function_)(A1, A2); +}; + +// Method: Arity 2. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1, A2); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2)); + } + + private: + R (T::*method_)(A1, A2); +}; + +// Const Method: Arity 2. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1, A2); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2)); + } + + private: + R (T::*method_)(A1, A2) const; +}; + +// Function: Arity 3. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3); + + explicit RunnableAdapter(R(*function)(A1, A2, A3)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { + return function_(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3)); + } + + private: + R (*function_)(A1, A2, A3); +}; + +// Method: Arity 3. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1, A2, A3); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3)); + } + + private: + R (T::*method_)(A1, A2, A3); +}; + +// Const Method: Arity 3. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1, A2, A3); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3)); + } + + private: + R (T::*method_)(A1, A2, A3) const; +}; + +// Function: Arity 4. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4); + + explicit RunnableAdapter(R(*function)(A1, A2, A3, A4)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { + return function_(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4)); + } + + private: + R (*function_)(A1, A2, A3, A4); +}; + +// Method: Arity 4. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1, A2, A3, A4); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4)); + } + + private: + R (T::*method_)(A1, A2, A3, A4); +}; + +// Const Method: Arity 4. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1, A2, A3, A4); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4)); + } + + private: + R (T::*method_)(A1, A2, A3, A4) const; +}; + +// Function: Arity 5. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5); + + explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { + return function_(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + } + + private: + R (*function_)(A1, A2, A3, A4, A5); +}; + +// Method: Arity 5. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1, A2, A3, A4, A5); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + } + + private: + R (T::*method_)(A1, A2, A3, A4, A5); +}; + +// Const Method: Arity 5. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1, A2, A3, A4, A5); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + } + + private: + R (T::*method_)(A1, A2, A3, A4, A5) const; +}; + +// Function: Arity 6. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5, A6); + + explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5, A6)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { + return function_(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6)); + } + + private: + R (*function_)(A1, A2, A3, A4, A5, A6); +}; + +// Method: Arity 6. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1, A2, A3, A4, A5, A6); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6)); + } + + private: + R (T::*method_)(A1, A2, A3, A4, A5, A6); +}; + +// Const Method: Arity 6. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1, A2, A3, A4, A5, A6); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6)); + } + + private: + R (T::*method_)(A1, A2, A3, A4, A5, A6) const; +}; + +// Function: Arity 7. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7); + + explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5, A6, A7)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { + return function_(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6), CallbackForward(a7)); + } + + private: + R (*function_)(A1, A2, A3, A4, A5, A6, A7); +}; + +// Method: Arity 7. +template +class RunnableAdapter { + public: + typedef R (RunType)(T*, A1, A2, A3, A4, A5, A6, A7); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6, A7)) + : method_(method) { + } + + R Run(T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6), CallbackForward(a7)); + } + + private: + R (T::*method_)(A1, A2, A3, A4, A5, A6, A7); +}; + +// Const Method: Arity 7. +template +class RunnableAdapter { + public: + typedef R (RunType)(const T*, A1, A2, A3, A4, A5, A6, A7); + typedef true_type IsMethod; + + explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6, A7) const) + : method_(method) { + } + + R Run(const T* object, typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { + return (object->*method_)(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6), CallbackForward(a7)); + } + + private: + R (T::*method_)(A1, A2, A3, A4, A5, A6, A7) const; +}; + + +// FunctionTraits<> +// +// Breaks a function signature apart into typedefs for easier introspection. +template +struct FunctionTraits; + +template +struct FunctionTraits { + typedef R ReturnType; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; + typedef A2 A2Type; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; + typedef A2 A2Type; + typedef A3 A3Type; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; + typedef A2 A2Type; + typedef A3 A3Type; + typedef A4 A4Type; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; + typedef A2 A2Type; + typedef A3 A3Type; + typedef A4 A4Type; + typedef A5 A5Type; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; + typedef A2 A2Type; + typedef A3 A3Type; + typedef A4 A4Type; + typedef A5 A5Type; + typedef A6 A6Type; +}; + +template +struct FunctionTraits { + typedef R ReturnType; + typedef A1 A1Type; + typedef A2 A2Type; + typedef A3 A3Type; + typedef A4 A4Type; + typedef A5 A5Type; + typedef A6 A6Type; + typedef A7 A7Type; +}; + + +// ForceVoidReturn<> +// +// Set of templates that support forcing the function return type to void. +template +struct ForceVoidReturn; + +template +struct ForceVoidReturn { + typedef void(RunType)(); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1, A2); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1, A2, A3); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1, A2, A3, A4); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1, A2, A3, A4, A5); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1, A2, A3, A4, A5, A6); +}; + +template +struct ForceVoidReturn { + typedef void(RunType)(A1, A2, A3, A4, A5, A6, A7); +}; + + +// FunctorTraits<> +// +// See description at top of file. +template +struct FunctorTraits { + typedef RunnableAdapter RunnableType; + typedef typename RunnableType::RunType RunType; +}; + +template +struct FunctorTraits > { + typedef typename FunctorTraits::RunnableType RunnableType; + typedef typename ForceVoidReturn< + typename RunnableType::RunType>::RunType RunType; +}; + +template +struct FunctorTraits > { + typedef Callback RunnableType; + typedef typename Callback::RunType RunType; +}; + + +// MakeRunnable<> +// +// Converts a passed in functor to a RunnableType using type inference. + +template +typename FunctorTraits::RunnableType MakeRunnable(const T& t) { + return RunnableAdapter(t); +} + +template +typename FunctorTraits::RunnableType +MakeRunnable(const IgnoreResultHelper& t) { + return MakeRunnable(t.functor_); +} + +template +const typename FunctorTraits >::RunnableType& +MakeRunnable(const Callback& t) { + DCHECK(!t.is_null()); + return t; +} + + +// InvokeHelper<> +// +// There are 3 logical InvokeHelper<> specializations: normal, void-return, +// WeakCalls. +// +// The normal type just calls the underlying runnable. +// +// We need a InvokeHelper to handle void return types in order to support +// IgnoreResult(). Normally, if the Runnable's RunType had a void return, +// the template system would just accept "return functor.Run()" ignoring +// the fact that a void function is being used with return. This piece of +// sugar breaks though when the Runnable's RunType is not void. Thus, we +// need a partial specialization to change the syntax to drop the "return" +// from the invocation call. +// +// WeakCalls similarly need special syntax that is applied to the first +// argument to check if they should no-op themselves. +template +struct InvokeHelper; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable) { + return runnable.Run(); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable) { + runnable.Run(); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1) { + return runnable.Run(CallbackForward(a1)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1) { + runnable.Run(CallbackForward(a1)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get()); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2) { + return runnable.Run(CallbackForward(a1), CallbackForward(a2)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1, A2 a2) { + runnable.Run(CallbackForward(a1), CallbackForward(a2)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get(), CallbackForward(a2)); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3) { + return runnable.Run(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3) { + runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3)); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4) { + return runnable.Run(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4) { + runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, + A4 a4) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4)); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, + A5 a5) { + return runnable.Run(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { + runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4), CallbackForward(a5)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, + A4 a4, A5 a5) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4), CallbackForward(a5)); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, + A5 a5, A6 a6) { + return runnable.Run(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, + A6 a6) { + runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, + A4 a4, A5 a5, A6 a6) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6)); + } +}; + +template +struct InvokeHelper { + static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, + A5 a5, A6 a6, A7 a7) { + return runnable.Run(CallbackForward(a1), CallbackForward(a2), + CallbackForward(a3), CallbackForward(a4), CallbackForward(a5), + CallbackForward(a6), CallbackForward(a7)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, + A6 a6, A7 a7) { + runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); + } +}; + +template +struct InvokeHelper { + static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3, + A4 a4, A5 a5, A6 a6, A7 a7) { + if (!weak_ptr.get()) { + return; + } + runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3), + CallbackForward(a4), CallbackForward(a5), CallbackForward(a6), + CallbackForward(a7)); + } +}; + +#if !defined(_MSC_VER) + +template +struct InvokeHelper { + // WeakCalls are only supported for functions with a void return type. + // Otherwise, the function result would be undefined if the the WeakPtr<> + // is invalidated. + COMPILE_ASSERT(is_void::value, + weak_ptrs_can_only_bind_to_methods_without_return_values); +}; + +#endif + +// Invoker<> +// +// See description at the top of the file. +template +struct Invoker; + +// Arity 0 -> 0. +template +struct Invoker<0, StorageType, R()> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper + ::MakeItSo(storage->runnable_); + } +}; + +// Arity 1 -> 1. +template +struct Invoker<0, StorageType, R(X1)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1)> + ::MakeItSo(storage->runnable_, CallbackForward(x1)); + } +}; + +// Arity 1 -> 0. +template +struct Invoker<1, StorageType, R(X1)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1)); + } +}; + +// Arity 2 -> 2. +template +struct Invoker<0, StorageType, R(X1, X2)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1, X2); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1, + typename CallbackParamTraits::ForwardType x2)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2)); + } +}; + +// Arity 2 -> 1. +template +struct Invoker<1, StorageType, R(X1, X2)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X2); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x2) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper::ForwardType x2)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2)); + } +}; + +// Arity 2 -> 0. +template +struct Invoker<2, StorageType, R(X1, X2)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2)); + } +}; + +// Arity 3 -> 3. +template +struct Invoker<0, StorageType, R(X1, X2, X3)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1, X2, X3); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3)); + } +}; + +// Arity 3 -> 2. +template +struct Invoker<1, StorageType, R(X1, X2, X3)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X2, X3); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper::ForwardType x2, + typename CallbackParamTraits::ForwardType x3)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3)); + } +}; + +// Arity 3 -> 1. +template +struct Invoker<2, StorageType, R(X1, X2, X3)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X3); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x3) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + return InvokeHelper::ForwardType x3)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3)); + } +}; + +// Arity 3 -> 0. +template +struct Invoker<3, StorageType, R(X1, X2, X3)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3)); + } +}; + +// Arity 4 -> 4. +template +struct Invoker<0, StorageType, R(X1, X2, X3, X4)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1, X2, X3, X4); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4)); + } +}; + +// Arity 4 -> 3. +template +struct Invoker<1, StorageType, R(X1, X2, X3, X4)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X2, X3, X4); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4)); + } +}; + +// Arity 4 -> 2. +template +struct Invoker<2, StorageType, R(X1, X2, X3, X4)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X3, X4); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + return InvokeHelper::ForwardType x3, + typename CallbackParamTraits::ForwardType x4)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4)); + } +}; + +// Arity 4 -> 1. +template +struct Invoker<3, StorageType, R(X1, X2, X3, X4)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X4); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x4) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + return InvokeHelper::ForwardType x4)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4)); + } +}; + +// Arity 4 -> 0. +template +struct Invoker<4, StorageType, R(X1, X2, X3, X4)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4)); + } +}; + +// Arity 5 -> 5. +template +struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1, X2, X3, X4, X5); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); + } +}; + +// Arity 5 -> 4. +template +struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X2, X3, X4, X5); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); + } +}; + +// Arity 5 -> 3. +template +struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X3, X4, X5); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + return InvokeHelper::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); + } +}; + +// Arity 5 -> 2. +template +struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X4, X5); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + return InvokeHelper::ForwardType x4, + typename CallbackParamTraits::ForwardType x5)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); + } +}; + +// Arity 5 -> 1. +template +struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X5); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x5) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + return InvokeHelper::ForwardType x5)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); + } +}; + +// Arity 5 -> 0. +template +struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + typename Bound5UnwrapTraits::ForwardType x5 = + Bound5UnwrapTraits::Unwrap(storage->p5_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5)); + } +}; + +// Arity 6 -> 6. +template +struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1, X2, X3, X4, X5, X6); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 6 -> 5. +template +struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X2, X3, X4, X5, X6); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 6 -> 4. +template +struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X3, X4, X5, X6); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + return InvokeHelper::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 6 -> 3. +template +struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X4, X5, X6); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + return InvokeHelper::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 6 -> 2. +template +struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X5, X6); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + return InvokeHelper::ForwardType x5, + typename CallbackParamTraits::ForwardType x6)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 6 -> 1. +template +struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X6); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x6) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + typename Bound5UnwrapTraits::ForwardType x5 = + Bound5UnwrapTraits::Unwrap(storage->p5_); + return InvokeHelper::ForwardType x6)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 6 -> 0. +template +struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits; + typedef typename StorageType::Bound6UnwrapTraits Bound6UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + typename Bound5UnwrapTraits::ForwardType x5 = + Bound5UnwrapTraits::Unwrap(storage->p5_); + typename Bound6UnwrapTraits::ForwardType x6 = + Bound6UnwrapTraits::Unwrap(storage->p6_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6)); + } +}; + +// Arity 7 -> 7. +template +struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X1, X2, X3, X4, X5, X6, X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + + return InvokeHelper::ForwardType x1, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 6. +template +struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X2, X3, X4, X5, X6, X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + return InvokeHelper::ForwardType x2, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 5. +template +struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X3, X4, X5, X6, X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + return InvokeHelper::ForwardType x3, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 4. +template +struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X4, X5, X6, X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + return InvokeHelper::ForwardType x4, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 3. +template +struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X5, X6, X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + return InvokeHelper::ForwardType x5, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 2. +template +struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X6, X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x6, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + typename Bound5UnwrapTraits::ForwardType x5 = + Bound5UnwrapTraits::Unwrap(storage->p5_); + return InvokeHelper::ForwardType x6, + typename CallbackParamTraits::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 1. +template +struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*, + typename CallbackParamTraits::ForwardType); + + typedef R(UnboundRunType)(X7); + + static R Run(BindStateBase* base, + typename CallbackParamTraits::ForwardType x7) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits; + typedef typename StorageType::Bound6UnwrapTraits Bound6UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + typename Bound5UnwrapTraits::ForwardType x5 = + Bound5UnwrapTraits::Unwrap(storage->p5_); + typename Bound6UnwrapTraits::ForwardType x6 = + Bound6UnwrapTraits::Unwrap(storage->p6_); + return InvokeHelper::ForwardType x7)> + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + +// Arity 7 -> 0. +template +struct Invoker<7, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> { + typedef R(RunType)(BindStateBase*); + + typedef R(UnboundRunType)(); + + static R Run(BindStateBase* base) { + StorageType* storage = static_cast(base); + + // Local references to make debugger stepping easier. If in a debugger, + // you really want to warp ahead and step through the + // InvokeHelper<>::MakeItSo() call below. + typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits; + typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits; + typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits; + typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits; + typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits; + typedef typename StorageType::Bound6UnwrapTraits Bound6UnwrapTraits; + typedef typename StorageType::Bound7UnwrapTraits Bound7UnwrapTraits; + + typename Bound1UnwrapTraits::ForwardType x1 = + Bound1UnwrapTraits::Unwrap(storage->p1_); + typename Bound2UnwrapTraits::ForwardType x2 = + Bound2UnwrapTraits::Unwrap(storage->p2_); + typename Bound3UnwrapTraits::ForwardType x3 = + Bound3UnwrapTraits::Unwrap(storage->p3_); + typename Bound4UnwrapTraits::ForwardType x4 = + Bound4UnwrapTraits::Unwrap(storage->p4_); + typename Bound5UnwrapTraits::ForwardType x5 = + Bound5UnwrapTraits::Unwrap(storage->p5_); + typename Bound6UnwrapTraits::ForwardType x6 = + Bound6UnwrapTraits::Unwrap(storage->p6_); + typename Bound7UnwrapTraits::ForwardType x7 = + Bound7UnwrapTraits::Unwrap(storage->p7_); + return InvokeHelper + ::MakeItSo(storage->runnable_, CallbackForward(x1), + CallbackForward(x2), CallbackForward(x3), + CallbackForward(x4), CallbackForward(x5), + CallbackForward(x6), CallbackForward(x7)); + } +}; + + +// BindState<> +// +// This stores all the state passed into Bind() and is also where most +// of the template resolution magic occurs. +// +// Runnable is the functor we are binding arguments to. +// RunType is type of the Run() function that the Invoker<> should use. +// Normally, this is the same as the RunType of the Runnable, but it can +// be different if an adapter like IgnoreResult() has been used. +// +// BoundArgsType contains the storage type for all the bound arguments by +// (ab)using a function type. +template +struct BindState; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef false_type IsWeakCall; + typedef Invoker<0, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + explicit BindState(const Runnable& runnable) + : runnable_(runnable) { + } + + virtual ~BindState() { } + + RunnableType runnable_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<1, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1) + : runnable_(runnable), + p1_(p1) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<2, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + typedef UnwrapTraits Bound2UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1, const P2& p2) + : runnable_(runnable), + p1_(p1), + p2_(p2) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; + P2 p2_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<3, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + typedef UnwrapTraits Bound2UnwrapTraits; + typedef UnwrapTraits Bound3UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3) + : runnable_(runnable), + p1_(p1), + p2_(p2), + p3_(p3) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; + P2 p2_; + P3 p3_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<4, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + typedef UnwrapTraits Bound2UnwrapTraits; + typedef UnwrapTraits Bound3UnwrapTraits; + typedef UnwrapTraits Bound4UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, + const P4& p4) + : runnable_(runnable), + p1_(p1), + p2_(p2), + p3_(p3), + p4_(p4) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; + P2 p2_; + P3 p3_; + P4 p4_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<5, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + typedef UnwrapTraits Bound2UnwrapTraits; + typedef UnwrapTraits Bound3UnwrapTraits; + typedef UnwrapTraits Bound4UnwrapTraits; + typedef UnwrapTraits Bound5UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, + const P4& p4, const P5& p5) + : runnable_(runnable), + p1_(p1), + p2_(p2), + p3_(p3), + p4_(p4), + p5_(p5) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; + P2 p2_; + P3 p3_; + P4 p4_; + P5 p5_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<6, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + typedef UnwrapTraits Bound2UnwrapTraits; + typedef UnwrapTraits Bound3UnwrapTraits; + typedef UnwrapTraits Bound4UnwrapTraits; + typedef UnwrapTraits Bound5UnwrapTraits; + typedef UnwrapTraits Bound6UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, + const P4& p4, const P5& p5, const P6& p6) + : runnable_(runnable), + p1_(p1), + p2_(p2), + p3_(p3), + p4_(p4), + p5_(p5), + p6_(p6) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; + P2 p2_; + P3 p3_; + P4 p4_; + P5 p5_; + P6 p6_; +}; + +template +struct BindState : public BindStateBase { + typedef Runnable RunnableType; + typedef IsWeakMethod::value, P1> IsWeakCall; + typedef Invoker<7, BindState, RunType> InvokerType; + typedef typename InvokerType::UnboundRunType UnboundRunType; + + // Convenience typedefs for bound argument types. + typedef UnwrapTraits Bound1UnwrapTraits; + typedef UnwrapTraits Bound2UnwrapTraits; + typedef UnwrapTraits Bound3UnwrapTraits; + typedef UnwrapTraits Bound4UnwrapTraits; + typedef UnwrapTraits Bound5UnwrapTraits; + typedef UnwrapTraits Bound6UnwrapTraits; + typedef UnwrapTraits Bound7UnwrapTraits; + + BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3, + const P4& p4, const P5& p5, const P6& p6, const P7& p7) + : runnable_(runnable), + p1_(p1), + p2_(p2), + p3_(p3), + p4_(p4), + p5_(p5), + p6_(p6), + p7_(p7) { + MaybeRefcount::value, P1>::AddRef(p1_); + } + + virtual ~BindState() { MaybeRefcount::value, + P1>::Release(p1_); } + + RunnableType runnable_; + P1 p1_; + P2 p2_; + P3 p3_; + P4 p4_; + P5 p5_; + P6 p6_; + P7 p7_; +}; + +} // namespace cef_internal +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_H_ diff --git a/include/base/internal/cef_bind_internal_win.h b/include/base/internal/cef_bind_internal_win.h new file mode 100644 index 000000000..1b061ccd0 --- /dev/null +++ b/include/base/internal/cef_bind_internal_win.h @@ -0,0 +1,390 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_bind.h instead. + +// Specializations of RunnableAdapter<> for Windows specific calling +// conventions. Please see base/bind_internal.h for more info. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_WIN_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_WIN_H_ + +// In the x64 architecture in Windows, __fastcall, __stdcall, etc, are all +// the same as __cdecl which would turn the following specializations into +// multiple definitions. +#if !defined(ARCH_CPU_X86_64) + +namespace base { +namespace cef_internal { + +template +class RunnableAdapter; + +// __stdcall Function: Arity 0. +template +class RunnableAdapter { + public: + typedef R (RunType)(); + + explicit RunnableAdapter(R(__stdcall *function)()) + : function_(function) { + } + + R Run() { + return function_(); + } + + private: + R (__stdcall *function_)(); +}; + +// __fastcall Function: Arity 0. +template +class RunnableAdapter { + public: + typedef R (RunType)(); + + explicit RunnableAdapter(R(__fastcall *function)()) + : function_(function) { + } + + R Run() { + return function_(); + } + + private: + R (__fastcall *function_)(); +}; + +// __stdcall Function: Arity 1. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1); + + explicit RunnableAdapter(R(__stdcall *function)(A1)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1) { + return function_(a1); + } + + private: + R (__stdcall *function_)(A1); +}; + +// __fastcall Function: Arity 1. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1); + + explicit RunnableAdapter(R(__fastcall *function)(A1)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1) { + return function_(a1); + } + + private: + R (__fastcall *function_)(A1); +}; + +// __stdcall Function: Arity 2. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2); + + explicit RunnableAdapter(R(__stdcall *function)(A1, A2)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { + return function_(a1, a2); + } + + private: + R (__stdcall *function_)(A1, A2); +}; + +// __fastcall Function: Arity 2. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2); + + explicit RunnableAdapter(R(__fastcall *function)(A1, A2)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2) { + return function_(a1, a2); + } + + private: + R (__fastcall *function_)(A1, A2); +}; + +// __stdcall Function: Arity 3. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3); + + explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { + return function_(a1, a2, a3); + } + + private: + R (__stdcall *function_)(A1, A2, A3); +}; + +// __fastcall Function: Arity 3. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3); + + explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3) { + return function_(a1, a2, a3); + } + + private: + R (__fastcall *function_)(A1, A2, A3); +}; + +// __stdcall Function: Arity 4. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4); + + explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { + return function_(a1, a2, a3, a4); + } + + private: + R (__stdcall *function_)(A1, A2, A3, A4); +}; + +// __fastcall Function: Arity 4. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4); + + explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4) { + return function_(a1, a2, a3, a4); + } + + private: + R (__fastcall *function_)(A1, A2, A3, A4); +}; + +// __stdcall Function: Arity 5. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5); + + explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4, A5)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { + return function_(a1, a2, a3, a4, a5); + } + + private: + R (__stdcall *function_)(A1, A2, A3, A4, A5); +}; + +// __fastcall Function: Arity 5. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5); + + explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4, A5)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5) { + return function_(a1, a2, a3, a4, a5); + } + + private: + R (__fastcall *function_)(A1, A2, A3, A4, A5); +}; + +// __stdcall Function: Arity 6. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5, A6); + + explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4, A5, A6)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { + return function_(a1, a2, a3, a4, a5, a6); + } + + private: + R (__stdcall *function_)(A1, A2, A3, A4, A5, A6); +}; + +// __fastcall Function: Arity 6. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5, A6); + + explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4, A5, A6)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6) { + return function_(a1, a2, a3, a4, a5, a6); + } + + private: + R (__fastcall *function_)(A1, A2, A3, A4, A5, A6); +}; + +// __stdcall Function: Arity 7. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7); + + explicit RunnableAdapter(R(__stdcall *function)(A1, A2, A3, A4, A5, A6, A7)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { + return function_(a1, a2, a3, a4, a5, a6, a7); + } + + private: + R (__stdcall *function_)(A1, A2, A3, A4, A5, A6, A7); +}; + +// __fastcall Function: Arity 7. +template +class RunnableAdapter { + public: + typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7); + + explicit RunnableAdapter(R(__fastcall *function)(A1, A2, A3, A4, A5, A6, A7)) + : function_(function) { + } + + R Run(typename CallbackParamTraits::ForwardType a1, + typename CallbackParamTraits::ForwardType a2, + typename CallbackParamTraits::ForwardType a3, + typename CallbackParamTraits::ForwardType a4, + typename CallbackParamTraits::ForwardType a5, + typename CallbackParamTraits::ForwardType a6, + typename CallbackParamTraits::ForwardType a7) { + return function_(a1, a2, a3, a4, a5, a6, a7); + } + + private: + R (__fastcall *function_)(A1, A2, A3, A4, A5, A6, A7); +}; + +} // namespace cef_internal +} // namespace base + +#endif // !defined(ARCH_CPU_X86_64) + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_BIND_INTERNAL_WIN_H_ diff --git a/include/base/internal/cef_callback_internal.h b/include/base/internal/cef_callback_internal.h new file mode 100644 index 000000000..8ed3af4ea --- /dev/null +++ b/include/base/internal/cef_callback_internal.h @@ -0,0 +1,205 @@ +// Copyright (c) 2012 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_bind.h or +// base/cef_callback.h instead. + +// This file contains utility functions and classes that help the +// implementation, and management of the Callback objects. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_CALLBACK_INTERNAL_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_CALLBACK_INTERNAL_H_ + +#include + +#include "include/base/cef_ref_counted.h" +#include "include/base/cef_scoped_ptr.h" + +template +class ScopedVector; + +namespace base { +namespace cef_internal { + +// BindStateBase is used to provide an opaque handle that the Callback +// class can use to represent a function object with bound arguments. It +// behaves as an existential type that is used by a corresponding +// DoInvoke function to perform the function execution. This allows +// us to shield the Callback class from the types of the bound argument via +// "type erasure." +class BindStateBase : public RefCountedThreadSafe { + protected: + friend class RefCountedThreadSafe; + virtual ~BindStateBase() {} +}; + +// Holds the Callback methods that don't require specialization to reduce +// template bloat. +class CallbackBase { + public: + // Returns true if Callback is null (doesn't refer to anything). + bool is_null() const { return bind_state_.get() == NULL; } + + // Returns the Callback into an uninitialized state. + void Reset(); + + protected: + // In C++, it is safe to cast function pointers to function pointers of + // another type. It is not okay to use void*. We create a InvokeFuncStorage + // that that can store our function pointer, and then cast it back to + // the original type on usage. + typedef void(*InvokeFuncStorage)(void); + + // Returns true if this callback equals |other|. |other| may be null. + bool Equals(const CallbackBase& other) const; + + // Allow initializing of |bind_state_| via the constructor to avoid default + // initialization of the scoped_refptr. We do not also initialize + // |polymorphic_invoke_| here because doing a normal assignment in the + // derived Callback templates makes for much nicer compiler errors. + explicit CallbackBase(BindStateBase* bind_state); + + // Force the destructor to be instantiated inside this translation unit so + // that our subclasses will not get inlined versions. Avoids more template + // bloat. + ~CallbackBase(); + + scoped_refptr bind_state_; + InvokeFuncStorage polymorphic_invoke_; +}; + +// A helper template to determine if given type is non-const move-only-type, +// i.e. if a value of the given type should be passed via .Pass() in a +// destructive way. +template struct IsMoveOnlyType { + template + static YesType Test(const typename U::MoveOnlyTypeForCPP03*); + + template + static NoType Test(...); + + static const bool value = sizeof(Test(0)) == sizeof(YesType) && + !is_const::value; +}; + +// This is a typetraits object that's used to take an argument type, and +// extract a suitable type for storing and forwarding arguments. +// +// In particular, it strips off references, and converts arrays to +// pointers for storage; and it avoids accidentally trying to create a +// "reference of a reference" if the argument is a reference type. +// +// This array type becomes an issue for storage because we are passing bound +// parameters by const reference. In this case, we end up passing an actual +// array type in the initializer list which C++ does not allow. This will +// break passing of C-string literals. +template ::value> +struct CallbackParamTraits { + typedef const T& ForwardType; + typedef T StorageType; +}; + +// The Storage should almost be impossible to trigger unless someone manually +// specifies type of the bind parameters. However, in case they do, +// this will guard against us accidentally storing a reference parameter. +// +// The ForwardType should only be used for unbound arguments. +template +struct CallbackParamTraits { + typedef T& ForwardType; + typedef T StorageType; +}; + +// Note that for array types, we implicitly add a const in the conversion. This +// means that it is not possible to bind array arguments to functions that take +// a non-const pointer. Trying to specialize the template based on a "const +// T[n]" does not seem to match correctly, so we are stuck with this +// restriction. +template +struct CallbackParamTraits { + typedef const T* ForwardType; + typedef const T* StorageType; +}; + +// See comment for CallbackParamTraits. +template +struct CallbackParamTraits { + typedef const T* ForwardType; + typedef const T* StorageType; +}; + +// Parameter traits for movable-but-not-copyable scopers. +// +// Callback<>/Bind() understands movable-but-not-copyable semantics where +// the type cannot be copied but can still have its state destructively +// transferred (aka. moved) to another instance of the same type by calling a +// helper function. When used with Bind(), this signifies transferal of the +// object's state to the target function. +// +// For these types, the ForwardType must not be a const reference, or a +// reference. A const reference is inappropriate, and would break const +// correctness, because we are implementing a destructive move. A non-const +// reference cannot be used with temporaries which means the result of a +// function or a cast would not be usable with Callback<> or Bind(). +template +struct CallbackParamTraits { + typedef T ForwardType; + typedef T StorageType; +}; + +// CallbackForward() is a very limited simulation of C++11's std::forward() +// used by the Callback/Bind system for a set of movable-but-not-copyable +// types. It is needed because forwarding a movable-but-not-copyable +// argument to another function requires us to invoke the proper move +// operator to create a rvalue version of the type. The supported types are +// whitelisted below as overloads of the CallbackForward() function. The +// default template compiles out to be a no-op. +// +// In C++11, std::forward would replace all uses of this function. However, it +// is impossible to implement a general std::forward with C++11 due to a lack +// of rvalue references. +// +// In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to +// simulate std::forward() and forward the result of one Callback as a +// parameter to another callback. This is to support Callbacks that return +// the movable-but-not-copyable types whitelisted above. +template +typename enable_if::value, T>::type& CallbackForward(T& t) { + return t; +} + +template +typename enable_if::value, T>::type CallbackForward(T& t) { + return t.Pass(); +} + +} // namespace cef_internal +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_CALLBACK_INTERNAL_H_ diff --git a/include/base/internal/cef_lock_impl.h b/include/base/internal/cef_lock_impl.h new file mode 100644 index 000000000..470547fe0 --- /dev/null +++ b/include/base/internal/cef_lock_impl.h @@ -0,0 +1,87 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_lock.h instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_LOCK_IMPL_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_LOCK_IMPL_H_ + +#include "include/base/cef_build.h" + +#if defined(OS_WIN) +#include +#elif defined(OS_POSIX) +#include +#endif + +#include "include/base/cef_macros.h" + +namespace base { +namespace cef_internal { + +// This class implements the underlying platform-specific spin-lock mechanism +// used for the Lock class. Most users should not use LockImpl directly, but +// should instead use Lock. +class LockImpl { + public: +#if defined(OS_WIN) + typedef CRITICAL_SECTION NativeHandle; +#elif defined(OS_POSIX) + typedef pthread_mutex_t NativeHandle; +#endif + + LockImpl(); + ~LockImpl(); + + // If the lock is not held, take it and return true. If the lock is already + // held by something else, immediately return false. + bool Try(); + + // Take the lock, blocking until it is available if necessary. + void Lock(); + + // Release the lock. This must only be called by the lock's holder: after + // a successful call to Try, or a call to Lock. + void Unlock(); + + // Return the native underlying lock. + // TODO(awalker): refactor lock and condition variables so that this is + // unnecessary. + NativeHandle* native_handle() { return &native_handle_; } + + private: + NativeHandle native_handle_; + + DISALLOW_COPY_AND_ASSIGN(LockImpl); +}; + +} // namespace cef_internal +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_LOCK_IMPL_H_ diff --git a/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h b/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h new file mode 100644 index 000000000..8584fcd70 --- /dev/null +++ b/include/base/internal/cef_raw_scoped_refptr_mismatch_checker.h @@ -0,0 +1,154 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_callback.h instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_CEF_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_ +#define CEF_INCLUDE_BASE_INTERNAL_CEF_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_ + +#include "include/base/cef_build.h" +#include "include/base/cef_ref_counted.h" +#include "include/base/cef_template_util.h" +#include "include/base/cef_tuple.h" + +// It is dangerous to post a task with a T* argument where T is a subtype of +// RefCounted(Base|ThreadSafeBase), since by the time the parameter is used, the +// object may already have been deleted since it was not held with a +// scoped_refptr. Example: http://crbug.com/27191 +// The following set of traits are designed to generate a compile error +// whenever this antipattern is attempted. + +namespace base { + +namespace cef_internal { + +template +struct NeedsScopedRefptrButGetsRawPtr { +#if defined(OS_WIN) + enum { + value = base::false_type::value + }; +#else + enum { + // Human readable translation: you needed to be a scoped_refptr if you are a + // raw pointer type and are convertible to a RefCounted(Base|ThreadSafeBase) + // type. + value = (is_pointer::value && + (is_convertible::value || + is_convertible::value)) + }; +#endif +}; + +template +struct ParamsUseScopedRefptrCorrectly { + enum { value = 0 }; +}; + +template <> +struct ParamsUseScopedRefptrCorrectly { + enum { value = 1 }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !NeedsScopedRefptrButGetsRawPtr::value }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +template +struct ParamsUseScopedRefptrCorrectly > { + enum { value = !(NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value || + NeedsScopedRefptrButGetsRawPtr::value) }; +}; + +} // namespace cef_internal + +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_CEF_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_ diff --git a/include/base/internal/cef_thread_checker_impl.h b/include/base/internal/cef_thread_checker_impl.h new file mode 100644 index 000000000..e74bcf8ac --- /dev/null +++ b/include/base/internal/cef_thread_checker_impl.h @@ -0,0 +1,70 @@ +// Copyright (c) 2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. + +// Do not include this header file directly. Use base/cef_thread_checker.h +// instead. + +#ifndef CEF_INCLUDE_BASE_INTERNAL_THREAD_CHECKER_IMPL_H_ +#define CEF_INCLUDE_BASE_INTERNAL_THREAD_CHECKER_IMPL_H_ + +#include "include/base/cef_lock.h" +#include "include/base/cef_platform_thread.h" + +namespace base { + +// Real implementation of ThreadChecker, for use in debug mode, or +// for temporary use in release mode (e.g. to CHECK on a threading issue +// seen only in the wild). +// +// Note: You should almost always use the ThreadChecker class to get the +// right version for your build configuration. +class ThreadCheckerImpl { + public: + ThreadCheckerImpl(); + ~ThreadCheckerImpl(); + + bool CalledOnValidThread() const; + + // Changes the thread that is checked for in CalledOnValidThread. This may + // be useful when an object may be created on one thread and then used + // exclusively on another thread. + void DetachFromThread(); + + private: + void EnsureThreadIdAssigned() const; + + mutable base::Lock lock_; + // This is mutable so that CalledOnValidThread can set it. + // It's guarded by |lock_|. + mutable PlatformThreadRef valid_thread_id_; +}; + +} // namespace base + +#endif // CEF_INCLUDE_BASE_INTERNAL_THREAD_CHECKER_IMPL_H_ diff --git a/include/capi/cef_app_capi.h b/include/capi/cef_app_capi.h new file mode 100644 index 000000000..7d1a070da --- /dev/null +++ b/include/capi/cef_app_capi.h @@ -0,0 +1,182 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_APP_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_APP_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_process_handler_capi.h" +#include "include/capi/cef_command_line_capi.h" +#include "include/capi/cef_render_process_handler_capi.h" +#include "include/capi/cef_resource_bundle_handler_capi.h" +#include "include/capi/cef_scheme_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_app_t; + +/// +// Implement this structure to provide handler implementations. Methods will be +// called by the process and/or thread indicated. +/// +typedef struct _cef_app_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Provides an opportunity to view and/or modify command-line arguments before + // processing by CEF and Chromium. The |process_type| value will be NULL for + // the browser process. Do not keep a reference to the cef_command_line_t + // object passed to this function. The CefSettings.command_line_args_disabled + // value can be used to start with an NULL command-line object. Any values + // specified in CefSettings that equate to command-line arguments will be set + // before this function is called. Be cautious when using this function to + // modify command-line arguments for non-browser processes as this may result + // in undefined behavior including crashes. + /// + void (CEF_CALLBACK *on_before_command_line_processing)( + struct _cef_app_t* self, const cef_string_t* process_type, + struct _cef_command_line_t* command_line); + + /// + // Provides an opportunity to register custom schemes. Do not keep a reference + // to the |registrar| object. This function is called on the main thread for + // each process and the registered schemes should be the same across all + // processes. + /// + void (CEF_CALLBACK *on_register_custom_schemes)(struct _cef_app_t* self, + struct _cef_scheme_registrar_t* registrar); + + /// + // Return the handler for resource bundle events. If + // CefSettings.pack_loading_disabled is true (1) a handler must be returned. + // If no handler is returned resources will be loaded from pack files. This + // function is called by the browser and render processes on multiple threads. + /// + struct _cef_resource_bundle_handler_t* ( + CEF_CALLBACK *get_resource_bundle_handler)(struct _cef_app_t* self); + + /// + // Return the handler for functionality specific to the browser process. This + // function is called on multiple threads in the browser process. + /// + struct _cef_browser_process_handler_t* ( + CEF_CALLBACK *get_browser_process_handler)(struct _cef_app_t* self); + + /// + // Return the handler for functionality specific to the render process. This + // function is called on the render process main thread. + /// + struct _cef_render_process_handler_t* ( + CEF_CALLBACK *get_render_process_handler)(struct _cef_app_t* self); +} cef_app_t; + + +/// +// This function should be called from the application entry point function to +// execute a secondary process. It can be used to run secondary processes from +// the browser client executable (default behavior) or from a separate +// executable specified by the CefSettings.browser_subprocess_path value. If +// called for the browser process (identified by no "type" command-line value) +// it will return immediately with a value of -1. If called for a recognized +// secondary process it will block until the process should exit and then return +// the process exit code. The |application| parameter may be NULL. The +// |windows_sandbox_info| parameter is only used on Windows and may be NULL (see +// cef_sandbox_win.h for details). +/// +CEF_EXPORT int cef_execute_process(const struct _cef_main_args_t* args, + cef_app_t* application, void* windows_sandbox_info); + +/// +// This function should be called on the main application thread to initialize +// the CEF browser process. The |application| parameter may be NULL. A return +// value of true (1) indicates that it succeeded and false (0) indicates that it +// failed. The |windows_sandbox_info| parameter is only used on Windows and may +// be NULL (see cef_sandbox_win.h for details). +/// +CEF_EXPORT int cef_initialize(const struct _cef_main_args_t* args, + const struct _cef_settings_t* settings, cef_app_t* application, + void* windows_sandbox_info); + +/// +// This function should be called on the main application thread to shut down +// the CEF browser process before the application exits. +/// +CEF_EXPORT void cef_shutdown(); + +/// +// Perform a single iteration of CEF message loop processing. This function is +// used to integrate the CEF message loop into an existing application message +// loop. Care must be taken to balance performance against excessive CPU usage. +// This function should only be called on the main application thread and only +// if cef_initialize() is called with a CefSettings.multi_threaded_message_loop +// value of false (0). This function will not block. +/// +CEF_EXPORT void cef_do_message_loop_work(); + +/// +// Run the CEF message loop. Use this function instead of an application- +// provided message loop to get the best balance between performance and CPU +// usage. This function should only be called on the main application thread and +// only if cef_initialize() is called with a +// CefSettings.multi_threaded_message_loop value of false (0). This function +// will block until a quit message is received by the system. +/// +CEF_EXPORT void cef_run_message_loop(); + +/// +// Quit the CEF message loop that was started by calling cef_run_message_loop(). +// This function should only be called on the main application thread and only +// if cef_run_message_loop() was used. +/// +CEF_EXPORT void cef_quit_message_loop(); + +/// +// Set to true (1) before calling Windows APIs like TrackPopupMenu that enter a +// modal message loop. Set to false (0) after exiting the modal message loop. +/// +CEF_EXPORT void cef_set_osmodal_loop(int osModalLoop); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_APP_CAPI_H_ diff --git a/include/capi/cef_auth_callback_capi.h b/include/capi/cef_auth_callback_capi.h new file mode 100644 index 000000000..01f4c0810 --- /dev/null +++ b/include/capi/cef_auth_callback_capi.h @@ -0,0 +1,75 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_AUTH_CALLBACK_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_AUTH_CALLBACK_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure used for asynchronous continuation of authentication +// requests. +/// +typedef struct _cef_auth_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue the authentication request. + /// + void (CEF_CALLBACK *cont)(struct _cef_auth_callback_t* self, + const cef_string_t* username, const cef_string_t* password); + + /// + // Cancel the authentication request. + /// + void (CEF_CALLBACK *cancel)(struct _cef_auth_callback_t* self); +} cef_auth_callback_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_AUTH_CALLBACK_CAPI_H_ diff --git a/include/capi/cef_base_capi.h b/include/capi/cef_base_capi.h new file mode 100644 index 000000000..edeef3c0e --- /dev/null +++ b/include/capi/cef_base_capi.h @@ -0,0 +1,89 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_CAPI_CEF_BASE_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_BASE_CAPI_H_ + +#include + +#include "include/internal/cef_export.h" +#include "include/internal/cef_string.h" +#include "include/internal/cef_string_list.h" +#include "include/internal/cef_string_map.h" +#include "include/internal/cef_string_multimap.h" +#include "include/internal/cef_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Structure defining the reference count implementation functions. All +// framework structures must include the cef_base_t structure first. +/// +typedef struct _cef_base_t { + /// + // Size of the data structure. + /// + size_t size; + + /// + // Called to increment the reference count for the object. Should be called + // for every new copy of a pointer to a given object. + /// + void (CEF_CALLBACK *add_ref)(struct _cef_base_t* self); + + /// + // Called to decrement the reference count for the object. If the reference + // count falls to 0 the object should self-delete. Returns true (1) if the + // resulting reference count is 0. + /// + int (CEF_CALLBACK *release)(struct _cef_base_t* self); + + /// + // Returns true (1) if the current reference count is 1. + /// + int (CEF_CALLBACK *has_one_ref)(struct _cef_base_t* self); +} cef_base_t; + + +// Check that the structure |s|, which is defined with a cef_base_t member named +// |base|, is large enough to contain the specified member |f|. +#define CEF_MEMBER_EXISTS(s, f) \ + ((intptr_t)&((s)->f) - (intptr_t)(s) + sizeof((s)->f) <= (s)->base.size) + +#define CEF_MEMBER_MISSING(s, f) (!CEF_MEMBER_EXISTS(s, f) || !((s)->f)) + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_BASE_CAPI_H_ diff --git a/include/capi/cef_browser_capi.h b/include/capi/cef_browser_capi.h new file mode 100644 index 000000000..ae8410019 --- /dev/null +++ b/include/capi/cef_browser_capi.h @@ -0,0 +1,621 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_BROWSER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_BROWSER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_drag_data_capi.h" +#include "include/capi/cef_frame_capi.h" +#include "include/capi/cef_navigation_entry_capi.h" +#include "include/capi/cef_process_message_capi.h" +#include "include/capi/cef_request_context_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_browser_host_t; +struct _cef_client_t; + +/// +// Structure used to represent a browser window. When used in the browser +// process the functions of this structure may be called on any thread unless +// otherwise indicated in the comments. When used in the render process the +// functions of this structure may only be called on the main thread. +/// +typedef struct _cef_browser_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the browser host object. This function can only be called in the + // browser process. + /// + struct _cef_browser_host_t* (CEF_CALLBACK *get_host)( + struct _cef_browser_t* self); + + /// + // Returns true (1) if the browser can navigate backwards. + /// + int (CEF_CALLBACK *can_go_back)(struct _cef_browser_t* self); + + /// + // Navigate backwards. + /// + void (CEF_CALLBACK *go_back)(struct _cef_browser_t* self); + + /// + // Returns true (1) if the browser can navigate forwards. + /// + int (CEF_CALLBACK *can_go_forward)(struct _cef_browser_t* self); + + /// + // Navigate forwards. + /// + void (CEF_CALLBACK *go_forward)(struct _cef_browser_t* self); + + /// + // Returns true (1) if the browser is currently loading. + /// + int (CEF_CALLBACK *is_loading)(struct _cef_browser_t* self); + + /// + // Reload the current page. + /// + void (CEF_CALLBACK *reload)(struct _cef_browser_t* self); + + /// + // Reload the current page ignoring any cached data. + /// + void (CEF_CALLBACK *reload_ignore_cache)(struct _cef_browser_t* self); + + /// + // Stop loading the page. + /// + void (CEF_CALLBACK *stop_load)(struct _cef_browser_t* self); + + /// + // Returns the globally unique identifier for this browser. + /// + int (CEF_CALLBACK *get_identifier)(struct _cef_browser_t* self); + + /// + // Returns true (1) if this object is pointing to the same handle as |that| + // object. + /// + int (CEF_CALLBACK *is_same)(struct _cef_browser_t* self, + struct _cef_browser_t* that); + + /// + // Returns true (1) if the window is a popup window. + /// + int (CEF_CALLBACK *is_popup)(struct _cef_browser_t* self); + + /// + // Returns true (1) if a document has been loaded in the browser. + /// + int (CEF_CALLBACK *has_document)(struct _cef_browser_t* self); + + /// + // Returns the main (top-level) frame for the browser window. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_main_frame)( + struct _cef_browser_t* self); + + /// + // Returns the focused frame for the browser window. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_focused_frame)( + struct _cef_browser_t* self); + + /// + // Returns the frame with the specified identifier, or NULL if not found. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_frame_byident)( + struct _cef_browser_t* self, int64 identifier); + + /// + // Returns the frame with the specified name, or NULL if not found. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_frame)(struct _cef_browser_t* self, + const cef_string_t* name); + + /// + // Returns the number of frames that currently exist. + /// + size_t (CEF_CALLBACK *get_frame_count)(struct _cef_browser_t* self); + + /// + // Returns the identifiers of all existing frames. + /// + void (CEF_CALLBACK *get_frame_identifiers)(struct _cef_browser_t* self, + size_t* identifiersCount, int64* identifiers); + + /// + // Returns the names of all existing frames. + /// + void (CEF_CALLBACK *get_frame_names)(struct _cef_browser_t* self, + cef_string_list_t names); + + // + // Send a message to the specified |target_process|. Returns true (1) if the + // message was sent successfully. + /// + int (CEF_CALLBACK *send_process_message)(struct _cef_browser_t* self, + cef_process_id_t target_process, + struct _cef_process_message_t* message); +} cef_browser_t; + + +/// +// Callback structure for cef_browser_host_t::RunFileDialog. The functions of +// this structure will be called on the browser process UI thread. +/// +typedef struct _cef_run_file_dialog_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called asynchronously after the file dialog is dismissed. + // |selected_accept_filter| is the 0-based index of the value selected from + // the accept filters array passed to cef_browser_host_t::RunFileDialog. + // |file_paths| will be a single value or a list of values depending on the + // dialog mode. If the selection was cancelled |file_paths| will be NULL. + /// + void (CEF_CALLBACK *on_file_dialog_dismissed)( + struct _cef_run_file_dialog_callback_t* self, int selected_accept_filter, + cef_string_list_t file_paths); +} cef_run_file_dialog_callback_t; + + +/// +// Callback structure for cef_browser_host_t::GetNavigationEntries. The +// functions of this structure will be called on the browser process UI thread. +/// +typedef struct _cef_navigation_entry_visitor_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be executed. Do not keep a reference to |entry| outside of + // this callback. Return true (1) to continue visiting entries or false (0) to + // stop. |current| is true (1) if this entry is the currently loaded + // navigation entry. |index| is the 0-based index of this entry and |total| is + // the total number of entries. + /// + int (CEF_CALLBACK *visit)(struct _cef_navigation_entry_visitor_t* self, + struct _cef_navigation_entry_t* entry, int current, int index, + int total); +} cef_navigation_entry_visitor_t; + + +/// +// Structure used to represent the browser process aspects of a browser window. +// The functions of this structure can only be called in the browser process. +// They may be called on any thread in that process unless otherwise indicated +// in the comments. +/// +typedef struct _cef_browser_host_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the hosted browser object. + /// + struct _cef_browser_t* (CEF_CALLBACK *get_browser)( + struct _cef_browser_host_t* self); + + /// + // Request that the browser close. The JavaScript 'onbeforeunload' event will + // be fired. If |force_close| is false (0) the event handler, if any, will be + // allowed to prompt the user and the user can optionally cancel the close. If + // |force_close| is true (1) the prompt will not be displayed and the close + // will proceed. Results in a call to cef_life_span_handler_t::do_close() if + // the event handler allows the close or if |force_close| is true (1). See + // cef_life_span_handler_t::do_close() documentation for additional usage + // information. + /// + void (CEF_CALLBACK *close_browser)(struct _cef_browser_host_t* self, + int force_close); + + /// + // Set whether the browser is focused. + /// + void (CEF_CALLBACK *set_focus)(struct _cef_browser_host_t* self, int focus); + + /// + // Set whether the window containing the browser is visible + // (minimized/unminimized, app hidden/unhidden, etc). Only used on Mac OS X. + /// + void (CEF_CALLBACK *set_window_visibility)(struct _cef_browser_host_t* self, + int visible); + + /// + // Retrieve the window handle for this browser. + /// + cef_window_handle_t (CEF_CALLBACK *get_window_handle)( + struct _cef_browser_host_t* self); + + /// + // Retrieve the window handle of the browser that opened this browser. Will + // return NULL for non-popup windows. This function can be used in combination + // with custom handling of modal windows. + /// + cef_window_handle_t (CEF_CALLBACK *get_opener_window_handle)( + struct _cef_browser_host_t* self); + + /// + // Returns the client for this browser. + /// + struct _cef_client_t* (CEF_CALLBACK *get_client)( + struct _cef_browser_host_t* self); + + /// + // Returns the request context for this browser. + /// + struct _cef_request_context_t* (CEF_CALLBACK *get_request_context)( + struct _cef_browser_host_t* self); + + /// + // Get the current zoom level. The default zoom level is 0.0. This function + // can only be called on the UI thread. + /// + double (CEF_CALLBACK *get_zoom_level)(struct _cef_browser_host_t* self); + + /// + // Change the zoom level to the specified value. Specify 0.0 to reset the zoom + // level. If called on the UI thread the change will be applied immediately. + // Otherwise, the change will be applied asynchronously on the UI thread. + /// + void (CEF_CALLBACK *set_zoom_level)(struct _cef_browser_host_t* self, + double zoomLevel); + + /// + // Call to run a file chooser dialog. Only a single file chooser dialog may be + // pending at any given time. |mode| represents the type of dialog to display. + // |title| to the title to be used for the dialog and may be NULL to show the + // default title ("Open" or "Save" depending on the mode). |default_file_path| + // is the path with optional directory and/or file name component that will be + // initially selected in the dialog. |accept_filters| are used to restrict the + // selectable file types and may any combination of (a) valid lower-cased MIME + // types (e.g. "text/*" or "image/*"), (b) individual file extensions (e.g. + // ".txt" or ".png"), or (c) combined description and file extension delimited + // using "|" and ";" (e.g. "Image Types|.png;.gif;.jpg"). + // |selected_accept_filter| is the 0-based index of the filter that will be + // selected by default. |callback| will be executed after the dialog is + // dismissed or immediately if another dialog is already pending. The dialog + // will be initiated asynchronously on the UI thread. + /// + void (CEF_CALLBACK *run_file_dialog)(struct _cef_browser_host_t* self, + cef_file_dialog_mode_t mode, const cef_string_t* title, + const cef_string_t* default_file_path, cef_string_list_t accept_filters, + int selected_accept_filter, + struct _cef_run_file_dialog_callback_t* callback); + + /// + // Download the file at |url| using cef_download_handler_t. + /// + void (CEF_CALLBACK *start_download)(struct _cef_browser_host_t* self, + const cef_string_t* url); + + /// + // Print the current browser contents. + /// + void (CEF_CALLBACK *print)(struct _cef_browser_host_t* self); + + /// + // Search for |searchText|. |identifier| can be used to have multiple searches + // running simultaniously. |forward| indicates whether to search forward or + // backward within the page. |matchCase| indicates whether the search should + // be case-sensitive. |findNext| indicates whether this is the first request + // or a follow-up. The cef_find_handler_t instance, if any, returned via + // cef_client_t::GetFindHandler will be called to report find results. + /// + void (CEF_CALLBACK *find)(struct _cef_browser_host_t* self, int identifier, + const cef_string_t* searchText, int forward, int matchCase, + int findNext); + + /// + // Cancel all searches that are currently going on. + /// + void (CEF_CALLBACK *stop_finding)(struct _cef_browser_host_t* self, + int clearSelection); + + /// + // Open developer tools in its own window. If |inspect_element_at| is non- + // NULL the element at the specified (x,y) location will be inspected. + /// + void (CEF_CALLBACK *show_dev_tools)(struct _cef_browser_host_t* self, + const struct _cef_window_info_t* windowInfo, + struct _cef_client_t* client, + const struct _cef_browser_settings_t* settings, + const cef_point_t* inspect_element_at); + + /// + // Explicitly close the developer tools window if one exists for this browser + // instance. + /// + void (CEF_CALLBACK *close_dev_tools)(struct _cef_browser_host_t* self); + + /// + // Retrieve a snapshot of current navigation entries as values sent to the + // specified visitor. If |current_only| is true (1) only the current + // navigation entry will be sent, otherwise all navigation entries will be + // sent. + /// + /// + void (CEF_CALLBACK *get_navigation_entries)(struct _cef_browser_host_t* self, + struct _cef_navigation_entry_visitor_t* visitor, int current_only); + + /// + // Set whether mouse cursor change is disabled. + /// + void (CEF_CALLBACK *set_mouse_cursor_change_disabled)( + struct _cef_browser_host_t* self, int disabled); + + /// + // Returns true (1) if mouse cursor change is disabled. + /// + int (CEF_CALLBACK *is_mouse_cursor_change_disabled)( + struct _cef_browser_host_t* self); + + /// + // If a misspelled word is currently selected in an editable node calling this + // function will replace it with the specified |word|. + /// + void (CEF_CALLBACK *replace_misspelling)(struct _cef_browser_host_t* self, + const cef_string_t* word); + + /// + // Add the specified |word| to the spelling dictionary. + /// + void (CEF_CALLBACK *add_word_to_dictionary)(struct _cef_browser_host_t* self, + const cef_string_t* word); + + /// + // Returns true (1) if window rendering is disabled. + /// + int (CEF_CALLBACK *is_window_rendering_disabled)( + struct _cef_browser_host_t* self); + + /// + // Notify the browser that the widget has been resized. The browser will first + // call cef_render_handler_t::GetViewRect to get the new size and then call + // cef_render_handler_t::OnPaint asynchronously with the updated regions. This + // function is only used when window rendering is disabled. + /// + void (CEF_CALLBACK *was_resized)(struct _cef_browser_host_t* self); + + /// + // Notify the browser that it has been hidden or shown. Layouting and + // cef_render_handler_t::OnPaint notification will stop when the browser is + // hidden. This function is only used when window rendering is disabled. + /// + void (CEF_CALLBACK *was_hidden)(struct _cef_browser_host_t* self, int hidden); + + /// + // Send a notification to the browser that the screen info has changed. The + // browser will then call cef_render_handler_t::GetScreenInfo to update the + // screen information with the new values. This simulates moving the webview + // window from one display to another, or changing the properties of the + // current display. This function is only used when window rendering is + // disabled. + /// + void (CEF_CALLBACK *notify_screen_info_changed)( + struct _cef_browser_host_t* self); + + /// + // Invalidate the view. The browser will call cef_render_handler_t::OnPaint + // asynchronously. This function is only used when window rendering is + // disabled. + /// + void (CEF_CALLBACK *invalidate)(struct _cef_browser_host_t* self, + cef_paint_element_type_t type); + + /// + // Send a key event to the browser. + /// + void (CEF_CALLBACK *send_key_event)(struct _cef_browser_host_t* self, + const struct _cef_key_event_t* event); + + /// + // Send a mouse click event to the browser. The |x| and |y| coordinates are + // relative to the upper-left corner of the view. + /// + void (CEF_CALLBACK *send_mouse_click_event)(struct _cef_browser_host_t* self, + const struct _cef_mouse_event_t* event, cef_mouse_button_type_t type, + int mouseUp, int clickCount); + + /// + // Send a mouse move event to the browser. The |x| and |y| coordinates are + // relative to the upper-left corner of the view. + /// + void (CEF_CALLBACK *send_mouse_move_event)(struct _cef_browser_host_t* self, + const struct _cef_mouse_event_t* event, int mouseLeave); + + /// + // Send a mouse wheel event to the browser. The |x| and |y| coordinates are + // relative to the upper-left corner of the view. The |deltaX| and |deltaY| + // values represent the movement delta in the X and Y directions respectively. + // In order to scroll inside select popups with window rendering disabled + // cef_render_handler_t::GetScreenPoint should be implemented properly. + /// + void (CEF_CALLBACK *send_mouse_wheel_event)(struct _cef_browser_host_t* self, + const struct _cef_mouse_event_t* event, int deltaX, int deltaY); + + /// + // Send a focus event to the browser. + /// + void (CEF_CALLBACK *send_focus_event)(struct _cef_browser_host_t* self, + int setFocus); + + /// + // Send a capture lost event to the browser. + /// + void (CEF_CALLBACK *send_capture_lost_event)( + struct _cef_browser_host_t* self); + + /// + // Notify the browser that the window hosting it is about to be moved or + // resized. This function is only used on Windows and Linux. + /// + void (CEF_CALLBACK *notify_move_or_resize_started)( + struct _cef_browser_host_t* self); + + /// + // Get the NSTextInputContext implementation for enabling IME on Mac when + // window rendering is disabled. + /// + cef_text_input_context_t (CEF_CALLBACK *get_nstext_input_context)( + struct _cef_browser_host_t* self); + + /// + // Handles a keyDown event prior to passing it through the NSTextInputClient + // machinery. + /// + void (CEF_CALLBACK *handle_key_event_before_text_input_client)( + struct _cef_browser_host_t* self, cef_event_handle_t keyEvent); + + /// + // Performs any additional actions after NSTextInputClient handles the event. + /// + void (CEF_CALLBACK *handle_key_event_after_text_input_client)( + struct _cef_browser_host_t* self, cef_event_handle_t keyEvent); + + /// + // Call this function when the user drags the mouse into the web view (before + // calling DragTargetDragOver/DragTargetLeave/DragTargetDrop). |drag_data| + // should not contain file contents as this type of data is not allowed to be + // dragged into the web view. File contents can be removed using + // cef_drag_data_t::ResetFileContents (for example, if |drag_data| comes from + // cef_render_handler_t::StartDragging). This function is only used when + // window rendering is disabled. + /// + void (CEF_CALLBACK *drag_target_drag_enter)(struct _cef_browser_host_t* self, + struct _cef_drag_data_t* drag_data, + const struct _cef_mouse_event_t* event, + cef_drag_operations_mask_t allowed_ops); + + /// + // Call this function each time the mouse is moved across the web view during + // a drag operation (after calling DragTargetDragEnter and before calling + // DragTargetDragLeave/DragTargetDrop). This function is only used when window + // rendering is disabled. + /// + void (CEF_CALLBACK *drag_target_drag_over)(struct _cef_browser_host_t* self, + const struct _cef_mouse_event_t* event, + cef_drag_operations_mask_t allowed_ops); + + /// + // Call this function when the user drags the mouse out of the web view (after + // calling DragTargetDragEnter). This function is only used when window + // rendering is disabled. + /// + void (CEF_CALLBACK *drag_target_drag_leave)(struct _cef_browser_host_t* self); + + /// + // Call this function when the user completes the drag operation by dropping + // the object onto the web view (after calling DragTargetDragEnter). The + // object being dropped is |drag_data|, given as an argument to the previous + // DragTargetDragEnter call. This function is only used when window rendering + // is disabled. + /// + void (CEF_CALLBACK *drag_target_drop)(struct _cef_browser_host_t* self, + const struct _cef_mouse_event_t* event); + + /// + // Call this function when the drag operation started by a + // cef_render_handler_t::StartDragging call has ended either in a drop or by + // being cancelled. |x| and |y| are mouse coordinates relative to the upper- + // left corner of the view. If the web view is both the drag source and the + // drag target then all DragTarget* functions should be called before + // DragSource* mthods. This function is only used when window rendering is + // disabled. + /// + void (CEF_CALLBACK *drag_source_ended_at)(struct _cef_browser_host_t* self, + int x, int y, cef_drag_operations_mask_t op); + + /// + // Call this function when the drag operation started by a + // cef_render_handler_t::StartDragging call has completed. This function may + // be called immediately without first calling DragSourceEndedAt to cancel a + // drag operation. If the web view is both the drag source and the drag target + // then all DragTarget* functions should be called before DragSource* mthods. + // This function is only used when window rendering is disabled. + /// + void (CEF_CALLBACK *drag_source_system_drag_ended)( + struct _cef_browser_host_t* self); +} cef_browser_host_t; + + +/// +// Create a new browser window using the window parameters specified by +// |windowInfo|. All values will be copied internally and the actual window will +// be created on the UI thread. If |request_context| is NULL the global request +// context will be used. This function can be called on any browser process +// thread and will not block. +/// +CEF_EXPORT int cef_browser_host_create_browser( + const cef_window_info_t* windowInfo, struct _cef_client_t* client, + const cef_string_t* url, const struct _cef_browser_settings_t* settings, + struct _cef_request_context_t* request_context); + +/// +// Create a new browser window using the window parameters specified by +// |windowInfo|. If |request_context| is NULL the global request context will be +// used. This function can only be called on the browser process UI thread. +/// +CEF_EXPORT cef_browser_t* cef_browser_host_create_browser_sync( + const cef_window_info_t* windowInfo, struct _cef_client_t* client, + const cef_string_t* url, const struct _cef_browser_settings_t* settings, + struct _cef_request_context_t* request_context); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_BROWSER_CAPI_H_ diff --git a/include/capi/cef_browser_process_handler_capi.h b/include/capi/cef_browser_process_handler_capi.h new file mode 100644 index 000000000..a4f63cc99 --- /dev/null +++ b/include/capi/cef_browser_process_handler_capi.h @@ -0,0 +1,104 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_BROWSER_PROCESS_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_BROWSER_PROCESS_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_command_line_capi.h" +#include "include/capi/cef_print_handler_capi.h" +#include "include/capi/cef_values_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to implement browser process callbacks. The functions of this +// structure will be called on the browser process main thread unless otherwise +// indicated. +/// +typedef struct _cef_browser_process_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called on the browser process UI thread immediately after the CEF context + // has been initialized. + /// + void (CEF_CALLBACK *on_context_initialized)( + struct _cef_browser_process_handler_t* self); + + /// + // Called before a child process is launched. Will be called on the browser + // process UI thread when launching a render process and on the browser + // process IO thread when launching a GPU or plugin process. Provides an + // opportunity to modify the child process command line. Do not keep a + // reference to |command_line| outside of this function. + /// + void (CEF_CALLBACK *on_before_child_process_launch)( + struct _cef_browser_process_handler_t* self, + struct _cef_command_line_t* command_line); + + /// + // Called on the browser process IO thread after the main thread has been + // created for a new render process. Provides an opportunity to specify extra + // information that will be passed to + // cef_render_process_handler_t::on_render_thread_created() in the render + // process. Do not keep a reference to |extra_info| outside of this function. + /// + void (CEF_CALLBACK *on_render_process_thread_created)( + struct _cef_browser_process_handler_t* self, + struct _cef_list_value_t* extra_info); + + /// + // Return the handler for printing on Linux. If a print handler is not + // provided then printing will not be supported on the Linux platform. + /// + struct _cef_print_handler_t* (CEF_CALLBACK *get_print_handler)( + struct _cef_browser_process_handler_t* self); +} cef_browser_process_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_BROWSER_PROCESS_HANDLER_CAPI_H_ diff --git a/include/capi/cef_callback_capi.h b/include/capi/cef_callback_capi.h new file mode 100644 index 000000000..275138686 --- /dev/null +++ b/include/capi/cef_callback_capi.h @@ -0,0 +1,89 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_CALLBACK_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_CALLBACK_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Generic callback structure used for asynchronous continuation. +/// +typedef struct _cef_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue processing. + /// + void (CEF_CALLBACK *cont)(struct _cef_callback_t* self); + + /// + // Cancel processing. + /// + void (CEF_CALLBACK *cancel)(struct _cef_callback_t* self); +} cef_callback_t; + + +/// +// Generic callback structure used for asynchronous completion. +/// +typedef struct _cef_completion_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be called once the task is complete. + /// + void (CEF_CALLBACK *on_complete)(struct _cef_completion_callback_t* self); +} cef_completion_callback_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_CALLBACK_CAPI_H_ diff --git a/include/capi/cef_client_capi.h b/include/capi/cef_client_capi.h new file mode 100644 index 000000000..7950152fe --- /dev/null +++ b/include/capi/cef_client_capi.h @@ -0,0 +1,176 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_CLIENT_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_CLIENT_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_context_menu_handler_capi.h" +#include "include/capi/cef_dialog_handler_capi.h" +#include "include/capi/cef_display_handler_capi.h" +#include "include/capi/cef_download_handler_capi.h" +#include "include/capi/cef_drag_handler_capi.h" +#include "include/capi/cef_find_handler_capi.h" +#include "include/capi/cef_focus_handler_capi.h" +#include "include/capi/cef_geolocation_handler_capi.h" +#include "include/capi/cef_jsdialog_handler_capi.h" +#include "include/capi/cef_keyboard_handler_capi.h" +#include "include/capi/cef_life_span_handler_capi.h" +#include "include/capi/cef_load_handler_capi.h" +#include "include/capi/cef_process_message_capi.h" +#include "include/capi/cef_render_handler_capi.h" +#include "include/capi/cef_request_handler_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to provide handler implementations. +/// +typedef struct _cef_client_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Return the handler for context menus. If no handler is provided the default + // implementation will be used. + /// + struct _cef_context_menu_handler_t* (CEF_CALLBACK *get_context_menu_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for dialogs. If no handler is provided the default + // implementation will be used. + /// + struct _cef_dialog_handler_t* (CEF_CALLBACK *get_dialog_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for browser display state events. + /// + struct _cef_display_handler_t* (CEF_CALLBACK *get_display_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for download events. If no handler is returned downloads + // will not be allowed. + /// + struct _cef_download_handler_t* (CEF_CALLBACK *get_download_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for drag events. + /// + struct _cef_drag_handler_t* (CEF_CALLBACK *get_drag_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for find result events. + /// + struct _cef_find_handler_t* (CEF_CALLBACK *get_find_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for focus events. + /// + struct _cef_focus_handler_t* (CEF_CALLBACK *get_focus_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for geolocation permissions requests. If no handler is + // provided geolocation access will be denied by default. + /// + struct _cef_geolocation_handler_t* (CEF_CALLBACK *get_geolocation_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for JavaScript dialogs. If no handler is provided the + // default implementation will be used. + /// + struct _cef_jsdialog_handler_t* (CEF_CALLBACK *get_jsdialog_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for keyboard events. + /// + struct _cef_keyboard_handler_t* (CEF_CALLBACK *get_keyboard_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for browser life span events. + /// + struct _cef_life_span_handler_t* (CEF_CALLBACK *get_life_span_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for browser load status events. + /// + struct _cef_load_handler_t* (CEF_CALLBACK *get_load_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for off-screen rendering events. + /// + struct _cef_render_handler_t* (CEF_CALLBACK *get_render_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for browser request events. + /// + struct _cef_request_handler_t* (CEF_CALLBACK *get_request_handler)( + struct _cef_client_t* self); + + /// + // Called when a new message is received from a different process. Return true + // (1) if the message was handled or false (0) otherwise. Do not keep a + // reference to or attempt to access the message outside of this callback. + /// + int (CEF_CALLBACK *on_process_message_received)(struct _cef_client_t* self, + struct _cef_browser_t* browser, cef_process_id_t source_process, + struct _cef_process_message_t* message); +} cef_client_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_CLIENT_CAPI_H_ diff --git a/include/capi/cef_command_line_capi.h b/include/capi/cef_command_line_capi.h new file mode 100644 index 000000000..8fc308b97 --- /dev/null +++ b/include/capi/cef_command_line_capi.h @@ -0,0 +1,213 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_COMMAND_LINE_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_COMMAND_LINE_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to create and/or parse command line arguments. Arguments with +// '--', '-' and, on Windows, '/' prefixes are considered switches. Switches +// will always precede any arguments without switch prefixes. Switches can +// optionally have a value specified using the '=' delimiter (e.g. +// "-switch=value"). An argument of "--" will terminate switch parsing with all +// subsequent tokens, regardless of prefix, being interpreted as non-switch +// arguments. Switch names are considered case-insensitive. This structure can +// be used before cef_initialize() is called. +/// +typedef struct _cef_command_line_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_command_line_t* self); + + /// + // Returns true (1) if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_command_line_t* self); + + /// + // Returns a writable copy of this object. + /// + struct _cef_command_line_t* (CEF_CALLBACK *copy)( + struct _cef_command_line_t* self); + + /// + // Initialize the command line with the specified |argc| and |argv| values. + // The first argument must be the name of the program. This function is only + // supported on non-Windows platforms. + /// + void (CEF_CALLBACK *init_from_argv)(struct _cef_command_line_t* self, + int argc, const char* const* argv); + + /// + // Initialize the command line with the string returned by calling + // GetCommandLineW(). This function is only supported on Windows. + /// + void (CEF_CALLBACK *init_from_string)(struct _cef_command_line_t* self, + const cef_string_t* command_line); + + /// + // Reset the command-line switches and arguments but leave the program + // component unchanged. + /// + void (CEF_CALLBACK *reset)(struct _cef_command_line_t* self); + + /// + // Retrieve the original command line string as a vector of strings. The argv + // array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* } + /// + void (CEF_CALLBACK *get_argv)(struct _cef_command_line_t* self, + cef_string_list_t argv); + + /// + // Constructs and returns the represented command line string. Use this + // function cautiously because quoting behavior is unclear. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_command_line_string)( + struct _cef_command_line_t* self); + + /// + // Get the program part of the command line string (the first item). + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_program)( + struct _cef_command_line_t* self); + + /// + // Set the program part of the command line string (the first item). + /// + void (CEF_CALLBACK *set_program)(struct _cef_command_line_t* self, + const cef_string_t* program); + + /// + // Returns true (1) if the command line has switches. + /// + int (CEF_CALLBACK *has_switches)(struct _cef_command_line_t* self); + + /// + // Returns true (1) if the command line contains the given switch. + /// + int (CEF_CALLBACK *has_switch)(struct _cef_command_line_t* self, + const cef_string_t* name); + + /// + // Returns the value associated with the given switch. If the switch has no + // value or isn't present this function returns the NULL string. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_switch_value)( + struct _cef_command_line_t* self, const cef_string_t* name); + + /// + // Returns the map of switch names and values. If a switch has no value an + // NULL string is returned. + /// + void (CEF_CALLBACK *get_switches)(struct _cef_command_line_t* self, + cef_string_map_t switches); + + /// + // Add a switch to the end of the command line. If the switch has no value + // pass an NULL value string. + /// + void (CEF_CALLBACK *append_switch)(struct _cef_command_line_t* self, + const cef_string_t* name); + + /// + // Add a switch with the specified value to the end of the command line. + /// + void (CEF_CALLBACK *append_switch_with_value)( + struct _cef_command_line_t* self, const cef_string_t* name, + const cef_string_t* value); + + /// + // True if there are remaining command line arguments. + /// + int (CEF_CALLBACK *has_arguments)(struct _cef_command_line_t* self); + + /// + // Get the remaining command line arguments. + /// + void (CEF_CALLBACK *get_arguments)(struct _cef_command_line_t* self, + cef_string_list_t arguments); + + /// + // Add an argument to the end of the command line. + /// + void (CEF_CALLBACK *append_argument)(struct _cef_command_line_t* self, + const cef_string_t* argument); + + /// + // Insert a command before the current command. Common for debuggers, like + // "valgrind" or "gdb --args". + /// + void (CEF_CALLBACK *prepend_wrapper)(struct _cef_command_line_t* self, + const cef_string_t* wrapper); +} cef_command_line_t; + + +/// +// Create a new cef_command_line_t instance. +/// +CEF_EXPORT cef_command_line_t* cef_command_line_create(); + +/// +// Returns the singleton global cef_command_line_t object. The returned object +// will be read-only. +/// +CEF_EXPORT cef_command_line_t* cef_command_line_get_global(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_COMMAND_LINE_CAPI_H_ diff --git a/include/capi/cef_context_menu_handler_capi.h b/include/capi/cef_context_menu_handler_capi.h new file mode 100644 index 000000000..4cc0e0abb --- /dev/null +++ b/include/capi/cef_context_menu_handler_capi.h @@ -0,0 +1,249 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_CONTEXT_MENU_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_CONTEXT_MENU_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_frame_capi.h" +#include "include/capi/cef_menu_model_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_context_menu_params_t; + +/// +// Implement this structure to handle context menu events. The functions of this +// structure will be called on the UI thread. +/// +typedef struct _cef_context_menu_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called before a context menu is displayed. |params| provides information + // about the context menu state. |model| initially contains the default + // context menu. The |model| can be cleared to show no context menu or + // modified to show a custom menu. Do not keep references to |params| or + // |model| outside of this callback. + /// + void (CEF_CALLBACK *on_before_context_menu)( + struct _cef_context_menu_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_context_menu_params_t* params, + struct _cef_menu_model_t* model); + + /// + // Called to execute a command selected from the context menu. Return true (1) + // if the command was handled or false (0) for the default implementation. See + // cef_menu_id_t for the command ids that have default implementations. All + // user-defined command ids should be between MENU_ID_USER_FIRST and + // MENU_ID_USER_LAST. |params| will have the same values as what was passed to + // on_before_context_menu(). Do not keep a reference to |params| outside of + // this callback. + /// + int (CEF_CALLBACK *on_context_menu_command)( + struct _cef_context_menu_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_context_menu_params_t* params, + int command_id, cef_event_flags_t event_flags); + + /// + // Called when the context menu is dismissed irregardless of whether the menu + // was NULL or a command was selected. + /// + void (CEF_CALLBACK *on_context_menu_dismissed)( + struct _cef_context_menu_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame); +} cef_context_menu_handler_t; + + +/// +// Provides information about the context menu state. The ethods of this +// structure can only be accessed on browser process the UI thread. +/// +typedef struct _cef_context_menu_params_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the X coordinate of the mouse where the context menu was invoked. + // Coords are relative to the associated RenderView's origin. + /// + int (CEF_CALLBACK *get_xcoord)(struct _cef_context_menu_params_t* self); + + /// + // Returns the Y coordinate of the mouse where the context menu was invoked. + // Coords are relative to the associated RenderView's origin. + /// + int (CEF_CALLBACK *get_ycoord)(struct _cef_context_menu_params_t* self); + + /// + // Returns flags representing the type of node that the context menu was + // invoked on. + /// + cef_context_menu_type_flags_t (CEF_CALLBACK *get_type_flags)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the URL of the link, if any, that encloses the node that the + // context menu was invoked on. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_link_url)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the link URL, if any, to be used ONLY for "copy link address". We + // don't validate this field in the frontend process. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_unfiltered_link_url)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the source URL, if any, for the element that the context menu was + // invoked on. Example of elements with source URLs are img, audio, and video. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_source_url)( + struct _cef_context_menu_params_t* self); + + /// + // Returns true (1) if the context menu was invoked on an image which has non- + // NULL contents. + /// + int (CEF_CALLBACK *has_image_contents)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the URL of the top level page that the context menu was invoked on. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_page_url)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the URL of the subframe that the context menu was invoked on. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_frame_url)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the character encoding of the subframe that the context menu was + // invoked on. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_frame_charset)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the type of context node that the context menu was invoked on. + /// + cef_context_menu_media_type_t (CEF_CALLBACK *get_media_type)( + struct _cef_context_menu_params_t* self); + + /// + // Returns flags representing the actions supported by the media element, if + // any, that the context menu was invoked on. + /// + cef_context_menu_media_state_flags_t (CEF_CALLBACK *get_media_state_flags)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the text of the selection, if any, that the context menu was + // invoked on. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_selection_text)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the text of the misspelled word, if any, that the context menu was + // invoked on. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_misspelled_word)( + struct _cef_context_menu_params_t* self); + + /// + // Returns the hash of the misspelled word, if any, that the context menu was + // invoked on. + /// + int (CEF_CALLBACK *get_misspelling_hash)( + struct _cef_context_menu_params_t* self); + + /// + // Returns true (1) if suggestions exist, false (0) otherwise. Fills in + // |suggestions| from the spell check service for the misspelled word if there + // is one. + /// + int (CEF_CALLBACK *get_dictionary_suggestions)( + struct _cef_context_menu_params_t* self, cef_string_list_t suggestions); + + /// + // Returns true (1) if the context menu was invoked on an editable node. + /// + int (CEF_CALLBACK *is_editable)(struct _cef_context_menu_params_t* self); + + /// + // Returns true (1) if the context menu was invoked on an editable node where + // spell-check is enabled. + /// + int (CEF_CALLBACK *is_spell_check_enabled)( + struct _cef_context_menu_params_t* self); + + /// + // Returns flags representing the actions supported by the editable node, if + // any, that the context menu was invoked on. + /// + cef_context_menu_edit_state_flags_t (CEF_CALLBACK *get_edit_state_flags)( + struct _cef_context_menu_params_t* self); +} cef_context_menu_params_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_CONTEXT_MENU_HANDLER_CAPI_H_ diff --git a/include/capi/cef_cookie_capi.h b/include/capi/cef_cookie_capi.h new file mode 100644 index 000000000..82c4dffa2 --- /dev/null +++ b/include/capi/cef_cookie_capi.h @@ -0,0 +1,176 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_COOKIE_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_COOKIE_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_callback_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_cookie_visitor_t; + +/// +// Structure used for managing cookies. The functions of this structure may be +// called on any thread unless otherwise indicated. +/// +typedef struct _cef_cookie_manager_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Set the schemes supported by this manager. By default only "http" and + // "https" schemes are supported. Must be called before any cookies are + // accessed. + /// + void (CEF_CALLBACK *set_supported_schemes)(struct _cef_cookie_manager_t* self, + cef_string_list_t schemes); + + /// + // Visit all cookies. The returned cookies are ordered by longest path, then + // by earliest creation date. Returns false (0) if cookies cannot be accessed. + /// + int (CEF_CALLBACK *visit_all_cookies)(struct _cef_cookie_manager_t* self, + struct _cef_cookie_visitor_t* visitor); + + /// + // Visit a subset of cookies. The results are filtered by the given url + // scheme, host, domain and path. If |includeHttpOnly| is true (1) HTTP-only + // cookies will also be included in the results. The returned cookies are + // ordered by longest path, then by earliest creation date. Returns false (0) + // if cookies cannot be accessed. + /// + int (CEF_CALLBACK *visit_url_cookies)(struct _cef_cookie_manager_t* self, + const cef_string_t* url, int includeHttpOnly, + struct _cef_cookie_visitor_t* visitor); + + /// + // Sets a cookie given a valid URL and explicit user-provided cookie + // attributes. This function expects each attribute to be well-formed. It will + // check for disallowed characters (e.g. the ';' character is disallowed + // within the cookie value attribute) and will return false (0) without + // setting the cookie if such characters are found. This function must be + // called on the IO thread. + /// + int (CEF_CALLBACK *set_cookie)(struct _cef_cookie_manager_t* self, + const cef_string_t* url, const struct _cef_cookie_t* cookie); + + /// + // Delete all cookies that match the specified parameters. If both |url| and + // values |cookie_name| are specified all host and domain cookies matching + // both will be deleted. If only |url| is specified all host cookies (but not + // domain cookies) irrespective of path will be deleted. If |url| is NULL all + // cookies for all hosts and domains will be deleted. Returns false (0) if a + // non- NULL invalid URL is specified or if cookies cannot be accessed. This + // function must be called on the IO thread. + /// + int (CEF_CALLBACK *delete_cookies)(struct _cef_cookie_manager_t* self, + const cef_string_t* url, const cef_string_t* cookie_name); + + /// + // Sets the directory path that will be used for storing cookie data. If + // |path| is NULL data will be stored in memory only. Otherwise, data will be + // stored at the specified |path|. To persist session cookies (cookies without + // an expiry date or validity interval) set |persist_session_cookies| to true + // (1). Session cookies are generally intended to be transient and most Web + // browsers do not persist them. Returns false (0) if cookies cannot be + // accessed. + /// + int (CEF_CALLBACK *set_storage_path)(struct _cef_cookie_manager_t* self, + const cef_string_t* path, int persist_session_cookies); + + /// + // Flush the backing store (if any) to disk and execute the specified + // |callback| on the IO thread when done. Returns false (0) if cookies cannot + // be accessed. + /// + int (CEF_CALLBACK *flush_store)(struct _cef_cookie_manager_t* self, + struct _cef_completion_callback_t* callback); +} cef_cookie_manager_t; + + +/// +// Returns the global cookie manager. By default data will be stored at +// CefSettings.cache_path if specified or in memory otherwise. +/// +CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_get_global_manager(); + +/// +// Creates a new cookie manager. If |path| is NULL data will be stored in memory +// only. Otherwise, data will be stored at the specified |path|. To persist +// session cookies (cookies without an expiry date or validity interval) set +// |persist_session_cookies| to true (1). Session cookies are generally intended +// to be transient and most Web browsers do not persist them. Returns NULL if +// creation fails. +/// +CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager( + const cef_string_t* path, int persist_session_cookies); + + +/// +// Structure to implement for visiting cookie values. The functions of this +// structure will always be called on the IO thread. +/// +typedef struct _cef_cookie_visitor_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be called once for each cookie. |count| is the 0-based + // index for the current cookie. |total| is the total number of cookies. Set + // |deleteCookie| to true (1) to delete the cookie currently being visited. + // Return false (0) to stop visiting cookies. This function may never be + // called if no cookies are found. + /// + int (CEF_CALLBACK *visit)(struct _cef_cookie_visitor_t* self, + const struct _cef_cookie_t* cookie, int count, int total, + int* deleteCookie); +} cef_cookie_visitor_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_COOKIE_CAPI_H_ diff --git a/include/capi/cef_dialog_handler_capi.h b/include/capi/cef_dialog_handler_capi.h new file mode 100644 index 000000000..c97a9639f --- /dev/null +++ b/include/capi/cef_dialog_handler_capi.h @@ -0,0 +1,112 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DIALOG_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DIALOG_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure for asynchronous continuation of file dialog requests. +/// +typedef struct _cef_file_dialog_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue the file selection. |selected_accept_filter| should be the 0-based + // index of the value selected from the accept filters array passed to + // cef_dialog_handler_t::OnFileDialog. |file_paths| should be a single value + // or a list of values depending on the dialog mode. An NULL |file_paths| + // value is treated the same as calling cancel(). + /// + void (CEF_CALLBACK *cont)(struct _cef_file_dialog_callback_t* self, + int selected_accept_filter, cef_string_list_t file_paths); + + /// + // Cancel the file selection. + /// + void (CEF_CALLBACK *cancel)(struct _cef_file_dialog_callback_t* self); +} cef_file_dialog_callback_t; + + +/// +// Implement this structure to handle dialog events. The functions of this +// structure will be called on the browser process UI thread. +/// +typedef struct _cef_dialog_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to run a file chooser dialog. |mode| represents the type of dialog + // to display. |title| to the title to be used for the dialog and may be NULL + // to show the default title ("Open" or "Save" depending on the mode). + // |default_file_path| is the path with optional directory and/or file name + // component that should be initially selected in the dialog. |accept_filters| + // are used to restrict the selectable file types and may any combination of + // (a) valid lower-cased MIME types (e.g. "text/*" or "image/*"), (b) + // individual file extensions (e.g. ".txt" or ".png"), or (c) combined + // description and file extension delimited using "|" and ";" (e.g. "Image + // Types|.png;.gif;.jpg"). |selected_accept_filter| is the 0-based index of + // the filter that should be selected by default. To display a custom dialog + // return true (1) and execute |callback| either inline or at a later time. To + // display the default dialog return false (0). + /// + int (CEF_CALLBACK *on_file_dialog)(struct _cef_dialog_handler_t* self, + struct _cef_browser_t* browser, cef_file_dialog_mode_t mode, + const cef_string_t* title, const cef_string_t* default_file_path, + cef_string_list_t accept_filters, int selected_accept_filter, + struct _cef_file_dialog_callback_t* callback); +} cef_dialog_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DIALOG_HANDLER_CAPI_H_ diff --git a/include/capi/cef_display_handler_capi.h b/include/capi/cef_display_handler_capi.h new file mode 100644 index 000000000..87e67c00b --- /dev/null +++ b/include/capi/cef_display_handler_capi.h @@ -0,0 +1,111 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DISPLAY_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DISPLAY_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_frame_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events related to browser display state. +// The functions of this structure will be called on the UI thread. +/// +typedef struct _cef_display_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called when a frame's address has changed. + /// + void (CEF_CALLBACK *on_address_change)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* url); + + /// + // Called when the page title changes. + /// + void (CEF_CALLBACK *on_title_change)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* title); + + /// + // Called when the page icon changes. + /// + void (CEF_CALLBACK *on_favicon_urlchange)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, cef_string_list_t icon_urls); + + /// + // Called when the browser is about to display a tooltip. |text| contains the + // text that will be displayed in the tooltip. To handle the display of the + // tooltip yourself return true (1). Otherwise, you can optionally modify + // |text| and then return false (0) to allow the browser to display the + // tooltip. When window rendering is disabled the application is responsible + // for drawing tooltips and the return value is ignored. + /// + int (CEF_CALLBACK *on_tooltip)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, cef_string_t* text); + + /// + // Called when the browser receives a status message. |value| contains the + // text that will be displayed in the status message. + /// + void (CEF_CALLBACK *on_status_message)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* value); + + /// + // Called to display a console message. Return true (1) to stop the message + // from being output to the console. + /// + int (CEF_CALLBACK *on_console_message)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* message, + const cef_string_t* source, int line); +} cef_display_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DISPLAY_HANDLER_CAPI_H_ diff --git a/include/capi/cef_dom_capi.h b/include/capi/cef_dom_capi.h new file mode 100644 index 000000000..ac4d1127c --- /dev/null +++ b/include/capi/cef_dom_capi.h @@ -0,0 +1,341 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DOM_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DOM_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_domdocument_t; +struct _cef_domnode_t; + +/// +// Structure to implement for visiting the DOM. The functions of this structure +// will be called on the render process main thread. +/// +typedef struct _cef_domvisitor_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method executed for visiting the DOM. The document object passed to this + // function represents a snapshot of the DOM at the time this function is + // executed. DOM objects are only valid for the scope of this function. Do not + // keep references to or attempt to access any DOM objects outside the scope + // of this function. + /// + void (CEF_CALLBACK *visit)(struct _cef_domvisitor_t* self, + struct _cef_domdocument_t* document); +} cef_domvisitor_t; + + +/// +// Structure used to represent a DOM document. The functions of this structure +// should only be called on the render process main thread thread. +/// +typedef struct _cef_domdocument_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the document type. + /// + cef_dom_document_type_t (CEF_CALLBACK *get_type)( + struct _cef_domdocument_t* self); + + /// + // Returns the root document node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_document)( + struct _cef_domdocument_t* self); + + /// + // Returns the BODY node of an HTML document. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_body)( + struct _cef_domdocument_t* self); + + /// + // Returns the HEAD node of an HTML document. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_head)( + struct _cef_domdocument_t* self); + + /// + // Returns the title of an HTML document. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_title)( + struct _cef_domdocument_t* self); + + /// + // Returns the document element with the specified ID value. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_element_by_id)( + struct _cef_domdocument_t* self, const cef_string_t* id); + + /// + // Returns the node that currently has keyboard focus. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_focused_node)( + struct _cef_domdocument_t* self); + + /// + // Returns true (1) if a portion of the document is selected. + /// + int (CEF_CALLBACK *has_selection)(struct _cef_domdocument_t* self); + + /// + // Returns the selection offset within the start node. + /// + int (CEF_CALLBACK *get_selection_start_offset)( + struct _cef_domdocument_t* self); + + /// + // Returns the selection offset within the end node. + /// + int (CEF_CALLBACK *get_selection_end_offset)(struct _cef_domdocument_t* self); + + /// + // Returns the contents of this selection as markup. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_selection_as_markup)( + struct _cef_domdocument_t* self); + + /// + // Returns the contents of this selection as text. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_selection_as_text)( + struct _cef_domdocument_t* self); + + /// + // Returns the base URL for the document. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_base_url)( + struct _cef_domdocument_t* self); + + /// + // Returns a complete URL based on the document base URL and the specified + // partial URL. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_complete_url)( + struct _cef_domdocument_t* self, const cef_string_t* partialURL); +} cef_domdocument_t; + + +/// +// Structure used to represent a DOM node. The functions of this structure +// should only be called on the render process main thread. +/// +typedef struct _cef_domnode_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the type for this node. + /// + cef_dom_node_type_t (CEF_CALLBACK *get_type)(struct _cef_domnode_t* self); + + /// + // Returns true (1) if this is a text node. + /// + int (CEF_CALLBACK *is_text)(struct _cef_domnode_t* self); + + /// + // Returns true (1) if this is an element node. + /// + int (CEF_CALLBACK *is_element)(struct _cef_domnode_t* self); + + /// + // Returns true (1) if this is an editable node. + /// + int (CEF_CALLBACK *is_editable)(struct _cef_domnode_t* self); + + /// + // Returns true (1) if this is a form control element node. + /// + int (CEF_CALLBACK *is_form_control_element)(struct _cef_domnode_t* self); + + /// + // Returns the type of this form control element node. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_form_control_element_type)( + struct _cef_domnode_t* self); + + /// + // Returns true (1) if this object is pointing to the same handle as |that| + // object. + /// + int (CEF_CALLBACK *is_same)(struct _cef_domnode_t* self, + struct _cef_domnode_t* that); + + /// + // Returns the name of this node. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_name)(struct _cef_domnode_t* self); + + /// + // Returns the value of this node. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_value)(struct _cef_domnode_t* self); + + /// + // Set the value of this node. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_value)(struct _cef_domnode_t* self, + const cef_string_t* value); + + /// + // Returns the contents of this node as markup. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_as_markup)( + struct _cef_domnode_t* self); + + /// + // Returns the document associated with this node. + /// + struct _cef_domdocument_t* (CEF_CALLBACK *get_document)( + struct _cef_domnode_t* self); + + /// + // Returns the parent node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_parent)( + struct _cef_domnode_t* self); + + /// + // Returns the previous sibling node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_previous_sibling)( + struct _cef_domnode_t* self); + + /// + // Returns the next sibling node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_next_sibling)( + struct _cef_domnode_t* self); + + /// + // Returns true (1) if this node has child nodes. + /// + int (CEF_CALLBACK *has_children)(struct _cef_domnode_t* self); + + /// + // Return the first child node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_first_child)( + struct _cef_domnode_t* self); + + /// + // Returns the last child node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_last_child)( + struct _cef_domnode_t* self); + + + // The following functions are valid only for element nodes. + + /// + // Returns the tag name of this element. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_element_tag_name)( + struct _cef_domnode_t* self); + + /// + // Returns true (1) if this element has attributes. + /// + int (CEF_CALLBACK *has_element_attributes)(struct _cef_domnode_t* self); + + /// + // Returns true (1) if this element has an attribute named |attrName|. + /// + int (CEF_CALLBACK *has_element_attribute)(struct _cef_domnode_t* self, + const cef_string_t* attrName); + + /// + // Returns the element attribute named |attrName|. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_element_attribute)( + struct _cef_domnode_t* self, const cef_string_t* attrName); + + /// + // Returns a map of all element attributes. + /// + void (CEF_CALLBACK *get_element_attributes)(struct _cef_domnode_t* self, + cef_string_map_t attrMap); + + /// + // Set the value for the element attribute named |attrName|. Returns true (1) + // on success. + /// + int (CEF_CALLBACK *set_element_attribute)(struct _cef_domnode_t* self, + const cef_string_t* attrName, const cef_string_t* value); + + /// + // Returns the inner text of the element. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_element_inner_text)( + struct _cef_domnode_t* self); +} cef_domnode_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DOM_CAPI_H_ diff --git a/include/capi/cef_download_handler_capi.h b/include/capi/cef_download_handler_capi.h new file mode 100644 index 000000000..6acf4fafa --- /dev/null +++ b/include/capi/cef_download_handler_capi.h @@ -0,0 +1,137 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DOWNLOAD_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DOWNLOAD_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_download_item_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure used to asynchronously continue a download. +/// +typedef struct _cef_before_download_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Call to continue the download. Set |download_path| to the full file path + // for the download including the file name or leave blank to use the + // suggested name and the default temp directory. Set |show_dialog| to true + // (1) if you do wish to show the default "Save As" dialog. + /// + void (CEF_CALLBACK *cont)(struct _cef_before_download_callback_t* self, + const cef_string_t* download_path, int show_dialog); +} cef_before_download_callback_t; + + +/// +// Callback structure used to asynchronously cancel a download. +/// +typedef struct _cef_download_item_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Call to cancel the download. + /// + void (CEF_CALLBACK *cancel)(struct _cef_download_item_callback_t* self); + + /// + // Call to pause the download. + /// + void (CEF_CALLBACK *pause)(struct _cef_download_item_callback_t* self); + + /// + // Call to resume the download. + /// + void (CEF_CALLBACK *resume)(struct _cef_download_item_callback_t* self); +} cef_download_item_callback_t; + + +/// +// Structure used to handle file downloads. The functions of this structure will +// called on the browser process UI thread. +/// +typedef struct _cef_download_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called before a download begins. |suggested_name| is the suggested name for + // the download file. By default the download will be canceled. Execute + // |callback| either asynchronously or in this function to continue the + // download if desired. Do not keep a reference to |download_item| outside of + // this function. + /// + void (CEF_CALLBACK *on_before_download)(struct _cef_download_handler_t* self, + struct _cef_browser_t* browser, + struct _cef_download_item_t* download_item, + const cef_string_t* suggested_name, + struct _cef_before_download_callback_t* callback); + + /// + // Called when a download's status or progress information has been updated. + // This may be called multiple times before and after on_before_download(). + // Execute |callback| either asynchronously or in this function to cancel the + // download if desired. Do not keep a reference to |download_item| outside of + // this function. + /// + void (CEF_CALLBACK *on_download_updated)(struct _cef_download_handler_t* self, + struct _cef_browser_t* browser, + struct _cef_download_item_t* download_item, + struct _cef_download_item_callback_t* callback); +} cef_download_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DOWNLOAD_HANDLER_CAPI_H_ diff --git a/include/capi/cef_download_item_capi.h b/include/capi/cef_download_item_capi.h new file mode 100644 index 000000000..6da4c684b --- /dev/null +++ b/include/capi/cef_download_item_capi.h @@ -0,0 +1,162 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DOWNLOAD_ITEM_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DOWNLOAD_ITEM_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to represent a download item. +/// +typedef struct _cef_download_item_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_download_item_t* self); + + /// + // Returns true (1) if the download is in progress. + /// + int (CEF_CALLBACK *is_in_progress)(struct _cef_download_item_t* self); + + /// + // Returns true (1) if the download is complete. + /// + int (CEF_CALLBACK *is_complete)(struct _cef_download_item_t* self); + + /// + // Returns true (1) if the download has been canceled or interrupted. + /// + int (CEF_CALLBACK *is_canceled)(struct _cef_download_item_t* self); + + /// + // Returns a simple speed estimate in bytes/s. + /// + int64 (CEF_CALLBACK *get_current_speed)(struct _cef_download_item_t* self); + + /// + // Returns the rough percent complete or -1 if the receive total size is + // unknown. + /// + int (CEF_CALLBACK *get_percent_complete)(struct _cef_download_item_t* self); + + /// + // Returns the total number of bytes. + /// + int64 (CEF_CALLBACK *get_total_bytes)(struct _cef_download_item_t* self); + + /// + // Returns the number of received bytes. + /// + int64 (CEF_CALLBACK *get_received_bytes)(struct _cef_download_item_t* self); + + /// + // Returns the time that the download started. + /// + cef_time_t (CEF_CALLBACK *get_start_time)(struct _cef_download_item_t* self); + + /// + // Returns the time that the download ended. + /// + cef_time_t (CEF_CALLBACK *get_end_time)(struct _cef_download_item_t* self); + + /// + // Returns the full path to the downloaded or downloading file. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_full_path)( + struct _cef_download_item_t* self); + + /// + // Returns the unique identifier for this download. + /// + uint32 (CEF_CALLBACK *get_id)(struct _cef_download_item_t* self); + + /// + // Returns the URL. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_url)( + struct _cef_download_item_t* self); + + /// + // Returns the original URL before any redirections. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_original_url)( + struct _cef_download_item_t* self); + + /// + // Returns the suggested file name. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_suggested_file_name)( + struct _cef_download_item_t* self); + + /// + // Returns the content disposition. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_content_disposition)( + struct _cef_download_item_t* self); + + /// + // Returns the mime type. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_mime_type)( + struct _cef_download_item_t* self); +} cef_download_item_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DOWNLOAD_ITEM_CAPI_H_ diff --git a/include/capi/cef_drag_data_capi.h b/include/capi/cef_drag_data_capi.h new file mode 100644 index 000000000..a24dd1ff4 --- /dev/null +++ b/include/capi/cef_drag_data_capi.h @@ -0,0 +1,211 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_stream_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to represent drag data. The functions of this structure may be +// called on any thread. +/// +typedef struct _cef_drag_data_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns a copy of the current object. + /// + struct _cef_drag_data_t* (CEF_CALLBACK *clone)(struct _cef_drag_data_t* self); + + /// + // Returns true (1) if this object is read-only. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_drag_data_t* self); + + /// + // Returns true (1) if the drag data is a link. + /// + int (CEF_CALLBACK *is_link)(struct _cef_drag_data_t* self); + + /// + // Returns true (1) if the drag data is a text or html fragment. + /// + int (CEF_CALLBACK *is_fragment)(struct _cef_drag_data_t* self); + + /// + // Returns true (1) if the drag data is a file. + /// + int (CEF_CALLBACK *is_file)(struct _cef_drag_data_t* self); + + /// + // Return the link URL that is being dragged. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_link_url)( + struct _cef_drag_data_t* self); + + /// + // Return the title associated with the link being dragged. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_link_title)( + struct _cef_drag_data_t* self); + + /// + // Return the metadata, if any, associated with the link being dragged. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_link_metadata)( + struct _cef_drag_data_t* self); + + /// + // Return the plain text fragment that is being dragged. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_fragment_text)( + struct _cef_drag_data_t* self); + + /// + // Return the text/html fragment that is being dragged. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_fragment_html)( + struct _cef_drag_data_t* self); + + /// + // Return the base URL that the fragment came from. This value is used for + // resolving relative URLs and may be NULL. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_fragment_base_url)( + struct _cef_drag_data_t* self); + + /// + // Return the name of the file being dragged out of the browser window. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_file_name)( + struct _cef_drag_data_t* self); + + /// + // Write the contents of the file being dragged out of the web view into + // |writer|. Returns the number of bytes sent to |writer|. If |writer| is NULL + // this function will return the size of the file contents in bytes. Call + // get_file_name() to get a suggested name for the file. + /// + size_t (CEF_CALLBACK *get_file_contents)(struct _cef_drag_data_t* self, + struct _cef_stream_writer_t* writer); + + /// + // Retrieve the list of file names that are being dragged into the browser + // window. + /// + int (CEF_CALLBACK *get_file_names)(struct _cef_drag_data_t* self, + cef_string_list_t names); + + /// + // Set the link URL that is being dragged. + /// + void (CEF_CALLBACK *set_link_url)(struct _cef_drag_data_t* self, + const cef_string_t* url); + + /// + // Set the title associated with the link being dragged. + /// + void (CEF_CALLBACK *set_link_title)(struct _cef_drag_data_t* self, + const cef_string_t* title); + + /// + // Set the metadata associated with the link being dragged. + /// + void (CEF_CALLBACK *set_link_metadata)(struct _cef_drag_data_t* self, + const cef_string_t* data); + + /// + // Set the plain text fragment that is being dragged. + /// + void (CEF_CALLBACK *set_fragment_text)(struct _cef_drag_data_t* self, + const cef_string_t* text); + + /// + // Set the text/html fragment that is being dragged. + /// + void (CEF_CALLBACK *set_fragment_html)(struct _cef_drag_data_t* self, + const cef_string_t* html); + + /// + // Set the base URL that the fragment came from. + /// + void (CEF_CALLBACK *set_fragment_base_url)(struct _cef_drag_data_t* self, + const cef_string_t* base_url); + + /// + // Reset the file contents. You should do this before calling + // cef_browser_host_t::DragTargetDragEnter as the web view does not allow us + // to drag in this kind of data. + /// + void (CEF_CALLBACK *reset_file_contents)(struct _cef_drag_data_t* self); + + /// + // Add a file that is being dragged into the webview. + /// + void (CEF_CALLBACK *add_file)(struct _cef_drag_data_t* self, + const cef_string_t* path, const cef_string_t* display_name); +} cef_drag_data_t; + + +/// +// Create a new cef_drag_data_t object. +/// +CEF_EXPORT cef_drag_data_t* cef_drag_data_create(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_ diff --git a/include/capi/cef_drag_handler_capi.h b/include/capi/cef_drag_handler_capi.h new file mode 100644 index 000000000..1e2368b25 --- /dev/null +++ b/include/capi/cef_drag_handler_capi.h @@ -0,0 +1,76 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_drag_data_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events related to dragging. The functions +// of this structure will be called on the UI thread. +/// +typedef struct _cef_drag_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called when an external drag event enters the browser window. |dragData| + // contains the drag event data and |mask| represents the type of drag + // operation. Return false (0) for default drag handling behavior or true (1) + // to cancel the drag event. + /// + int (CEF_CALLBACK *on_drag_enter)(struct _cef_drag_handler_t* self, + struct _cef_browser_t* browser, struct _cef_drag_data_t* dragData, + cef_drag_operations_mask_t mask); +} cef_drag_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DRAG_HANDLER_CAPI_H_ diff --git a/include/capi/cef_find_handler_capi.h b/include/capi/cef_find_handler_capi.h new file mode 100644 index 000000000..14e15bb86 --- /dev/null +++ b/include/capi/cef_find_handler_capi.h @@ -0,0 +1,78 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_FIND_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_FIND_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events related to find results. The +// functions of this structure will be called on the UI thread. +/// +typedef struct _cef_find_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to report find results returned by cef_browser_host_t::find(). + // |identifer| is the identifier passed to find(), |count| is the number of + // matches currently identified, |selectionRect| is the location of where the + // match was found (in window coordinates), |activeMatchOrdinal| is the + // current position in the search results, and |finalUpdate| is true (1) if + // this is the last find notification. + /// + void (CEF_CALLBACK *on_find_result)(struct _cef_find_handler_t* self, + struct _cef_browser_t* browser, int identifier, int count, + const cef_rect_t* selectionRect, int activeMatchOrdinal, + int finalUpdate); +} cef_find_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_FIND_HANDLER_CAPI_H_ diff --git a/include/capi/cef_focus_handler_capi.h b/include/capi/cef_focus_handler_capi.h new file mode 100644 index 000000000..c0c1e9d9c --- /dev/null +++ b/include/capi/cef_focus_handler_capi.h @@ -0,0 +1,90 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_FOCUS_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_FOCUS_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_dom_capi.h" +#include "include/capi/cef_frame_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events related to focus. The functions of +// this structure will be called on the UI thread. +/// +typedef struct _cef_focus_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called when the browser component is about to loose focus. For instance, if + // focus was on the last HTML element and the user pressed the TAB key. |next| + // will be true (1) if the browser is giving focus to the next component and + // false (0) if the browser is giving focus to the previous component. + /// + void (CEF_CALLBACK *on_take_focus)(struct _cef_focus_handler_t* self, + struct _cef_browser_t* browser, int next); + + /// + // Called when the browser component is requesting focus. |source| indicates + // where the focus request is originating from. Return false (0) to allow the + // focus to be set or true (1) to cancel setting the focus. + /// + int (CEF_CALLBACK *on_set_focus)(struct _cef_focus_handler_t* self, + struct _cef_browser_t* browser, cef_focus_source_t source); + + /// + // Called when the browser component has received focus. + /// + void (CEF_CALLBACK *on_got_focus)(struct _cef_focus_handler_t* self, + struct _cef_browser_t* browser); +} cef_focus_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_FOCUS_HANDLER_CAPI_H_ diff --git a/include/capi/cef_frame_capi.h b/include/capi/cef_frame_capi.h new file mode 100644 index 000000000..c1c40bdf6 --- /dev/null +++ b/include/capi/cef_frame_capi.h @@ -0,0 +1,220 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_FRAME_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_FRAME_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_dom_capi.h" +#include "include/capi/cef_request_capi.h" +#include "include/capi/cef_stream_capi.h" +#include "include/capi/cef_string_visitor_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_browser_t; +struct _cef_v8context_t; + +/// +// Structure used to represent a frame in the browser window. When used in the +// browser process the functions of this structure may be called on any thread +// unless otherwise indicated in the comments. When used in the render process +// the functions of this structure may only be called on the main thread. +/// +typedef struct _cef_frame_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // True if this object is currently attached to a valid frame. + /// + int (CEF_CALLBACK *is_valid)(struct _cef_frame_t* self); + + /// + // Execute undo in this frame. + /// + void (CEF_CALLBACK *undo)(struct _cef_frame_t* self); + + /// + // Execute redo in this frame. + /// + void (CEF_CALLBACK *redo)(struct _cef_frame_t* self); + + /// + // Execute cut in this frame. + /// + void (CEF_CALLBACK *cut)(struct _cef_frame_t* self); + + /// + // Execute copy in this frame. + /// + void (CEF_CALLBACK *copy)(struct _cef_frame_t* self); + + /// + // Execute paste in this frame. + /// + void (CEF_CALLBACK *paste)(struct _cef_frame_t* self); + + /// + // Execute delete in this frame. + /// + void (CEF_CALLBACK *del)(struct _cef_frame_t* self); + + /// + // Execute select all in this frame. + /// + void (CEF_CALLBACK *select_all)(struct _cef_frame_t* self); + + /// + // Save this frame's HTML source to a temporary file and open it in the + // default text viewing application. This function can only be called from the + // browser process. + /// + void (CEF_CALLBACK *view_source)(struct _cef_frame_t* self); + + /// + // Retrieve this frame's HTML source as a string sent to the specified + // visitor. + /// + void (CEF_CALLBACK *get_source)(struct _cef_frame_t* self, + struct _cef_string_visitor_t* visitor); + + /// + // Retrieve this frame's display text as a string sent to the specified + // visitor. + /// + void (CEF_CALLBACK *get_text)(struct _cef_frame_t* self, + struct _cef_string_visitor_t* visitor); + + /// + // Load the request represented by the |request| object. + /// + void (CEF_CALLBACK *load_request)(struct _cef_frame_t* self, + struct _cef_request_t* request); + + /// + // Load the specified |url|. + /// + void (CEF_CALLBACK *load_url)(struct _cef_frame_t* self, + const cef_string_t* url); + + /// + // Load the contents of |string_val| with the specified dummy |url|. |url| + // should have a standard scheme (for example, http scheme) or behaviors like + // link clicks and web security restrictions may not behave as expected. + /// + void (CEF_CALLBACK *load_string)(struct _cef_frame_t* self, + const cef_string_t* string_val, const cef_string_t* url); + + /// + // Execute a string of JavaScript code in this frame. The |script_url| + // parameter is the URL where the script in question can be found, if any. The + // renderer may request this URL to show the developer the source of the + // error. The |start_line| parameter is the base line number to use for error + // reporting. + /// + void (CEF_CALLBACK *execute_java_script)(struct _cef_frame_t* self, + const cef_string_t* code, const cef_string_t* script_url, + int start_line); + + /// + // Returns true (1) if this is the main (top-level) frame. + /// + int (CEF_CALLBACK *is_main)(struct _cef_frame_t* self); + + /// + // Returns true (1) if this is the focused frame. + /// + int (CEF_CALLBACK *is_focused)(struct _cef_frame_t* self); + + /// + // Returns the name for this frame. If the frame has an assigned name (for + // example, set via the iframe "name" attribute) then that value will be + // returned. Otherwise a unique name will be constructed based on the frame + // parent hierarchy. The main (top-level) frame will always have an NULL name + // value. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_name)(struct _cef_frame_t* self); + + /// + // Returns the globally unique identifier for this frame. + /// + int64 (CEF_CALLBACK *get_identifier)(struct _cef_frame_t* self); + + /// + // Returns the parent of this frame or NULL if this is the main (top-level) + // frame. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_parent)(struct _cef_frame_t* self); + + /// + // Returns the URL currently loaded in this frame. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_url)(struct _cef_frame_t* self); + + /// + // Returns the browser that this frame belongs to. + /// + struct _cef_browser_t* (CEF_CALLBACK *get_browser)(struct _cef_frame_t* self); + + /// + // Get the V8 context associated with the frame. This function can only be + // called from the render process. + /// + struct _cef_v8context_t* (CEF_CALLBACK *get_v8context)( + struct _cef_frame_t* self); + + /// + // Visit the DOM document. This function can only be called from the render + // process. + /// + void (CEF_CALLBACK *visit_dom)(struct _cef_frame_t* self, + struct _cef_domvisitor_t* visitor); +} cef_frame_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_FRAME_CAPI_H_ diff --git a/include/capi/cef_geolocation_capi.h b/include/capi/cef_geolocation_capi.h new file mode 100644 index 000000000..8a72c5b7f --- /dev/null +++ b/include/capi/cef_geolocation_capi.h @@ -0,0 +1,79 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_GEOLOCATION_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_GEOLOCATION_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to receive geolocation updates. The functions of +// this structure will be called on the browser process UI thread. +/// +typedef struct _cef_get_geolocation_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called with the 'best available' location information or, if the location + // update failed, with error information. + /// + void (CEF_CALLBACK *on_location_update)( + struct _cef_get_geolocation_callback_t* self, + const struct _cef_geoposition_t* position); +} cef_get_geolocation_callback_t; + + +/// +// Request a one-time geolocation update. This function bypasses any user +// permission checks so should only be used by code that is allowed to access +// location information. +/// +CEF_EXPORT int cef_get_geolocation(cef_get_geolocation_callback_t* callback); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_GEOLOCATION_CAPI_H_ diff --git a/include/capi/cef_geolocation_handler_capi.h b/include/capi/cef_geolocation_handler_capi.h new file mode 100644 index 000000000..f739f4df0 --- /dev/null +++ b/include/capi/cef_geolocation_handler_capi.h @@ -0,0 +1,106 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_GEOLOCATION_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_GEOLOCATION_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure used for asynchronous continuation of geolocation +// permission requests. +/// +typedef struct _cef_geolocation_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Call to allow or deny geolocation access. + /// + void (CEF_CALLBACK *cont)(struct _cef_geolocation_callback_t* self, + int allow); +} cef_geolocation_callback_t; + + +/// +// Implement this structure to handle events related to geolocation permission +// requests. The functions of this structure will be called on the browser +// process UI thread. +/// +typedef struct _cef_geolocation_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called when a page requests permission to access geolocation information. + // |requesting_url| is the URL requesting permission and |request_id| is the + // unique ID for the permission request. Return true (1) and call + // cef_geolocation_callback_t::cont() either in this function or at a later + // time to continue or cancel the request. Return false (0) to cancel the + // request immediately. + /// + int (CEF_CALLBACK *on_request_geolocation_permission)( + struct _cef_geolocation_handler_t* self, struct _cef_browser_t* browser, + const cef_string_t* requesting_url, int request_id, + struct _cef_geolocation_callback_t* callback); + + /// + // Called when a geolocation access request is canceled. |requesting_url| is + // the URL that originally requested permission and |request_id| is the unique + // ID for the permission request. + /// + void (CEF_CALLBACK *on_cancel_geolocation_permission)( + struct _cef_geolocation_handler_t* self, struct _cef_browser_t* browser, + const cef_string_t* requesting_url, int request_id); +} cef_geolocation_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_GEOLOCATION_HANDLER_CAPI_H_ diff --git a/include/capi/cef_jsdialog_handler_capi.h b/include/capi/cef_jsdialog_handler_capi.h new file mode 100644 index 000000000..c674341f1 --- /dev/null +++ b/include/capi/cef_jsdialog_handler_capi.h @@ -0,0 +1,133 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_JSDIALOG_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_JSDIALOG_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure used for asynchronous continuation of JavaScript dialog +// requests. +/// +typedef struct _cef_jsdialog_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue the JS dialog request. Set |success| to true (1) if the OK button + // was pressed. The |user_input| value should be specified for prompt dialogs. + /// + void (CEF_CALLBACK *cont)(struct _cef_jsdialog_callback_t* self, int success, + const cef_string_t* user_input); +} cef_jsdialog_callback_t; + + +/// +// Implement this structure to handle events related to JavaScript dialogs. The +// functions of this structure will be called on the UI thread. +/// +typedef struct _cef_jsdialog_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to run a JavaScript dialog. The |default_prompt_text| value will be + // specified for prompt dialogs only. Set |suppress_message| to true (1) and + // return false (0) to suppress the message (suppressing messages is + // preferable to immediately executing the callback as this is used to detect + // presumably malicious behavior like spamming alert messages in + // onbeforeunload). Set |suppress_message| to false (0) and return false (0) + // to use the default implementation (the default implementation will show one + // modal dialog at a time and suppress any additional dialog requests until + // the displayed dialog is dismissed). Return true (1) if the application will + // use a custom dialog or if the callback has been executed immediately. + // Custom dialogs may be either modal or modeless. If a custom dialog is used + // the application must execute |callback| once the custom dialog is + // dismissed. + /// + int (CEF_CALLBACK *on_jsdialog)(struct _cef_jsdialog_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* origin_url, + const cef_string_t* accept_lang, cef_jsdialog_type_t dialog_type, + const cef_string_t* message_text, + const cef_string_t* default_prompt_text, + struct _cef_jsdialog_callback_t* callback, int* suppress_message); + + /// + // Called to run a dialog asking the user if they want to leave a page. Return + // false (0) to use the default dialog implementation. Return true (1) if the + // application will use a custom dialog or if the callback has been executed + // immediately. Custom dialogs may be either modal or modeless. If a custom + // dialog is used the application must execute |callback| once the custom + // dialog is dismissed. + /// + int (CEF_CALLBACK *on_before_unload_dialog)( + struct _cef_jsdialog_handler_t* self, struct _cef_browser_t* browser, + const cef_string_t* message_text, int is_reload, + struct _cef_jsdialog_callback_t* callback); + + /// + // Called to cancel any pending dialogs and reset any saved dialog state. Will + // be called due to events like page navigation irregardless of whether any + // dialogs are currently pending. + /// + void (CEF_CALLBACK *on_reset_dialog_state)( + struct _cef_jsdialog_handler_t* self, struct _cef_browser_t* browser); + + /// + // Called when the default implementation dialog is closed. + /// + void (CEF_CALLBACK *on_dialog_closed)(struct _cef_jsdialog_handler_t* self, + struct _cef_browser_t* browser); +} cef_jsdialog_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_JSDIALOG_HANDLER_CAPI_H_ diff --git a/include/capi/cef_keyboard_handler_capi.h b/include/capi/cef_keyboard_handler_capi.h new file mode 100644 index 000000000..a50e1977f --- /dev/null +++ b/include/capi/cef_keyboard_handler_capi.h @@ -0,0 +1,84 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_KEYBOARD_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_KEYBOARD_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events related to keyboard input. The +// functions of this structure will be called on the UI thread. +/// +typedef struct _cef_keyboard_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + // Called before a keyboard event is sent to the renderer. |event| contains + // information about the keyboard event. |os_event| is the operating system + // event message, if any. Return true (1) if the event was handled or false + // (0) otherwise. If the event will be handled in on_key_event() as a keyboard + // shortcut set |is_keyboard_shortcut| to true (1) and return false (0). + int (CEF_CALLBACK *on_pre_key_event)(struct _cef_keyboard_handler_t* self, + struct _cef_browser_t* browser, const struct _cef_key_event_t* event, + cef_event_handle_t os_event, int* is_keyboard_shortcut); + + /// + // Called after the renderer and JavaScript in the page has had a chance to + // handle the event. |event| contains information about the keyboard event. + // |os_event| is the operating system event message, if any. Return true (1) + // if the keyboard event was handled or false (0) otherwise. + /// + int (CEF_CALLBACK *on_key_event)(struct _cef_keyboard_handler_t* self, + struct _cef_browser_t* browser, const struct _cef_key_event_t* event, + cef_event_handle_t os_event); +} cef_keyboard_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_KEYBOARD_HANDLER_CAPI_H_ diff --git a/include/capi/cef_life_span_handler_capi.h b/include/capi/cef_life_span_handler_capi.h new file mode 100644 index 000000000..2bb000212 --- /dev/null +++ b/include/capi/cef_life_span_handler_capi.h @@ -0,0 +1,171 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_LIFE_SPAN_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_LIFE_SPAN_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_client_t; + +/// +// Implement this structure to handle events related to browser life span. The +// functions of this structure will be called on the UI thread unless otherwise +// indicated. +/// +typedef struct _cef_life_span_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called on the IO thread before a new popup window is created. The |browser| + // and |frame| parameters represent the source of the popup request. The + // |target_url| and |target_frame_name| values may be NULL if none were + // specified with the request. The |popupFeatures| structure contains + // information about the requested popup window. To allow creation of the + // popup window optionally modify |windowInfo|, |client|, |settings| and + // |no_javascript_access| and return false (0). To cancel creation of the + // popup window return true (1). The |client| and |settings| values will + // default to the source browser's values. The |no_javascript_access| value + // indicates whether the new browser window should be scriptable and in the + // same process as the source browser. + int (CEF_CALLBACK *on_before_popup)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* target_url, const cef_string_t* target_frame_name, + const struct _cef_popup_features_t* popupFeatures, + struct _cef_window_info_t* windowInfo, struct _cef_client_t** client, + struct _cef_browser_settings_t* settings, int* no_javascript_access); + + /// + // Called after a new browser is created. + /// + void (CEF_CALLBACK *on_after_created)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* browser); + + /// + // Called when a modal window is about to display and the modal loop should + // begin running. Return false (0) to use the default modal loop + // implementation or true (1) to use a custom implementation. + /// + int (CEF_CALLBACK *run_modal)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* browser); + + /// + // Called when a browser has recieved a request to close. This may result + // directly from a call to cef_browser_host_t::close_browser() or indirectly + // if the browser is a top-level OS window created by CEF and the user + // attempts to close the window. This function will be called after the + // JavaScript 'onunload' event has been fired. It will not be called for + // browsers after the associated OS window has been destroyed (for those + // browsers it is no longer possible to cancel the close). + // + // If CEF created an OS window for the browser returning false (0) will send + // an OS close notification to the browser window's top-level owner (e.g. + // WM_CLOSE on Windows, performClose: on OS-X and "delete_event" on Linux). If + // no OS window exists (window rendering disabled) returning false (0) will + // cause the browser object to be destroyed immediately. Return true (1) if + // the browser is parented to another window and that other window needs to + // receive close notification via some non-standard technique. + // + // If an application provides its own top-level window it should handle OS + // close notifications by calling cef_browser_host_t::CloseBrowser(false (0)) + // instead of immediately closing (see the example below). This gives CEF an + // opportunity to process the 'onbeforeunload' event and optionally cancel the + // close before do_close() is called. + // + // The cef_life_span_handler_t::on_before_close() function will be called + // immediately before the browser object is destroyed. The application should + // only exit after on_before_close() has been called for all existing + // browsers. + // + // If the browser represents a modal window and a custom modal loop + // implementation was provided in cef_life_span_handler_t::run_modal() this + // callback should be used to restore the opener window to a usable state. + // + // By way of example consider what should happen during window close when the + // browser is parented to an application-provided top-level OS window. 1. + // User clicks the window close button which sends an OS close + // notification (e.g. WM_CLOSE on Windows, performClose: on OS-X and + // "delete_event" on Linux). + // 2. Application's top-level window receives the close notification and: + // A. Calls CefBrowserHost::CloseBrowser(false). + // B. Cancels the window close. + // 3. JavaScript 'onbeforeunload' handler executes and shows the close + // confirmation dialog (which can be overridden via + // CefJSDialogHandler::OnBeforeUnloadDialog()). + // 4. User approves the close. 5. JavaScript 'onunload' handler executes. 6. + // Application's do_close() handler is called. Application will: + // A. Set a flag to indicate that the next close attempt will be allowed. + // B. Return false. + // 7. CEF sends an OS close notification. 8. Application's top-level window + // receives the OS close notification and + // allows the window to close based on the flag from #6B. + // 9. Browser OS window is destroyed. 10. Application's + // cef_life_span_handler_t::on_before_close() handler is called and + // the browser object is destroyed. + // 11. Application exits by calling cef_quit_message_loop() if no other + // browsers + // exist. + /// + int (CEF_CALLBACK *do_close)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* browser); + + /// + // Called just before a browser is destroyed. Release all references to the + // browser object and do not attempt to execute any functions on the browser + // object after this callback returns. If this is a modal window and a custom + // modal loop implementation was provided in run_modal() this callback should + // be used to exit the custom modal loop. See do_close() documentation for + // additional usage information. + /// + void (CEF_CALLBACK *on_before_close)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* browser); +} cef_life_span_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_LIFE_SPAN_HANDLER_CAPI_H_ diff --git a/include/capi/cef_load_handler_capi.h b/include/capi/cef_load_handler_capi.h new file mode 100644 index 000000000..21388b54c --- /dev/null +++ b/include/capi/cef_load_handler_capi.h @@ -0,0 +1,112 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_LOAD_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_LOAD_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_frame_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events related to browser load status. The +// functions of this structure will be called on the browser process UI thread +// or render process main thread (TID_RENDERER). +/// +typedef struct _cef_load_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called when the loading state has changed. This callback will be executed + // twice -- once when loading is initiated either programmatically or by user + // action, and once when loading is terminated due to completion, cancellation + // of failure. + /// + void (CEF_CALLBACK *on_loading_state_change)(struct _cef_load_handler_t* self, + struct _cef_browser_t* browser, int isLoading, int canGoBack, + int canGoForward); + + /// + // Called when the browser begins loading a frame. The |frame| value will + // never be NULL -- call the is_main() function to check if this frame is the + // main frame. Multiple frames may be loading at the same time. Sub-frames may + // start or continue loading after the main frame load has ended. This + // function may not be called for a particular frame if the load request for + // that frame fails. For notification of overall browser load status use + // OnLoadingStateChange instead. + /// + void (CEF_CALLBACK *on_load_start)(struct _cef_load_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame); + + /// + // Called when the browser is done loading a frame. The |frame| value will + // never be NULL -- call the is_main() function to check if this frame is the + // main frame. Multiple frames may be loading at the same time. Sub-frames may + // start or continue loading after the main frame load has ended. This + // function will always be called for all frames irrespective of whether the + // request completes successfully. + /// + void (CEF_CALLBACK *on_load_end)(struct _cef_load_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + int httpStatusCode); + + /// + // Called when the resource load for a navigation fails or is canceled. + // |errorCode| is the error code number, |errorText| is the error text and + // |failedUrl| is the URL that failed to load. See net\base\net_error_list.h + // for complete descriptions of the error codes. + /// + void (CEF_CALLBACK *on_load_error)(struct _cef_load_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + cef_errorcode_t errorCode, const cef_string_t* errorText, + const cef_string_t* failedUrl); +} cef_load_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_LOAD_HANDLER_CAPI_H_ diff --git a/include/capi/cef_menu_model_capi.h b/include/capi/cef_menu_model_capi.h new file mode 100644 index 000000000..0a9c21a75 --- /dev/null +++ b/include/capi/cef_menu_model_capi.h @@ -0,0 +1,388 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_MENU_MODEL_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_MENU_MODEL_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Supports creation and modification of menus. See cef_menu_id_t for the +// command ids that have default implementations. All user-defined command ids +// should be between MENU_ID_USER_FIRST and MENU_ID_USER_LAST. The functions of +// this structure can only be accessed on the browser process the UI thread. +/// +typedef struct _cef_menu_model_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Clears the menu. Returns true (1) on success. + /// + int (CEF_CALLBACK *clear)(struct _cef_menu_model_t* self); + + /// + // Returns the number of items in this menu. + /// + int (CEF_CALLBACK *get_count)(struct _cef_menu_model_t* self); + + // + // Add a separator to the menu. Returns true (1) on success. + /// + int (CEF_CALLBACK *add_separator)(struct _cef_menu_model_t* self); + + // + // Add an item to the menu. Returns true (1) on success. + /// + int (CEF_CALLBACK *add_item)(struct _cef_menu_model_t* self, int command_id, + const cef_string_t* label); + + // + // Add a check item to the menu. Returns true (1) on success. + /// + int (CEF_CALLBACK *add_check_item)(struct _cef_menu_model_t* self, + int command_id, const cef_string_t* label); + + // + // Add a radio item to the menu. Only a single item with the specified + // |group_id| can be checked at a time. Returns true (1) on success. + /// + int (CEF_CALLBACK *add_radio_item)(struct _cef_menu_model_t* self, + int command_id, const cef_string_t* label, int group_id); + + // + // Add a sub-menu to the menu. The new sub-menu is returned. + /// + struct _cef_menu_model_t* (CEF_CALLBACK *add_sub_menu)( + struct _cef_menu_model_t* self, int command_id, + const cef_string_t* label); + + // + // Insert a separator in the menu at the specified |index|. Returns true (1) + // on success. + /// + int (CEF_CALLBACK *insert_separator_at)(struct _cef_menu_model_t* self, + int index); + + // + // Insert an item in the menu at the specified |index|. Returns true (1) on + // success. + /// + int (CEF_CALLBACK *insert_item_at)(struct _cef_menu_model_t* self, int index, + int command_id, const cef_string_t* label); + + // + // Insert a check item in the menu at the specified |index|. Returns true (1) + // on success. + /// + int (CEF_CALLBACK *insert_check_item_at)(struct _cef_menu_model_t* self, + int index, int command_id, const cef_string_t* label); + + // + // Insert a radio item in the menu at the specified |index|. Only a single + // item with the specified |group_id| can be checked at a time. Returns true + // (1) on success. + /// + int (CEF_CALLBACK *insert_radio_item_at)(struct _cef_menu_model_t* self, + int index, int command_id, const cef_string_t* label, int group_id); + + // + // Insert a sub-menu in the menu at the specified |index|. The new sub-menu is + // returned. + /// + struct _cef_menu_model_t* (CEF_CALLBACK *insert_sub_menu_at)( + struct _cef_menu_model_t* self, int index, int command_id, + const cef_string_t* label); + + /// + // Removes the item with the specified |command_id|. Returns true (1) on + // success. + /// + int (CEF_CALLBACK *remove)(struct _cef_menu_model_t* self, int command_id); + + /// + // Removes the item at the specified |index|. Returns true (1) on success. + /// + int (CEF_CALLBACK *remove_at)(struct _cef_menu_model_t* self, int index); + + /// + // Returns the index associated with the specified |command_id| or -1 if not + // found due to the command id not existing in the menu. + /// + int (CEF_CALLBACK *get_index_of)(struct _cef_menu_model_t* self, + int command_id); + + /// + // Returns the command id at the specified |index| or -1 if not found due to + // invalid range or the index being a separator. + /// + int (CEF_CALLBACK *get_command_id_at)(struct _cef_menu_model_t* self, + int index); + + /// + // Sets the command id at the specified |index|. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_command_id_at)(struct _cef_menu_model_t* self, + int index, int command_id); + + /// + // Returns the label for the specified |command_id| or NULL if not found. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_label)( + struct _cef_menu_model_t* self, int command_id); + + /// + // Returns the label at the specified |index| or NULL if not found due to + // invalid range or the index being a separator. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_label_at)( + struct _cef_menu_model_t* self, int index); + + /// + // Sets the label for the specified |command_id|. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_label)(struct _cef_menu_model_t* self, int command_id, + const cef_string_t* label); + + /// + // Set the label at the specified |index|. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_label_at)(struct _cef_menu_model_t* self, int index, + const cef_string_t* label); + + /// + // Returns the item type for the specified |command_id|. + /// + cef_menu_item_type_t (CEF_CALLBACK *get_type)(struct _cef_menu_model_t* self, + int command_id); + + /// + // Returns the item type at the specified |index|. + /// + cef_menu_item_type_t (CEF_CALLBACK *get_type_at)( + struct _cef_menu_model_t* self, int index); + + /// + // Returns the group id for the specified |command_id| or -1 if invalid. + /// + int (CEF_CALLBACK *get_group_id)(struct _cef_menu_model_t* self, + int command_id); + + /// + // Returns the group id at the specified |index| or -1 if invalid. + /// + int (CEF_CALLBACK *get_group_id_at)(struct _cef_menu_model_t* self, + int index); + + /// + // Sets the group id for the specified |command_id|. Returns true (1) on + // success. + /// + int (CEF_CALLBACK *set_group_id)(struct _cef_menu_model_t* self, + int command_id, int group_id); + + /// + // Sets the group id at the specified |index|. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_group_id_at)(struct _cef_menu_model_t* self, int index, + int group_id); + + /// + // Returns the submenu for the specified |command_id| or NULL if invalid. + /// + struct _cef_menu_model_t* (CEF_CALLBACK *get_sub_menu)( + struct _cef_menu_model_t* self, int command_id); + + /// + // Returns the submenu at the specified |index| or NULL if invalid. + /// + struct _cef_menu_model_t* (CEF_CALLBACK *get_sub_menu_at)( + struct _cef_menu_model_t* self, int index); + + // + // Returns true (1) if the specified |command_id| is visible. + /// + int (CEF_CALLBACK *is_visible)(struct _cef_menu_model_t* self, + int command_id); + + // + // Returns true (1) if the specified |index| is visible. + /// + int (CEF_CALLBACK *is_visible_at)(struct _cef_menu_model_t* self, int index); + + // + // Change the visibility of the specified |command_id|. Returns true (1) on + // success. + /// + int (CEF_CALLBACK *set_visible)(struct _cef_menu_model_t* self, + int command_id, int visible); + + // + // Change the visibility at the specified |index|. Returns true (1) on + // success. + /// + int (CEF_CALLBACK *set_visible_at)(struct _cef_menu_model_t* self, int index, + int visible); + + // + // Returns true (1) if the specified |command_id| is enabled. + /// + int (CEF_CALLBACK *is_enabled)(struct _cef_menu_model_t* self, + int command_id); + + // + // Returns true (1) if the specified |index| is enabled. + /// + int (CEF_CALLBACK *is_enabled_at)(struct _cef_menu_model_t* self, int index); + + // + // Change the enabled status of the specified |command_id|. Returns true (1) + // on success. + /// + int (CEF_CALLBACK *set_enabled)(struct _cef_menu_model_t* self, + int command_id, int enabled); + + // + // Change the enabled status at the specified |index|. Returns true (1) on + // success. + /// + int (CEF_CALLBACK *set_enabled_at)(struct _cef_menu_model_t* self, int index, + int enabled); + + // + // Returns true (1) if the specified |command_id| is checked. Only applies to + // check and radio items. + /// + int (CEF_CALLBACK *is_checked)(struct _cef_menu_model_t* self, + int command_id); + + // + // Returns true (1) if the specified |index| is checked. Only applies to check + // and radio items. + /// + int (CEF_CALLBACK *is_checked_at)(struct _cef_menu_model_t* self, int index); + + // + // Check the specified |command_id|. Only applies to check and radio items. + // Returns true (1) on success. + /// + int (CEF_CALLBACK *set_checked)(struct _cef_menu_model_t* self, + int command_id, int checked); + + // + // Check the specified |index|. Only applies to check and radio items. Returns + // true (1) on success. + /// + int (CEF_CALLBACK *set_checked_at)(struct _cef_menu_model_t* self, int index, + int checked); + + // + // Returns true (1) if the specified |command_id| has a keyboard accelerator + // assigned. + /// + int (CEF_CALLBACK *has_accelerator)(struct _cef_menu_model_t* self, + int command_id); + + // + // Returns true (1) if the specified |index| has a keyboard accelerator + // assigned. + /// + int (CEF_CALLBACK *has_accelerator_at)(struct _cef_menu_model_t* self, + int index); + + // + // Set the keyboard accelerator for the specified |command_id|. |key_code| can + // be any virtual key or character value. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_accelerator)(struct _cef_menu_model_t* self, + int command_id, int key_code, int shift_pressed, int ctrl_pressed, + int alt_pressed); + + // + // Set the keyboard accelerator at the specified |index|. |key_code| can be + // any virtual key or character value. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_accelerator_at)(struct _cef_menu_model_t* self, + int index, int key_code, int shift_pressed, int ctrl_pressed, + int alt_pressed); + + // + // Remove the keyboard accelerator for the specified |command_id|. Returns + // true (1) on success. + /// + int (CEF_CALLBACK *remove_accelerator)(struct _cef_menu_model_t* self, + int command_id); + + // + // Remove the keyboard accelerator at the specified |index|. Returns true (1) + // on success. + /// + int (CEF_CALLBACK *remove_accelerator_at)(struct _cef_menu_model_t* self, + int index); + + // + // Retrieves the keyboard accelerator for the specified |command_id|. Returns + // true (1) on success. + /// + int (CEF_CALLBACK *get_accelerator)(struct _cef_menu_model_t* self, + int command_id, int* key_code, int* shift_pressed, int* ctrl_pressed, + int* alt_pressed); + + // + // Retrieves the keyboard accelerator for the specified |index|. Returns true + // (1) on success. + /// + int (CEF_CALLBACK *get_accelerator_at)(struct _cef_menu_model_t* self, + int index, int* key_code, int* shift_pressed, int* ctrl_pressed, + int* alt_pressed); +} cef_menu_model_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_MENU_MODEL_CAPI_H_ diff --git a/include/capi/cef_navigation_entry_capi.h b/include/capi/cef_navigation_entry_capi.h new file mode 100644 index 000000000..642f0b928 --- /dev/null +++ b/include/capi/cef_navigation_entry_capi.h @@ -0,0 +1,134 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_NAVIGATION_ENTRY_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_NAVIGATION_ENTRY_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to represent an entry in navigation history. +/// +typedef struct _cef_navigation_entry_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_navigation_entry_t* self); + + /// + // Returns the actual URL of the page. For some pages this may be data: URL or + // similar. Use get_display_url() to return a display-friendly version. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_url)( + struct _cef_navigation_entry_t* self); + + /// + // Returns a display-friendly version of the URL. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_display_url)( + struct _cef_navigation_entry_t* self); + + /// + // Returns the original URL that was entered by the user before any redirects. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_original_url)( + struct _cef_navigation_entry_t* self); + + /// + // Returns the title set by the page. This value may be NULL. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_title)( + struct _cef_navigation_entry_t* self); + + /// + // Returns the transition type which indicates what the user did to move to + // this page from the previous page. + /// + cef_transition_type_t (CEF_CALLBACK *get_transition_type)( + struct _cef_navigation_entry_t* self); + + /// + // Returns true (1) if this navigation includes post data. + /// + int (CEF_CALLBACK *has_post_data)(struct _cef_navigation_entry_t* self); + + /// + // Returns the name of the sub-frame that navigated or an NULL value if the + // main frame navigated. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_frame_name)( + struct _cef_navigation_entry_t* self); + + /// + // Returns the time for the last known successful navigation completion. A + // navigation may be completed more than once if the page is reloaded. May be + // 0 if the navigation has not yet completed. + /// + cef_time_t (CEF_CALLBACK *get_completion_time)( + struct _cef_navigation_entry_t* self); + + /// + // Returns the HTTP status code for the last known successful navigation + // response. May be 0 if the response has not yet been received or if the + // navigation has not yet completed. + /// + int (CEF_CALLBACK *get_http_status_code)( + struct _cef_navigation_entry_t* self); +} cef_navigation_entry_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_NAVIGATION_ENTRY_CAPI_H_ diff --git a/include/capi/cef_origin_whitelist_capi.h b/include/capi/cef_origin_whitelist_capi.h new file mode 100644 index 000000000..6cd123762 --- /dev/null +++ b/include/capi/cef_origin_whitelist_capi.h @@ -0,0 +1,106 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_ORIGIN_WHITELIST_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_ORIGIN_WHITELIST_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Add an entry to the cross-origin access whitelist. +// +// The same-origin policy restricts how scripts hosted from different origins +// (scheme + domain + port) can communicate. By default, scripts can only access +// resources with the same origin. Scripts hosted on the HTTP and HTTPS schemes +// (but no other schemes) can use the "Access-Control-Allow-Origin" header to +// allow cross-origin requests. For example, https://source.example.com can make +// XMLHttpRequest requests on http://target.example.com if the +// http://target.example.com request returns an "Access-Control-Allow-Origin: +// https://source.example.com" response header. +// +// Scripts in separate frames or iframes and hosted from the same protocol and +// domain suffix can execute cross-origin JavaScript if both pages set the +// document.domain value to the same domain suffix. For example, +// scheme://foo.example.com and scheme://bar.example.com can communicate using +// JavaScript if both domains set document.domain="example.com". +// +// This function is used to allow access to origins that would otherwise violate +// the same-origin policy. Scripts hosted underneath the fully qualified +// |source_origin| URL (like http://www.example.com) will be allowed access to +// all resources hosted on the specified |target_protocol| and |target_domain|. +// If |target_domain| is non-NULL and |allow_target_subdomains| if false (0) +// only exact domain matches will be allowed. If |target_domain| contains a top- +// level domain component (like "example.com") and |allow_target_subdomains| is +// true (1) sub-domain matches will be allowed. If |target_domain| is NULL and +// |allow_target_subdomains| if true (1) all domains and IP addresses will be +// allowed. +// +// This function cannot be used to bypass the restrictions on local or display +// isolated schemes. See the comments on CefRegisterCustomScheme for more +// information. +// +// This function may be called on any thread. Returns false (0) if +// |source_origin| is invalid or the whitelist cannot be accessed. +/// +CEF_EXPORT int cef_add_cross_origin_whitelist_entry( + const cef_string_t* source_origin, const cef_string_t* target_protocol, + const cef_string_t* target_domain, int allow_target_subdomains); + +/// +// Remove an entry from the cross-origin access whitelist. Returns false (0) if +// |source_origin| is invalid or the whitelist cannot be accessed. +/// +CEF_EXPORT int cef_remove_cross_origin_whitelist_entry( + const cef_string_t* source_origin, const cef_string_t* target_protocol, + const cef_string_t* target_domain, int allow_target_subdomains); + +/// +// Remove all entries from the cross-origin access whitelist. Returns false (0) +// if the whitelist cannot be accessed. +/// +CEF_EXPORT int cef_clear_cross_origin_whitelist(); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_ORIGIN_WHITELIST_CAPI_H_ diff --git a/include/capi/cef_path_util_capi.h b/include/capi/cef_path_util_capi.h new file mode 100644 index 000000000..4655b792a --- /dev/null +++ b/include/capi/cef_path_util_capi.h @@ -0,0 +1,58 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_PATH_UTIL_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PATH_UTIL_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Retrieve the path associated with the specified |key|. Returns true (1) on +// success. Can be called on any thread in the browser process. +/// +CEF_EXPORT int cef_get_path(cef_path_key_t key, cef_string_t* path); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PATH_UTIL_CAPI_H_ diff --git a/include/capi/cef_print_handler_capi.h b/include/capi/cef_print_handler_capi.h new file mode 100644 index 000000000..f2e29ae51 --- /dev/null +++ b/include/capi/cef_print_handler_capi.h @@ -0,0 +1,134 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_PRINT_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PRINT_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_print_settings_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure for asynchronous continuation of print dialog requests. +/// +typedef struct _cef_print_dialog_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue printing with the specified |settings|. + /// + void (CEF_CALLBACK *cont)(struct _cef_print_dialog_callback_t* self, + struct _cef_print_settings_t* settings); + + /// + // Cancel the printing. + /// + void (CEF_CALLBACK *cancel)(struct _cef_print_dialog_callback_t* self); +} cef_print_dialog_callback_t; + + +/// +// Callback structure for asynchronous continuation of print job requests. +/// +typedef struct _cef_print_job_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Indicate completion of the print job. + /// + void (CEF_CALLBACK *cont)(struct _cef_print_job_callback_t* self); +} cef_print_job_callback_t; + + +/// +// Implement this structure to handle printing on Linux. The functions of this +// structure will be called on the browser process UI thread. +/// +typedef struct _cef_print_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Synchronize |settings| with client state. If |get_defaults| is true (1) + // then populate |settings| with the default print settings. Do not keep a + // reference to |settings| outside of this callback. + /// + void (CEF_CALLBACK *on_print_settings)(struct _cef_print_handler_t* self, + struct _cef_print_settings_t* settings, int get_defaults); + + /// + // Show the print dialog. Execute |callback| once the dialog is dismissed. + // Return true (1) if the dialog will be displayed or false (0) to cancel the + // printing immediately. + /// + int (CEF_CALLBACK *on_print_dialog)(struct _cef_print_handler_t* self, + int has_selection, struct _cef_print_dialog_callback_t* callback); + + /// + // Send the print job to the printer. Execute |callback| once the job is + // completed. Return true (1) if the job will proceed or false (0) to cancel + // the job immediately. + /// + int (CEF_CALLBACK *on_print_job)(struct _cef_print_handler_t* self, + const cef_string_t* document_name, const cef_string_t* pdf_file_path, + struct _cef_print_job_callback_t* callback); + + /// + // Reset client state related to printing. + /// + void (CEF_CALLBACK *on_print_reset)(struct _cef_print_handler_t* self); +} cef_print_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PRINT_HANDLER_CAPI_H_ diff --git a/include/capi/cef_print_settings_capi.h b/include/capi/cef_print_settings_capi.h new file mode 100644 index 000000000..5dfd0ffd9 --- /dev/null +++ b/include/capi/cef_print_settings_capi.h @@ -0,0 +1,207 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_PRINT_SETTINGS_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PRINT_SETTINGS_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure representing print settings. +/// +typedef struct _cef_print_settings_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_print_settings_t* self); + + /// + // Returns true (1) if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_print_settings_t* self); + + /// + // Returns a writable copy of this object. + /// + struct _cef_print_settings_t* (CEF_CALLBACK *copy)( + struct _cef_print_settings_t* self); + + /// + // Set the page orientation. + /// + void (CEF_CALLBACK *set_orientation)(struct _cef_print_settings_t* self, + int landscape); + + /// + // Returns true (1) if the orientation is landscape. + /// + int (CEF_CALLBACK *is_landscape)(struct _cef_print_settings_t* self); + + /// + // Set the printer printable area in device units. Some platforms already + // provide flipped area. Set |landscape_needs_flip| to false (0) on those + // platforms to avoid double flipping. + /// + void (CEF_CALLBACK *set_printer_printable_area)( + struct _cef_print_settings_t* self, + const cef_size_t* physical_size_device_units, + const cef_rect_t* printable_area_device_units, + int landscape_needs_flip); + + /// + // Set the device name. + /// + void (CEF_CALLBACK *set_device_name)(struct _cef_print_settings_t* self, + const cef_string_t* name); + + /// + // Get the device name. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_device_name)( + struct _cef_print_settings_t* self); + + /// + // Set the DPI (dots per inch). + /// + void (CEF_CALLBACK *set_dpi)(struct _cef_print_settings_t* self, int dpi); + + /// + // Get the DPI (dots per inch). + /// + int (CEF_CALLBACK *get_dpi)(struct _cef_print_settings_t* self); + + /// + // Set the page ranges. + /// + void (CEF_CALLBACK *set_page_ranges)(struct _cef_print_settings_t* self, + size_t rangesCount, cef_page_range_t const* ranges); + + /// + // Returns the number of page ranges that currently exist. + /// + size_t (CEF_CALLBACK *get_page_ranges_count)( + struct _cef_print_settings_t* self); + + /// + // Retrieve the page ranges. + /// + void (CEF_CALLBACK *get_page_ranges)(struct _cef_print_settings_t* self, + size_t* rangesCount, cef_page_range_t* ranges); + + /// + // Set whether only the selection will be printed. + /// + void (CEF_CALLBACK *set_selection_only)(struct _cef_print_settings_t* self, + int selection_only); + + /// + // Returns true (1) if only the selection will be printed. + /// + int (CEF_CALLBACK *is_selection_only)(struct _cef_print_settings_t* self); + + /// + // Set whether pages will be collated. + /// + void (CEF_CALLBACK *set_collate)(struct _cef_print_settings_t* self, + int collate); + + /// + // Returns true (1) if pages will be collated. + /// + int (CEF_CALLBACK *will_collate)(struct _cef_print_settings_t* self); + + /// + // Set the color model. + /// + void (CEF_CALLBACK *set_color_model)(struct _cef_print_settings_t* self, + cef_color_model_t model); + + /// + // Get the color model. + /// + cef_color_model_t (CEF_CALLBACK *get_color_model)( + struct _cef_print_settings_t* self); + + /// + // Set the number of copies. + /// + void (CEF_CALLBACK *set_copies)(struct _cef_print_settings_t* self, + int copies); + + /// + // Get the number of copies. + /// + int (CEF_CALLBACK *get_copies)(struct _cef_print_settings_t* self); + + /// + // Set the duplex mode. + /// + void (CEF_CALLBACK *set_duplex_mode)(struct _cef_print_settings_t* self, + cef_duplex_mode_t mode); + + /// + // Get the duplex mode. + /// + cef_duplex_mode_t (CEF_CALLBACK *get_duplex_mode)( + struct _cef_print_settings_t* self); +} cef_print_settings_t; + + +/// +// Create a new cef_print_settings_t object. +/// +CEF_EXPORT cef_print_settings_t* cef_print_settings_create(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PRINT_SETTINGS_CAPI_H_ diff --git a/include/capi/cef_process_message_capi.h b/include/capi/cef_process_message_capi.h new file mode 100644 index 000000000..975450caf --- /dev/null +++ b/include/capi/cef_process_message_capi.h @@ -0,0 +1,102 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_values_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure representing a message. Can be used on any process and thread. +/// +typedef struct _cef_process_message_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_process_message_t* self); + + /// + // Returns true (1) if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_process_message_t* self); + + /// + // Returns a writable copy of this object. + /// + struct _cef_process_message_t* (CEF_CALLBACK *copy)( + struct _cef_process_message_t* self); + + /// + // Returns the message name. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_name)( + struct _cef_process_message_t* self); + + /// + // Returns the list of arguments. + /// + struct _cef_list_value_t* (CEF_CALLBACK *get_argument_list)( + struct _cef_process_message_t* self); +} cef_process_message_t; + + +/// +// Create a new cef_process_message_t object with the specified name. +/// +CEF_EXPORT cef_process_message_t* cef_process_message_create( + const cef_string_t* name); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PROCESS_MESSAGE_CAPI_H_ diff --git a/include/capi/cef_process_util_capi.h b/include/capi/cef_process_util_capi.h new file mode 100644 index 000000000..f5061009e --- /dev/null +++ b/include/capi/cef_process_util_capi.h @@ -0,0 +1,64 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_PROCESS_UTIL_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PROCESS_UTIL_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Launches the process specified via |command_line|. Returns true (1) upon +// success. Must be called on the browser process TID_PROCESS_LAUNCHER thread. +// +// Unix-specific notes: - All file descriptors open in the parent process will +// be closed in the +// child process except for stdin, stdout, and stderr. +// - If the first argument on the command line does not contain a slash, +// PATH will be searched. (See man execvp.) +/// +CEF_EXPORT int cef_launch_process(struct _cef_command_line_t* command_line); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PROCESS_UTIL_CAPI_H_ diff --git a/include/capi/cef_render_handler_capi.h b/include/capi/cef_render_handler_capi.h new file mode 100644 index 000000000..b6ad76438 --- /dev/null +++ b/include/capi/cef_render_handler_capi.h @@ -0,0 +1,170 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_RENDER_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_RENDER_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_drag_data_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to handle events when window rendering is disabled. +// The functions of this structure will be called on the UI thread. +/// +typedef struct _cef_render_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to retrieve the root window rectangle in screen coordinates. Return + // true (1) if the rectangle was provided. + /// + int (CEF_CALLBACK *get_root_screen_rect)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, cef_rect_t* rect); + + /// + // Called to retrieve the view rectangle which is relative to screen + // coordinates. Return true (1) if the rectangle was provided. + /// + int (CEF_CALLBACK *get_view_rect)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, cef_rect_t* rect); + + /// + // Called to retrieve the translation from view coordinates to actual screen + // coordinates. Return true (1) if the screen coordinates were provided. + /// + int (CEF_CALLBACK *get_screen_point)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, int viewX, int viewY, int* screenX, + int* screenY); + + /// + // Called to allow the client to fill in the CefScreenInfo object with + // appropriate values. Return true (1) if the |screen_info| structure has been + // modified. + // + // If the screen info rectangle is left NULL the rectangle from GetViewRect + // will be used. If the rectangle is still NULL or invalid popups may not be + // drawn correctly. + /// + int (CEF_CALLBACK *get_screen_info)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, struct _cef_screen_info_t* screen_info); + + /// + // Called when the browser wants to show or hide the popup widget. The popup + // should be shown if |show| is true (1) and hidden if |show| is false (0). + /// + void (CEF_CALLBACK *on_popup_show)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, int show); + + /// + // Called when the browser wants to move or resize the popup widget. |rect| + // contains the new location and size in view coordinates. + /// + void (CEF_CALLBACK *on_popup_size)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, const cef_rect_t* rect); + + /// + // Called when an element should be painted. Pixel values passed to this + // function are scaled relative to view coordinates based on the value of + // CefScreenInfo.device_scale_factor returned from GetScreenInfo. |type| + // indicates whether the element is the view or the popup widget. |buffer| + // contains the pixel data for the whole image. |dirtyRects| contains the set + // of rectangles in pixel coordinates that need to be repainted. |buffer| will + // be |width|*|height|*4 bytes in size and represents a BGRA image with an + // upper-left origin. + /// + void (CEF_CALLBACK *on_paint)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, cef_paint_element_type_t type, + size_t dirtyRectsCount, cef_rect_t const* dirtyRects, const void* buffer, + int width, int height); + + /// + // Called when the browser's cursor has changed. If |type| is CT_CUSTOM then + // |custom_cursor_info| will be populated with the custom cursor information. + /// + void (CEF_CALLBACK *on_cursor_change)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, cef_cursor_handle_t cursor, + cef_cursor_type_t type, + const struct _cef_cursor_info_t* custom_cursor_info); + + /// + // Called when the user starts dragging content in the web view. Contextual + // information about the dragged content is supplied by |drag_data|. (|x|, + // |y|) is the drag start location in screen coordinates. OS APIs that run a + // system message loop may be used within the StartDragging call. + // + // Return false (0) to abort the drag operation. Don't call any of + // cef_browser_host_t::DragSource*Ended* functions after returning false (0). + // + // Return true (1) to handle the drag operation. Call + // cef_browser_host_t::DragSourceEndedAt and DragSourceSystemDragEnded either + // synchronously or asynchronously to inform the web view that the drag + // operation has ended. + /// + int (CEF_CALLBACK *start_dragging)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, struct _cef_drag_data_t* drag_data, + cef_drag_operations_mask_t allowed_ops, int x, int y); + + /// + // Called when the web view wants to update the mouse cursor during a drag & + // drop operation. |operation| describes the allowed operation (none, move, + // copy, link). + /// + void (CEF_CALLBACK *update_drag_cursor)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, cef_drag_operations_mask_t operation); + + /// + // Called when the scroll offset has changed. + /// + void (CEF_CALLBACK *on_scroll_offset_changed)( + struct _cef_render_handler_t* self, struct _cef_browser_t* browser); +} cef_render_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RENDER_HANDLER_CAPI_H_ diff --git a/include/capi/cef_render_process_handler_capi.h b/include/capi/cef_render_process_handler_capi.h new file mode 100644 index 000000000..35f6c94cb --- /dev/null +++ b/include/capi/cef_render_process_handler_capi.h @@ -0,0 +1,177 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_RENDER_PROCESS_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_RENDER_PROCESS_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_dom_capi.h" +#include "include/capi/cef_frame_capi.h" +#include "include/capi/cef_load_handler_capi.h" +#include "include/capi/cef_process_message_capi.h" +#include "include/capi/cef_v8_capi.h" +#include "include/capi/cef_values_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to implement render process callbacks. The functions of this +// structure will be called on the render process main thread (TID_RENDERER) +// unless otherwise indicated. +/// +typedef struct _cef_render_process_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called after the render process main thread has been created. |extra_info| + // is a read-only value originating from + // cef_browser_process_handler_t::on_render_process_thread_created(). Do not + // keep a reference to |extra_info| outside of this function. + /// + void (CEF_CALLBACK *on_render_thread_created)( + struct _cef_render_process_handler_t* self, + struct _cef_list_value_t* extra_info); + + /// + // Called after WebKit has been initialized. + /// + void (CEF_CALLBACK *on_web_kit_initialized)( + struct _cef_render_process_handler_t* self); + + /// + // Called after a browser has been created. When browsing cross-origin a new + // browser will be created before the old browser with the same identifier is + // destroyed. + /// + void (CEF_CALLBACK *on_browser_created)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser); + + /// + // Called before a browser is destroyed. + /// + void (CEF_CALLBACK *on_browser_destroyed)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser); + + /// + // Return the handler for browser load status events. + /// + struct _cef_load_handler_t* (CEF_CALLBACK *get_load_handler)( + struct _cef_render_process_handler_t* self); + + /// + // Called before browser navigation. Return true (1) to cancel the navigation + // or false (0) to allow the navigation to proceed. The |request| object + // cannot be modified in this callback. + /// + int (CEF_CALLBACK *on_before_navigation)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + struct _cef_request_t* request, cef_navigation_type_t navigation_type, + int is_redirect); + + /// + // Called immediately after the V8 context for a frame has been created. To + // retrieve the JavaScript 'window' object use the + // cef_v8context_t::get_global() function. V8 handles can only be accessed + // from the thread on which they are created. A task runner for posting tasks + // on the associated thread can be retrieved via the + // cef_v8context_t::get_task_runner() function. + /// + void (CEF_CALLBACK *on_context_created)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + struct _cef_v8context_t* context); + + /// + // Called immediately before the V8 context for a frame is released. No + // references to the context should be kept after this function is called. + /// + void (CEF_CALLBACK *on_context_released)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + struct _cef_v8context_t* context); + + /// + // Called for global uncaught exceptions in a frame. Execution of this + // callback is disabled by default. To enable set + // CefSettings.uncaught_exception_stack_size > 0. + /// + void (CEF_CALLBACK *on_uncaught_exception)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + struct _cef_v8context_t* context, struct _cef_v8exception_t* exception, + struct _cef_v8stack_trace_t* stackTrace); + + /// + // Called when a new node in the the browser gets focus. The |node| value may + // be NULL if no specific node has gained focus. The node object passed to + // this function represents a snapshot of the DOM at the time this function is + // executed. DOM objects are only valid for the scope of this function. Do not + // keep references to or attempt to access any DOM objects outside the scope + // of this function. + /// + void (CEF_CALLBACK *on_focused_node_changed)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + struct _cef_domnode_t* node); + + /// + // Called when a new message is received from a different process. Return true + // (1) if the message was handled or false (0) otherwise. Do not keep a + // reference to or attempt to access the message outside of this callback. + /// + int (CEF_CALLBACK *on_process_message_received)( + struct _cef_render_process_handler_t* self, + struct _cef_browser_t* browser, cef_process_id_t source_process, + struct _cef_process_message_t* message); +} cef_render_process_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RENDER_PROCESS_HANDLER_CAPI_H_ diff --git a/include/capi/cef_request_capi.h b/include/capi/cef_request_capi.h new file mode 100644 index 000000000..0479e5279 --- /dev/null +++ b/include/capi/cef_request_capi.h @@ -0,0 +1,293 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_post_data_element_t; +struct _cef_post_data_t; + +/// +// Structure used to represent a web request. The functions of this structure +// may be called on any thread. +/// +typedef struct _cef_request_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is read-only. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_request_t* self); + + /// + // Get the fully qualified URL. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_url)(struct _cef_request_t* self); + + /// + // Set the fully qualified URL. + /// + void (CEF_CALLBACK *set_url)(struct _cef_request_t* self, + const cef_string_t* url); + + /// + // Get the request function type. The value will default to POST if post data + // is provided and GET otherwise. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_method)(struct _cef_request_t* self); + + /// + // Set the request function type. + /// + void (CEF_CALLBACK *set_method)(struct _cef_request_t* self, + const cef_string_t* method); + + /// + // Get the post data. + /// + struct _cef_post_data_t* (CEF_CALLBACK *get_post_data)( + struct _cef_request_t* self); + + /// + // Set the post data. + /// + void (CEF_CALLBACK *set_post_data)(struct _cef_request_t* self, + struct _cef_post_data_t* postData); + + /// + // Get the header values. + /// + void (CEF_CALLBACK *get_header_map)(struct _cef_request_t* self, + cef_string_multimap_t headerMap); + + /// + // Set the header values. + /// + void (CEF_CALLBACK *set_header_map)(struct _cef_request_t* self, + cef_string_multimap_t headerMap); + + /// + // Set all values at one time. + /// + void (CEF_CALLBACK *set)(struct _cef_request_t* self, const cef_string_t* url, + const cef_string_t* method, struct _cef_post_data_t* postData, + cef_string_multimap_t headerMap); + + /// + // Get the flags used in combination with cef_urlrequest_t. See + // cef_urlrequest_flags_t for supported values. + /// + int (CEF_CALLBACK *get_flags)(struct _cef_request_t* self); + + /// + // Set the flags used in combination with cef_urlrequest_t. See + // cef_urlrequest_flags_t for supported values. + /// + void (CEF_CALLBACK *set_flags)(struct _cef_request_t* self, int flags); + + /// + // Set the URL to the first party for cookies used in combination with + // cef_urlrequest_t. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_first_party_for_cookies)( + struct _cef_request_t* self); + + /// + // Get the URL to the first party for cookies used in combination with + // cef_urlrequest_t. + /// + void (CEF_CALLBACK *set_first_party_for_cookies)(struct _cef_request_t* self, + const cef_string_t* url); + + /// + // Get the resource type for this request. Only available in the browser + // process. + /// + cef_resource_type_t (CEF_CALLBACK *get_resource_type)( + struct _cef_request_t* self); + + /// + // Get the transition type for this request. Only available in the browser + // process and only applies to requests that represent a main frame or sub- + // frame navigation. + /// + cef_transition_type_t (CEF_CALLBACK *get_transition_type)( + struct _cef_request_t* self); +} cef_request_t; + + +/// +// Create a new cef_request_t object. +/// +CEF_EXPORT cef_request_t* cef_request_create(); + + +/// +// Structure used to represent post data for a web request. The functions of +// this structure may be called on any thread. +/// +typedef struct _cef_post_data_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is read-only. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_post_data_t* self); + + /// + // Returns the number of existing post data elements. + /// + size_t (CEF_CALLBACK *get_element_count)(struct _cef_post_data_t* self); + + /// + // Retrieve the post data elements. + /// + void (CEF_CALLBACK *get_elements)(struct _cef_post_data_t* self, + size_t* elementsCount, struct _cef_post_data_element_t** elements); + + /// + // Remove the specified post data element. Returns true (1) if the removal + // succeeds. + /// + int (CEF_CALLBACK *remove_element)(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element); + + /// + // Add the specified post data element. Returns true (1) if the add succeeds. + /// + int (CEF_CALLBACK *add_element)(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element); + + /// + // Remove all existing post data elements. + /// + void (CEF_CALLBACK *remove_elements)(struct _cef_post_data_t* self); +} cef_post_data_t; + + +/// +// Create a new cef_post_data_t object. +/// +CEF_EXPORT cef_post_data_t* cef_post_data_create(); + + +/// +// Structure used to represent a single element in the request post data. The +// functions of this structure may be called on any thread. +/// +typedef struct _cef_post_data_element_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is read-only. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_post_data_element_t* self); + + /// + // Remove all contents from the post data element. + /// + void (CEF_CALLBACK *set_to_empty)(struct _cef_post_data_element_t* self); + + /// + // The post data element will represent a file. + /// + void (CEF_CALLBACK *set_to_file)(struct _cef_post_data_element_t* self, + const cef_string_t* fileName); + + /// + // The post data element will represent bytes. The bytes passed in will be + // copied. + /// + void (CEF_CALLBACK *set_to_bytes)(struct _cef_post_data_element_t* self, + size_t size, const void* bytes); + + /// + // Return the type of this post data element. + /// + cef_postdataelement_type_t (CEF_CALLBACK *get_type)( + struct _cef_post_data_element_t* self); + + /// + // Return the file name. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_file)( + struct _cef_post_data_element_t* self); + + /// + // Return the number of bytes. + /// + size_t (CEF_CALLBACK *get_bytes_count)(struct _cef_post_data_element_t* self); + + /// + // Read up to |size| bytes into |bytes| and return the number of bytes + // actually read. + /// + size_t (CEF_CALLBACK *get_bytes)(struct _cef_post_data_element_t* self, + size_t size, void* bytes); +} cef_post_data_element_t; + + +/// +// Create a new cef_post_data_element_t object. +/// +CEF_EXPORT cef_post_data_element_t* cef_post_data_element_create(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_CAPI_H_ diff --git a/include/capi/cef_request_context_capi.h b/include/capi/cef_request_context_capi.h new file mode 100644 index 000000000..65e9dfe8a --- /dev/null +++ b/include/capi/cef_request_context_capi.h @@ -0,0 +1,105 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_REQUEST_CONTEXT_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_REQUEST_CONTEXT_CAPI_H_ +#pragma once + +#include "include/capi/cef_request_context_handler_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// A request context provides request handling for a set of related browser +// objects. A request context is specified when creating a new browser object +// via the cef_browser_host_t static factory functions. Browser objects with +// different request contexts will never be hosted in the same render process. +// Browser objects with the same request context may or may not be hosted in the +// same render process depending on the process model. Browser objects created +// indirectly via the JavaScript window.open function or targeted links will +// share the same render process and the same request context as the source +// browser. When running in single-process mode there is only a single render +// process (the main process) and so all browsers created in single-process mode +// will share the same request context. This will be the first request context +// passed into a cef_browser_host_t static factory function and all other +// request context objects will be ignored. +/// +typedef struct _cef_request_context_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is pointing to the same context as |that| + // object. + /// + int (CEF_CALLBACK *is_same)(struct _cef_request_context_t* self, + struct _cef_request_context_t* other); + + /// + // Returns true (1) if this object is the global context. + /// + int (CEF_CALLBACK *is_global)(struct _cef_request_context_t* self); + + /// + // Returns the handler for this context if any. + /// + struct _cef_request_context_handler_t* (CEF_CALLBACK *get_handler)( + struct _cef_request_context_t* self); +} cef_request_context_t; + + +/// +// Returns the global context object. +/// +CEF_EXPORT cef_request_context_t* cef_request_context_get_global_context(); + +/// +// Creates a new context object with the specified handler. +/// +CEF_EXPORT cef_request_context_t* cef_request_context_create_context( + struct _cef_request_context_handler_t* handler); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_CONTEXT_CAPI_H_ diff --git a/include/capi/cef_request_context_handler_capi.h b/include/capi/cef_request_context_handler_capi.h new file mode 100644 index 000000000..4c6934832 --- /dev/null +++ b/include/capi/cef_request_context_handler_capi.h @@ -0,0 +1,71 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_REQUEST_CONTEXT_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_REQUEST_CONTEXT_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_cookie_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to provide handler implementations. +/// +typedef struct _cef_request_context_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called on the IO thread to retrieve the cookie manager. The global cookie + // manager will be used if this function returns NULL. + /// + struct _cef_cookie_manager_t* (CEF_CALLBACK *get_cookie_manager)( + struct _cef_request_context_handler_t* self); +} cef_request_context_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_CONTEXT_HANDLER_CAPI_H_ diff --git a/include/capi/cef_request_handler_capi.h b/include/capi/cef_request_handler_capi.h new file mode 100644 index 000000000..cd0ed9369 --- /dev/null +++ b/include/capi/cef_request_handler_capi.h @@ -0,0 +1,226 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_REQUEST_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_REQUEST_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_auth_callback_capi.h" +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_frame_capi.h" +#include "include/capi/cef_request_capi.h" +#include "include/capi/cef_resource_handler_capi.h" +#include "include/capi/cef_response_capi.h" +#include "include/capi/cef_web_plugin_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Callback structure used for asynchronous continuation of quota requests. +/// +typedef struct _cef_quota_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue the quota request. If |allow| is true (1) the request will be + // allowed. Otherwise, the request will be denied. + /// + void (CEF_CALLBACK *cont)(struct _cef_quota_callback_t* self, int allow); + + /// + // Cancel the quota request. + /// + void (CEF_CALLBACK *cancel)(struct _cef_quota_callback_t* self); +} cef_quota_callback_t; + + +/// +// Callback structure used for asynchronous continuation of url requests when +// invalid SSL certificates are encountered. +/// +typedef struct _cef_allow_certificate_error_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Continue the url request. If |allow| is true (1) the request will be + // continued. Otherwise, the request will be canceled. + /// + void (CEF_CALLBACK *cont)( + struct _cef_allow_certificate_error_callback_t* self, int allow); +} cef_allow_certificate_error_callback_t; + + +/// +// Implement this structure to handle events related to browser requests. The +// functions of this structure will be called on the thread indicated. +/// +typedef struct _cef_request_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called on the UI thread before browser navigation. Return true (1) to + // cancel the navigation or false (0) to allow the navigation to proceed. The + // |request| object cannot be modified in this callback. + // cef_load_handler_t::OnLoadingStateChange will be called twice in all cases. + // If the navigation is allowed cef_load_handler_t::OnLoadStart and + // cef_load_handler_t::OnLoadEnd will be called. If the navigation is canceled + // cef_load_handler_t::OnLoadError will be called with an |errorCode| value of + // ERR_ABORTED. + /// + int (CEF_CALLBACK *on_before_browse)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + struct _cef_request_t* request, int is_redirect); + + /// + // Called on the IO thread before a resource request is loaded. The |request| + // object may be modified. To cancel the request return true (1) otherwise + // return false (0). + /// + int (CEF_CALLBACK *on_before_resource_load)( + struct _cef_request_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_request_t* request); + + /// + // Called on the IO thread before a resource is loaded. To allow the resource + // to load normally return NULL. To specify a handler for the resource return + // a cef_resource_handler_t object. The |request| object should not be + // modified in this callback. + /// + struct _cef_resource_handler_t* (CEF_CALLBACK *get_resource_handler)( + struct _cef_request_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_request_t* request); + + /// + // Called on the IO thread when a resource load is redirected. The |old_url| + // parameter will contain the old URL. The |new_url| parameter will contain + // the new URL and can be changed if desired. + /// + void (CEF_CALLBACK *on_resource_redirect)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* old_url, cef_string_t* new_url); + + /// + // Called on the IO thread when the browser needs credentials from the user. + // |isProxy| indicates whether the host is a proxy server. |host| contains the + // hostname and |port| contains the port number. Return true (1) to continue + // the request and call cef_auth_callback_t::cont() when the authentication + // information is available. Return false (0) to cancel the request. + /// + int (CEF_CALLBACK *get_auth_credentials)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, int isProxy, + const cef_string_t* host, int port, const cef_string_t* realm, + const cef_string_t* scheme, struct _cef_auth_callback_t* callback); + + /// + // Called on the IO thread when JavaScript requests a specific storage quota + // size via the webkitStorageInfo.requestQuota function. |origin_url| is the + // origin of the page making the request. |new_size| is the requested quota + // size in bytes. Return true (1) and call cef_quota_callback_t::cont() either + // in this function or at a later time to grant or deny the request. Return + // false (0) to cancel the request. + /// + int (CEF_CALLBACK *on_quota_request)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* origin_url, + int64 new_size, struct _cef_quota_callback_t* callback); + + /// + // Called on the UI thread to handle requests for URLs with an unknown + // protocol component. Set |allow_os_execution| to true (1) to attempt + // execution via the registered OS protocol handler, if any. SECURITY WARNING: + // YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED ON SCHEME, HOST OR + // OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION. + /// + void (CEF_CALLBACK *on_protocol_execution)( + struct _cef_request_handler_t* self, struct _cef_browser_t* browser, + const cef_string_t* url, int* allow_os_execution); + + /// + // Called on the UI thread to handle requests for URLs with an invalid SSL + // certificate. Return true (1) and call + // cef_allow_certificate_error_callback_t:: cont() either in this function or + // at a later time to continue or cancel the request. Return false (0) to + // cancel the request immediately. If |callback| is NULL the error cannot be + // recovered from and the request will be canceled automatically. If + // CefSettings.ignore_certificate_errors is set all invalid certificates will + // be accepted without calling this function. + /// + int (CEF_CALLBACK *on_certificate_error)(struct _cef_request_handler_t* self, + cef_errorcode_t cert_error, const cef_string_t* request_url, + struct _cef_allow_certificate_error_callback_t* callback); + + /// + // Called on the browser process IO thread before a plugin is loaded. Return + // true (1) to block loading of the plugin. + /// + int (CEF_CALLBACK *on_before_plugin_load)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* url, + const cef_string_t* policy_url, struct _cef_web_plugin_info_t* info); + + /// + // Called on the browser process UI thread when a plugin has crashed. + // |plugin_path| is the path of the plugin that crashed. + /// + void (CEF_CALLBACK *on_plugin_crashed)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* plugin_path); + + /// + // Called on the browser process UI thread when the render process terminates + // unexpectedly. |status| indicates how the process terminated. + /// + void (CEF_CALLBACK *on_render_process_terminated)( + struct _cef_request_handler_t* self, struct _cef_browser_t* browser, + cef_termination_status_t status); +} cef_request_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_HANDLER_CAPI_H_ diff --git a/include/capi/cef_resource_bundle_handler_capi.h b/include/capi/cef_resource_bundle_handler_capi.h new file mode 100644 index 000000000..b84adc47a --- /dev/null +++ b/include/capi/cef_resource_bundle_handler_capi.h @@ -0,0 +1,86 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_RESOURCE_BUNDLE_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_RESOURCE_BUNDLE_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to implement a custom resource bundle structure. The functions +// of this structure may be called on multiple threads. +/// +typedef struct _cef_resource_bundle_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to retrieve a localized translation for the string specified by + // |message_id|. To provide the translation set |string| to the translation + // string and return true (1). To use the default translation return false + // (0). Supported message IDs are listed in cef_pack_strings.h. + /// + int (CEF_CALLBACK *get_localized_string)( + struct _cef_resource_bundle_handler_t* self, int message_id, + cef_string_t* string); + + /// + // Called to retrieve data for the resource specified by |resource_id|. To + // provide the resource data set |data| and |data_size| to the data pointer + // and size respectively and return true (1). To use the default resource data + // return false (0). The resource data will not be copied and must remain + // resident in memory. Supported resource IDs are listed in + // cef_pack_resources.h. + /// + int (CEF_CALLBACK *get_data_resource)( + struct _cef_resource_bundle_handler_t* self, int resource_id, void** data, + size_t* data_size); +} cef_resource_bundle_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RESOURCE_BUNDLE_HANDLER_CAPI_H_ diff --git a/include/capi/cef_resource_handler_capi.h b/include/capi/cef_resource_handler_capi.h new file mode 100644 index 000000000..cf3bae9f4 --- /dev/null +++ b/include/capi/cef_resource_handler_capi.h @@ -0,0 +1,124 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_RESOURCE_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_RESOURCE_HANDLER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_callback_capi.h" +#include "include/capi/cef_cookie_capi.h" +#include "include/capi/cef_request_capi.h" +#include "include/capi/cef_response_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to implement a custom request handler structure. The functions +// of this structure will always be called on the IO thread. +/// +typedef struct _cef_resource_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Begin processing the request. To handle the request return true (1) and + // call cef_callback_t::cont() once the response header information is + // available (cef_callback_t::cont() can also be called from inside this + // function if header information is available immediately). To cancel the + // request return false (0). + /// + int (CEF_CALLBACK *process_request)(struct _cef_resource_handler_t* self, + struct _cef_request_t* request, struct _cef_callback_t* callback); + + /// + // Retrieve response header information. If the response length is not known + // set |response_length| to -1 and read_response() will be called until it + // returns false (0). If the response length is known set |response_length| to + // a positive value and read_response() will be called until it returns false + // (0) or the specified number of bytes have been read. Use the |response| + // object to set the mime type, http status code and other optional header + // values. To redirect the request to a new URL set |redirectUrl| to the new + // URL. + /// + void (CEF_CALLBACK *get_response_headers)( + struct _cef_resource_handler_t* self, struct _cef_response_t* response, + int64* response_length, cef_string_t* redirectUrl); + + /// + // Read response data. If data is available immediately copy up to + // |bytes_to_read| bytes into |data_out|, set |bytes_read| to the number of + // bytes copied, and return true (1). To read the data at a later time set + // |bytes_read| to 0, return true (1) and call cef_callback_t::cont() when the + // data is available. To indicate response completion return false (0). + /// + int (CEF_CALLBACK *read_response)(struct _cef_resource_handler_t* self, + void* data_out, int bytes_to_read, int* bytes_read, + struct _cef_callback_t* callback); + + /// + // Return true (1) if the specified cookie can be sent with the request or + // false (0) otherwise. If false (0) is returned for any cookie then no + // cookies will be sent with the request. + /// + int (CEF_CALLBACK *can_get_cookie)(struct _cef_resource_handler_t* self, + const struct _cef_cookie_t* cookie); + + /// + // Return true (1) if the specified cookie returned with the response can be + // set or false (0) otherwise. + /// + int (CEF_CALLBACK *can_set_cookie)(struct _cef_resource_handler_t* self, + const struct _cef_cookie_t* cookie); + + /// + // Request processing has been canceled. + /// + void (CEF_CALLBACK *cancel)(struct _cef_resource_handler_t* self); +} cef_resource_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RESOURCE_HANDLER_CAPI_H_ diff --git a/include/capi/cef_response_capi.h b/include/capi/cef_response_capi.h new file mode 100644 index 000000000..d48a2d18e --- /dev/null +++ b/include/capi/cef_response_capi.h @@ -0,0 +1,130 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_RESPONSE_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_RESPONSE_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure used to represent a web response. The functions of this structure +// may be called on any thread. +/// +typedef struct _cef_response_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is read-only. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_response_t* self); + + /// + // Get the response status code. + /// + int (CEF_CALLBACK *get_status)(struct _cef_response_t* self); + + /// + // Set the response status code. + /// + void (CEF_CALLBACK *set_status)(struct _cef_response_t* self, int status); + + /// + // Get the response status text. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_status_text)( + struct _cef_response_t* self); + + /// + // Set the response status text. + /// + void (CEF_CALLBACK *set_status_text)(struct _cef_response_t* self, + const cef_string_t* statusText); + + /// + // Get the response mime type. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_mime_type)( + struct _cef_response_t* self); + + /// + // Set the response mime type. + /// + void (CEF_CALLBACK *set_mime_type)(struct _cef_response_t* self, + const cef_string_t* mimeType); + + /// + // Get the value for the specified response header field. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_header)(struct _cef_response_t* self, + const cef_string_t* name); + + /// + // Get all response header fields. + /// + void (CEF_CALLBACK *get_header_map)(struct _cef_response_t* self, + cef_string_multimap_t headerMap); + + /// + // Set all response header fields. + /// + void (CEF_CALLBACK *set_header_map)(struct _cef_response_t* self, + cef_string_multimap_t headerMap); +} cef_response_t; + + +/// +// Create a new cef_response_t object. +/// +CEF_EXPORT cef_response_t* cef_response_create(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RESPONSE_CAPI_H_ diff --git a/include/capi/cef_scheme_capi.h b/include/capi/cef_scheme_capi.h new file mode 100644 index 000000000..e046aaaba --- /dev/null +++ b/include/capi/cef_scheme_capi.h @@ -0,0 +1,168 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_SCHEME_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_SCHEME_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_frame_capi.h" +#include "include/capi/cef_request_capi.h" +#include "include/capi/cef_resource_handler_capi.h" +#include "include/capi/cef_response_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_scheme_handler_factory_t; + +/// +// Structure that manages custom scheme registrations. +/// +typedef struct _cef_scheme_registrar_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Register a custom scheme. This function should not be called for the built- + // in HTTP, HTTPS, FILE, FTP, ABOUT and DATA schemes. + // + // If |is_standard| is true (1) the scheme will be treated as a standard + // scheme. Standard schemes are subject to URL canonicalization and parsing + // rules as defined in the Common Internet Scheme Syntax RFC 1738 Section 3.1 + // available at http://www.ietf.org/rfc/rfc1738.txt + // + // In particular, the syntax for standard scheme URLs must be of the form: + //
+  //  [scheme]://[username]:[password]@[host]:[port]/[url-path]
+  // 
Standard scheme URLs must have a host component that is a fully + // qualified domain name as defined in Section 3.5 of RFC 1034 [13] and + // Section 2.1 of RFC 1123. These URLs will be canonicalized to + // "scheme://host/path" in the simplest case and + // "scheme://username:password@host:port/path" in the most explicit case. For + // example, "scheme:host/path" and "scheme:///host/path" will both be + // canonicalized to "scheme://host/path". The origin of a standard scheme URL + // is the combination of scheme, host and port (i.e., "scheme://host:port" in + // the most explicit case). + // + // For non-standard scheme URLs only the "scheme:" component is parsed and + // canonicalized. The remainder of the URL will be passed to the handler as- + // is. For example, "scheme:///some%20text" will remain the same. Non-standard + // scheme URLs cannot be used as a target for form submission. + // + // If |is_local| is true (1) the scheme will be treated as local (i.e., with + // the same security rules as those applied to "file" URLs). Normal pages + // cannot link to or access local URLs. Also, by default, local URLs can only + // perform XMLHttpRequest calls to the same URL (origin + path) that + // originated the request. To allow XMLHttpRequest calls from a local URL to + // other URLs with the same origin set the + // CefSettings.file_access_from_file_urls_allowed value to true (1). To allow + // XMLHttpRequest calls from a local URL to all origins set the + // CefSettings.universal_access_from_file_urls_allowed value to true (1). + // + // If |is_display_isolated| is true (1) the scheme will be treated as display- + // isolated. This means that pages cannot display these URLs unless they are + // from the same scheme. For example, pages in another origin cannot create + // iframes or hyperlinks to URLs with this scheme. + // + // This function may be called on any thread. It should only be called once + // per unique |scheme_name| value. If |scheme_name| is already registered or + // if an error occurs this function will return false (0). + /// + int (CEF_CALLBACK *add_custom_scheme)(struct _cef_scheme_registrar_t* self, + const cef_string_t* scheme_name, int is_standard, int is_local, + int is_display_isolated); +} cef_scheme_registrar_t; + + +/// +// Structure that creates cef_resource_handler_t instances for handling scheme +// requests. The functions of this structure will always be called on the IO +// thread. +/// +typedef struct _cef_scheme_handler_factory_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Return a new resource handler instance to handle the request or an NULL + // reference to allow default handling of the request. |browser| and |frame| + // will be the browser window and frame respectively that originated the + // request or NULL if the request did not originate from a browser window (for + // example, if the request came from cef_urlrequest_t). The |request| object + // passed to this function will not contain cookie data. + /// + struct _cef_resource_handler_t* (CEF_CALLBACK *create)( + struct _cef_scheme_handler_factory_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* scheme_name, struct _cef_request_t* request); +} cef_scheme_handler_factory_t; + + +/// +// Register a scheme handler factory for the specified |scheme_name| and +// optional |domain_name|. An NULL |domain_name| value for a standard scheme +// will cause the factory to match all domain names. The |domain_name| value +// will be ignored for non-standard schemes. If |scheme_name| is a built-in +// scheme and no handler is returned by |factory| then the built-in scheme +// handler factory will be called. If |scheme_name| is a custom scheme then also +// implement the cef_app_t::on_register_custom_schemes() function in all +// processes. This function may be called multiple times to change or remove the +// factory that matches the specified |scheme_name| and optional |domain_name|. +// Returns false (0) if an error occurs. This function may be called on any +// thread in the browser process. +/// +CEF_EXPORT int cef_register_scheme_handler_factory( + const cef_string_t* scheme_name, const cef_string_t* domain_name, + cef_scheme_handler_factory_t* factory); + +/// +// Clear all registered scheme handler factories. Returns false (0) on error. +// This function may be called on any thread in the browser process. +/// +CEF_EXPORT int cef_clear_scheme_handler_factories(); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_SCHEME_CAPI_H_ diff --git a/include/capi/cef_stream_capi.h b/include/capi/cef_stream_capi.h new file mode 100644 index 000000000..260dae8c3 --- /dev/null +++ b/include/capi/cef_stream_capi.h @@ -0,0 +1,252 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_STREAM_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_STREAM_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure the client can implement to provide a custom stream reader. The +// functions of this structure may be called on any thread. +/// +typedef struct _cef_read_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Read raw binary data. + /// + size_t (CEF_CALLBACK *read)(struct _cef_read_handler_t* self, void* ptr, + size_t size, size_t n); + + /// + // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, + // SEEK_END or SEEK_SET. Return zero on success and non-zero on failure. + /// + int (CEF_CALLBACK *seek)(struct _cef_read_handler_t* self, int64 offset, + int whence); + + /// + // Return the current offset position. + /// + int64 (CEF_CALLBACK *tell)(struct _cef_read_handler_t* self); + + /// + // Return non-zero if at end of file. + /// + int (CEF_CALLBACK *eof)(struct _cef_read_handler_t* self); + + /// + // Return true (1) if this handler performs work like accessing the file + // system which may block. Used as a hint for determining the thread to access + // the handler from. + /// + int (CEF_CALLBACK *may_block)(struct _cef_read_handler_t* self); +} cef_read_handler_t; + + +/// +// Structure used to read data from a stream. The functions of this structure +// may be called on any thread. +/// +typedef struct _cef_stream_reader_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Read raw binary data. + /// + size_t (CEF_CALLBACK *read)(struct _cef_stream_reader_t* self, void* ptr, + size_t size, size_t n); + + /// + // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, + // SEEK_END or SEEK_SET. Returns zero on success and non-zero on failure. + /// + int (CEF_CALLBACK *seek)(struct _cef_stream_reader_t* self, int64 offset, + int whence); + + /// + // Return the current offset position. + /// + int64 (CEF_CALLBACK *tell)(struct _cef_stream_reader_t* self); + + /// + // Return non-zero if at end of file. + /// + int (CEF_CALLBACK *eof)(struct _cef_stream_reader_t* self); + + /// + // Returns true (1) if this reader performs work like accessing the file + // system which may block. Used as a hint for determining the thread to access + // the reader from. + /// + int (CEF_CALLBACK *may_block)(struct _cef_stream_reader_t* self); +} cef_stream_reader_t; + + +/// +// Create a new cef_stream_reader_t object from a file. +/// +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_file( + const cef_string_t* fileName); + +/// +// Create a new cef_stream_reader_t object from data. +/// +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_data(void* data, + size_t size); + +/// +// Create a new cef_stream_reader_t object from a custom handler. +/// +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_handler( + cef_read_handler_t* handler); + + +/// +// Structure the client can implement to provide a custom stream writer. The +// functions of this structure may be called on any thread. +/// +typedef struct _cef_write_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Write raw binary data. + /// + size_t (CEF_CALLBACK *write)(struct _cef_write_handler_t* self, + const void* ptr, size_t size, size_t n); + + /// + // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, + // SEEK_END or SEEK_SET. Return zero on success and non-zero on failure. + /// + int (CEF_CALLBACK *seek)(struct _cef_write_handler_t* self, int64 offset, + int whence); + + /// + // Return the current offset position. + /// + int64 (CEF_CALLBACK *tell)(struct _cef_write_handler_t* self); + + /// + // Flush the stream. + /// + int (CEF_CALLBACK *flush)(struct _cef_write_handler_t* self); + + /// + // Return true (1) if this handler performs work like accessing the file + // system which may block. Used as a hint for determining the thread to access + // the handler from. + /// + int (CEF_CALLBACK *may_block)(struct _cef_write_handler_t* self); +} cef_write_handler_t; + + +/// +// Structure used to write data to a stream. The functions of this structure may +// be called on any thread. +/// +typedef struct _cef_stream_writer_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Write raw binary data. + /// + size_t (CEF_CALLBACK *write)(struct _cef_stream_writer_t* self, + const void* ptr, size_t size, size_t n); + + /// + // Seek to the specified offset position. |whence| may be any one of SEEK_CUR, + // SEEK_END or SEEK_SET. Returns zero on success and non-zero on failure. + /// + int (CEF_CALLBACK *seek)(struct _cef_stream_writer_t* self, int64 offset, + int whence); + + /// + // Return the current offset position. + /// + int64 (CEF_CALLBACK *tell)(struct _cef_stream_writer_t* self); + + /// + // Flush the stream. + /// + int (CEF_CALLBACK *flush)(struct _cef_stream_writer_t* self); + + /// + // Returns true (1) if this writer performs work like accessing the file + // system which may block. Used as a hint for determining the thread to access + // the writer from. + /// + int (CEF_CALLBACK *may_block)(struct _cef_stream_writer_t* self); +} cef_stream_writer_t; + + +/// +// Create a new cef_stream_writer_t object for a file. +/// +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_file( + const cef_string_t* fileName); + +/// +// Create a new cef_stream_writer_t object for a custom handler. +/// +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_handler( + cef_write_handler_t* handler); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_STREAM_CAPI_H_ diff --git a/include/capi/cef_string_visitor_capi.h b/include/capi/cef_string_visitor_capi.h new file mode 100644 index 000000000..8fde238b5 --- /dev/null +++ b/include/capi/cef_string_visitor_capi.h @@ -0,0 +1,69 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_STRING_VISITOR_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_STRING_VISITOR_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to receive string values asynchronously. +/// +typedef struct _cef_string_visitor_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be executed. + /// + void (CEF_CALLBACK *visit)(struct _cef_string_visitor_t* self, + const cef_string_t* string); +} cef_string_visitor_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_STRING_VISITOR_CAPI_H_ diff --git a/include/capi/cef_task_capi.h b/include/capi/cef_task_capi.h new file mode 100644 index 000000000..ea0ff7f08 --- /dev/null +++ b/include/capi/cef_task_capi.h @@ -0,0 +1,159 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_TASK_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_TASK_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure for asynchronous task execution. If the task is +// posted successfully and if the associated message loop is still running then +// the execute() function will be called on the target thread. If the task fails +// to post then the task object may be destroyed on the source thread instead of +// the target thread. For this reason be cautious when performing work in the +// task object destructor. +/// +typedef struct _cef_task_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be executed on the target thread. + /// + void (CEF_CALLBACK *execute)(struct _cef_task_t* self); +} cef_task_t; + + +/// +// Structure that asynchronously executes tasks on the associated thread. It is +// safe to call the functions of this structure on any thread. +// +// CEF maintains multiple internal threads that are used for handling different +// types of tasks in different processes. The cef_thread_id_t definitions in +// cef_types.h list the common CEF threads. Task runners are also available for +// other CEF threads as appropriate (for example, V8 WebWorker threads). +/// +typedef struct _cef_task_runner_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is pointing to the same task runner as + // |that| object. + /// + int (CEF_CALLBACK *is_same)(struct _cef_task_runner_t* self, + struct _cef_task_runner_t* that); + + /// + // Returns true (1) if this task runner belongs to the current thread. + /// + int (CEF_CALLBACK *belongs_to_current_thread)( + struct _cef_task_runner_t* self); + + /// + // Returns true (1) if this task runner is for the specified CEF thread. + /// + int (CEF_CALLBACK *belongs_to_thread)(struct _cef_task_runner_t* self, + cef_thread_id_t threadId); + + /// + // Post a task for execution on the thread associated with this task runner. + // Execution will occur asynchronously. + /// + int (CEF_CALLBACK *post_task)(struct _cef_task_runner_t* self, + struct _cef_task_t* task); + + /// + // Post a task for delayed execution on the thread associated with this task + // runner. Execution will occur asynchronously. Delayed tasks are not + // supported on V8 WebWorker threads and will be executed without the + // specified delay. + /// + int (CEF_CALLBACK *post_delayed_task)(struct _cef_task_runner_t* self, + struct _cef_task_t* task, int64 delay_ms); +} cef_task_runner_t; + + +/// +// Returns the task runner for the current thread. Only CEF threads will have +// task runners. An NULL reference will be returned if this function is called +// on an invalid thread. +/// +CEF_EXPORT cef_task_runner_t* cef_task_runner_get_for_current_thread(); + +/// +// Returns the task runner for the specified CEF thread. +/// +CEF_EXPORT cef_task_runner_t* cef_task_runner_get_for_thread( + cef_thread_id_t threadId); + + +/// +// Returns true (1) if called on the specified thread. Equivalent to using +// cef_task_tRunner::GetForThread(threadId)->belongs_to_current_thread(). +/// +CEF_EXPORT int cef_currently_on(cef_thread_id_t threadId); + +/// +// Post a task for execution on the specified thread. Equivalent to using +// cef_task_tRunner::GetForThread(threadId)->PostTask(task). +/// +CEF_EXPORT int cef_post_task(cef_thread_id_t threadId, cef_task_t* task); + +/// +// Post a task for delayed execution on the specified thread. Equivalent to +// using cef_task_tRunner::GetForThread(threadId)->PostDelayedTask(task, +// delay_ms). +/// +CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, cef_task_t* task, + int64 delay_ms); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_TASK_CAPI_H_ diff --git a/include/capi/cef_trace_capi.h b/include/capi/cef_trace_capi.h new file mode 100644 index 000000000..92b499916 --- /dev/null +++ b/include/capi/cef_trace_capi.h @@ -0,0 +1,118 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_TRACE_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_TRACE_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_callback_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Implement this structure to receive notification when tracing has completed. +// The functions of this structure will be called on the browser process UI +// thread. +/// +typedef struct _cef_end_tracing_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called after all processes have sent their trace data. |tracing_file| is + // the path at which tracing data was written. The client is responsible for + // deleting |tracing_file|. + /// + void (CEF_CALLBACK *on_end_tracing_complete)( + struct _cef_end_tracing_callback_t* self, + const cef_string_t* tracing_file); +} cef_end_tracing_callback_t; + + +/// +// Start tracing events on all processes. Tracing is initialized asynchronously +// and |callback| will be executed on the UI thread after initialization is +// complete. +// +// If CefBeginTracing was called previously, or if a CefEndTracingAsync call is +// pending, CefBeginTracing will fail and return false (0). +// +// |categories| is a comma-delimited list of category wildcards. A category can +// have an optional '-' prefix to make it an excluded category. Having both +// included and excluded categories in the same list is not supported. +// +// Example: "test_MyTest*" Example: "test_MyTest*,test_OtherStuff" Example: +// "-excluded_category1,-excluded_category2" +// +// This function must be called on the browser process UI thread. +/// +CEF_EXPORT int cef_begin_tracing(const cef_string_t* categories, + struct _cef_completion_callback_t* callback); + +/// +// Stop tracing events on all processes. +// +// This function will fail and return false (0) if a previous call to +// CefEndTracingAsync is already pending or if CefBeginTracing was not called. +// +// |tracing_file| is the path at which tracing data will be written and +// |callback| is the callback that will be executed once all processes have sent +// their trace data. If |tracing_file| is NULL a new temporary file path will be +// used. If |callback| is NULL no trace data will be written. +// +// This function must be called on the browser process UI thread. +/// +CEF_EXPORT int cef_end_tracing(const cef_string_t* tracing_file, + cef_end_tracing_callback_t* callback); + +/// +// Returns the current system trace time or, if none is defined, the current +// high-res time. Can be used by clients to synchronize with the time +// information in trace events. +/// +CEF_EXPORT int64 cef_now_from_system_trace_time(); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_TRACE_CAPI_H_ diff --git a/include/capi/cef_url_capi.h b/include/capi/cef_url_capi.h new file mode 100644 index 000000000..a21896402 --- /dev/null +++ b/include/capi/cef_url_capi.h @@ -0,0 +1,82 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_URL_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_URL_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Parse the specified |url| into its component parts. Returns false (0) if the +// URL is NULL or invalid. +/// +CEF_EXPORT int cef_parse_url(const cef_string_t* url, + struct _cef_urlparts_t* parts); + +/// +// Creates a URL from the specified |parts|, which must contain a non-NULL spec +// or a non-NULL host and path (at a minimum), but not both. Returns false (0) +// if |parts| isn't initialized as described. +/// +CEF_EXPORT int cef_create_url(const struct _cef_urlparts_t* parts, + cef_string_t* url); + +/// +// Returns the mime type for the specified file extension or an NULL string if +// unknown. +/// +// The resulting string must be freed by calling cef_string_userfree_free(). +CEF_EXPORT cef_string_userfree_t cef_get_mime_type( + const cef_string_t* extension); + +// Get the extensions associated with the given mime type. This should be passed +// in lower case. There could be multiple extensions for a given mime type, like +// "html,htm" for "text/html", or "txt,text,html,..." for "text/*". Any existing +// elements in the provided vector will not be erased. +CEF_EXPORT void cef_get_extensions_for_mime_type(const cef_string_t* mime_type, + cef_string_list_t extensions); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_URL_CAPI_H_ diff --git a/include/capi/cef_urlrequest_capi.h b/include/capi/cef_urlrequest_capi.h new file mode 100644 index 000000000..cf95f268b --- /dev/null +++ b/include/capi/cef_urlrequest_capi.h @@ -0,0 +1,189 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_URLREQUEST_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_URLREQUEST_CAPI_H_ +#pragma once + +#include "include/capi/cef_auth_callback_capi.h" +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_request_capi.h" +#include "include/capi/cef_response_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_urlrequest_client_t; + +/// +// Structure used to make a URL request. URL requests are not associated with a +// browser instance so no cef_client_t callbacks will be executed. URL requests +// can be created on any valid CEF thread in either the browser or render +// process. Once created the functions of the URL request object must be +// accessed on the same thread that created it. +/// +typedef struct _cef_urlrequest_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the request object used to create this URL request. The returned + // object is read-only and should not be modified. + /// + struct _cef_request_t* (CEF_CALLBACK *get_request)( + struct _cef_urlrequest_t* self); + + /// + // Returns the client. + /// + struct _cef_urlrequest_client_t* (CEF_CALLBACK *get_client)( + struct _cef_urlrequest_t* self); + + /// + // Returns the request status. + /// + cef_urlrequest_status_t (CEF_CALLBACK *get_request_status)( + struct _cef_urlrequest_t* self); + + /// + // Returns the request error if status is UR_CANCELED or UR_FAILED, or 0 + // otherwise. + /// + cef_errorcode_t (CEF_CALLBACK *get_request_error)( + struct _cef_urlrequest_t* self); + + /// + // Returns the response, or NULL if no response information is available. + // Response information will only be available after the upload has completed. + // The returned object is read-only and should not be modified. + /// + struct _cef_response_t* (CEF_CALLBACK *get_response)( + struct _cef_urlrequest_t* self); + + /// + // Cancel the request. + /// + void (CEF_CALLBACK *cancel)(struct _cef_urlrequest_t* self); +} cef_urlrequest_t; + + +/// +// Create a new URL request. Only GET, POST, HEAD, DELETE and PUT request +// functions are supported. Multiple post data elements are not supported and +// elements of type PDE_TYPE_FILE are only supported for requests originating +// from the browser process. Requests originating from the render process will +// receive the same handling as requests originating from Web content -- if the +// response contains Content-Disposition or Mime-Type header values that would +// not normally be rendered then the response may receive special handling +// inside the browser (for example, via the file download code path instead of +// the URL request code path). The |request| object will be marked as read-only +// after calling this function. +/// +CEF_EXPORT cef_urlrequest_t* cef_urlrequest_create( + struct _cef_request_t* request, struct _cef_urlrequest_client_t* client); + + +/// +// Structure that should be implemented by the cef_urlrequest_t client. The +// functions of this structure will be called on the same thread that created +// the request unless otherwise documented. +/// +typedef struct _cef_urlrequest_client_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Notifies the client that the request has completed. Use the + // cef_urlrequest_t::GetRequestStatus function to determine if the request was + // successful or not. + /// + void (CEF_CALLBACK *on_request_complete)( + struct _cef_urlrequest_client_t* self, + struct _cef_urlrequest_t* request); + + /// + // Notifies the client of upload progress. |current| denotes the number of + // bytes sent so far and |total| is the total size of uploading data (or -1 if + // chunked upload is enabled). This function will only be called if the + // UR_FLAG_REPORT_UPLOAD_PROGRESS flag is set on the request. + /// + void (CEF_CALLBACK *on_upload_progress)(struct _cef_urlrequest_client_t* self, + struct _cef_urlrequest_t* request, int64 current, int64 total); + + /// + // Notifies the client of download progress. |current| denotes the number of + // bytes received up to the call and |total| is the expected total size of the + // response (or -1 if not determined). + /// + void (CEF_CALLBACK *on_download_progress)( + struct _cef_urlrequest_client_t* self, struct _cef_urlrequest_t* request, + int64 current, int64 total); + + /// + // Called when some part of the response is read. |data| contains the current + // bytes received since the last call. This function will not be called if the + // UR_FLAG_NO_DOWNLOAD_DATA flag is set on the request. + /// + void (CEF_CALLBACK *on_download_data)(struct _cef_urlrequest_client_t* self, + struct _cef_urlrequest_t* request, const void* data, + size_t data_length); + + /// + // Called on the IO thread when the browser needs credentials from the user. + // |isProxy| indicates whether the host is a proxy server. |host| contains the + // hostname and |port| contains the port number. Return true (1) to continue + // the request and call cef_auth_callback_t::cont() when the authentication + // information is available. Return false (0) to cancel the request. This + // function will only be called for requests initiated from the browser + // process. + /// + int (CEF_CALLBACK *get_auth_credentials)( + struct _cef_urlrequest_client_t* self, int isProxy, + const cef_string_t* host, int port, const cef_string_t* realm, + const cef_string_t* scheme, struct _cef_auth_callback_t* callback); +} cef_urlrequest_client_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_URLREQUEST_CAPI_H_ diff --git a/include/capi/cef_v8_capi.h b/include/capi/cef_v8_capi.h new file mode 100644 index 000000000..123163b55 --- /dev/null +++ b/include/capi/cef_v8_capi.h @@ -0,0 +1,851 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_V8_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_V8_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" +#include "include/capi/cef_frame_capi.h" +#include "include/capi/cef_task_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_v8exception_t; +struct _cef_v8handler_t; +struct _cef_v8stack_frame_t; +struct _cef_v8value_t; + +/// +// Structure representing a V8 context handle. V8 handles can only be accessed +// from the thread on which they are created. Valid threads for creating a V8 +// handle include the render process main thread (TID_RENDERER) and WebWorker +// threads. A task runner for posting tasks on the associated thread can be +// retrieved via the cef_v8context_t::get_task_runner() function. +/// +typedef struct _cef_v8context_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the task runner associated with this context. V8 handles can only + // be accessed from the thread on which they are created. This function can be + // called on any render process thread. + /// + struct _cef_task_runner_t* (CEF_CALLBACK *get_task_runner)( + struct _cef_v8context_t* self); + + /// + // Returns true (1) if the underlying handle is valid and it can be accessed + // on the current thread. Do not call any other functions if this function + // returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_v8context_t* self); + + /// + // Returns the browser for this context. This function will return an NULL + // reference for WebWorker contexts. + /// + struct _cef_browser_t* (CEF_CALLBACK *get_browser)( + struct _cef_v8context_t* self); + + /// + // Returns the frame for this context. This function will return an NULL + // reference for WebWorker contexts. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_frame)(struct _cef_v8context_t* self); + + /// + // Returns the global object for this context. The context must be entered + // before calling this function. + /// + struct _cef_v8value_t* (CEF_CALLBACK *get_global)( + struct _cef_v8context_t* self); + + /// + // Enter this context. A context must be explicitly entered before creating a + // V8 Object, Array, Function or Date asynchronously. exit() must be called + // the same number of times as enter() before releasing this context. V8 + // objects belong to the context in which they are created. Returns true (1) + // if the scope was entered successfully. + /// + int (CEF_CALLBACK *enter)(struct _cef_v8context_t* self); + + /// + // Exit this context. Call this function only after calling enter(). Returns + // true (1) if the scope was exited successfully. + /// + int (CEF_CALLBACK *exit)(struct _cef_v8context_t* self); + + /// + // Returns true (1) if this object is pointing to the same handle as |that| + // object. + /// + int (CEF_CALLBACK *is_same)(struct _cef_v8context_t* self, + struct _cef_v8context_t* that); + + /// + // Evaluates the specified JavaScript code using this context's global object. + // On success |retval| will be set to the return value, if any, and the + // function will return true (1). On failure |exception| will be set to the + // exception, if any, and the function will return false (0). + /// + int (CEF_CALLBACK *eval)(struct _cef_v8context_t* self, + const cef_string_t* code, struct _cef_v8value_t** retval, + struct _cef_v8exception_t** exception); +} cef_v8context_t; + + +/// +// Returns the current (top) context object in the V8 context stack. +/// +CEF_EXPORT cef_v8context_t* cef_v8context_get_current_context(); + +/// +// Returns the entered (bottom) context object in the V8 context stack. +/// +CEF_EXPORT cef_v8context_t* cef_v8context_get_entered_context(); + +/// +// Returns true (1) if V8 is currently inside a context. +/// +CEF_EXPORT int cef_v8context_in_context(); + + +/// +// Structure that should be implemented to handle V8 function calls. The +// functions of this structure will be called on the thread associated with the +// V8 function. +/// +typedef struct _cef_v8handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Handle execution of the function identified by |name|. |object| is the + // receiver ('this' object) of the function. |arguments| is the list of + // arguments passed to the function. If execution succeeds set |retval| to the + // function return value. If execution fails set |exception| to the exception + // that will be thrown. Return true (1) if execution was handled. + /// + int (CEF_CALLBACK *execute)(struct _cef_v8handler_t* self, + const cef_string_t* name, struct _cef_v8value_t* object, + size_t argumentsCount, struct _cef_v8value_t* const* arguments, + struct _cef_v8value_t** retval, cef_string_t* exception); +} cef_v8handler_t; + + +/// +// Structure that should be implemented to handle V8 accessor calls. Accessor +// identifiers are registered by calling cef_v8value_t::set_value_byaccessor(). +// The functions of this structure will be called on the thread associated with +// the V8 accessor. +/// +typedef struct _cef_v8accessor_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Handle retrieval the accessor value identified by |name|. |object| is the + // receiver ('this' object) of the accessor. If retrieval succeeds set + // |retval| to the return value. If retrieval fails set |exception| to the + // exception that will be thrown. Return true (1) if accessor retrieval was + // handled. + /// + int (CEF_CALLBACK *get)(struct _cef_v8accessor_t* self, + const cef_string_t* name, struct _cef_v8value_t* object, + struct _cef_v8value_t** retval, cef_string_t* exception); + + /// + // Handle assignment of the accessor value identified by |name|. |object| is + // the receiver ('this' object) of the accessor. |value| is the new value + // being assigned to the accessor. If assignment fails set |exception| to the + // exception that will be thrown. Return true (1) if accessor assignment was + // handled. + /// + int (CEF_CALLBACK *set)(struct _cef_v8accessor_t* self, + const cef_string_t* name, struct _cef_v8value_t* object, + struct _cef_v8value_t* value, cef_string_t* exception); +} cef_v8accessor_t; + + +/// +// Structure representing a V8 exception. The functions of this structure may be +// called on any render process thread. +/// +typedef struct _cef_v8exception_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the exception message. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_message)( + struct _cef_v8exception_t* self); + + /// + // Returns the line of source code that the exception occurred within. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_source_line)( + struct _cef_v8exception_t* self); + + /// + // Returns the resource name for the script from where the function causing + // the error originates. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_script_resource_name)( + struct _cef_v8exception_t* self); + + /// + // Returns the 1-based number of the line where the error occurred or 0 if the + // line number is unknown. + /// + int (CEF_CALLBACK *get_line_number)(struct _cef_v8exception_t* self); + + /// + // Returns the index within the script of the first character where the error + // occurred. + /// + int (CEF_CALLBACK *get_start_position)(struct _cef_v8exception_t* self); + + /// + // Returns the index within the script of the last character where the error + // occurred. + /// + int (CEF_CALLBACK *get_end_position)(struct _cef_v8exception_t* self); + + /// + // Returns the index within the line of the first character where the error + // occurred. + /// + int (CEF_CALLBACK *get_start_column)(struct _cef_v8exception_t* self); + + /// + // Returns the index within the line of the last character where the error + // occurred. + /// + int (CEF_CALLBACK *get_end_column)(struct _cef_v8exception_t* self); +} cef_v8exception_t; + + +/// +// Structure representing a V8 value handle. V8 handles can only be accessed +// from the thread on which they are created. Valid threads for creating a V8 +// handle include the render process main thread (TID_RENDERER) and WebWorker +// threads. A task runner for posting tasks on the associated thread can be +// retrieved via the cef_v8context_t::get_task_runner() function. +/// +typedef struct _cef_v8value_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if the underlying handle is valid and it can be accessed + // on the current thread. Do not call any other functions if this function + // returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_v8value_t* self); + + /// + // True if the value type is undefined. + /// + int (CEF_CALLBACK *is_undefined)(struct _cef_v8value_t* self); + + /// + // True if the value type is null. + /// + int (CEF_CALLBACK *is_null)(struct _cef_v8value_t* self); + + /// + // True if the value type is bool. + /// + int (CEF_CALLBACK *is_bool)(struct _cef_v8value_t* self); + + /// + // True if the value type is int. + /// + int (CEF_CALLBACK *is_int)(struct _cef_v8value_t* self); + + /// + // True if the value type is unsigned int. + /// + int (CEF_CALLBACK *is_uint)(struct _cef_v8value_t* self); + + /// + // True if the value type is double. + /// + int (CEF_CALLBACK *is_double)(struct _cef_v8value_t* self); + + /// + // True if the value type is Date. + /// + int (CEF_CALLBACK *is_date)(struct _cef_v8value_t* self); + + /// + // True if the value type is string. + /// + int (CEF_CALLBACK *is_string)(struct _cef_v8value_t* self); + + /// + // True if the value type is object. + /// + int (CEF_CALLBACK *is_object)(struct _cef_v8value_t* self); + + /// + // True if the value type is array. + /// + int (CEF_CALLBACK *is_array)(struct _cef_v8value_t* self); + + /// + // True if the value type is function. + /// + int (CEF_CALLBACK *is_function)(struct _cef_v8value_t* self); + + /// + // Returns true (1) if this object is pointing to the same handle as |that| + // object. + /// + int (CEF_CALLBACK *is_same)(struct _cef_v8value_t* self, + struct _cef_v8value_t* that); + + /// + // Return a bool value. The underlying data will be converted to if + // necessary. + /// + int (CEF_CALLBACK *get_bool_value)(struct _cef_v8value_t* self); + + /// + // Return an int value. The underlying data will be converted to if + // necessary. + /// + int32 (CEF_CALLBACK *get_int_value)(struct _cef_v8value_t* self); + + /// + // Return an unisgned int value. The underlying data will be converted to if + // necessary. + /// + uint32 (CEF_CALLBACK *get_uint_value)(struct _cef_v8value_t* self); + + /// + // Return a double value. The underlying data will be converted to if + // necessary. + /// + double (CEF_CALLBACK *get_double_value)(struct _cef_v8value_t* self); + + /// + // Return a Date value. The underlying data will be converted to if + // necessary. + /// + cef_time_t (CEF_CALLBACK *get_date_value)(struct _cef_v8value_t* self); + + /// + // Return a string value. The underlying data will be converted to if + // necessary. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_string_value)( + struct _cef_v8value_t* self); + + + // OBJECT METHODS - These functions are only available on objects. Arrays and + // functions are also objects. String- and integer-based keys can be used + // interchangably with the framework converting between them as necessary. + + /// + // Returns true (1) if this is a user created object. + /// + int (CEF_CALLBACK *is_user_created)(struct _cef_v8value_t* self); + + /// + // Returns true (1) if the last function call resulted in an exception. This + // attribute exists only in the scope of the current CEF value object. + /// + int (CEF_CALLBACK *has_exception)(struct _cef_v8value_t* self); + + /// + // Returns the exception resulting from the last function call. This attribute + // exists only in the scope of the current CEF value object. + /// + struct _cef_v8exception_t* (CEF_CALLBACK *get_exception)( + struct _cef_v8value_t* self); + + /// + // Clears the last exception and returns true (1) on success. + /// + int (CEF_CALLBACK *clear_exception)(struct _cef_v8value_t* self); + + /// + // Returns true (1) if this object will re-throw future exceptions. This + // attribute exists only in the scope of the current CEF value object. + /// + int (CEF_CALLBACK *will_rethrow_exceptions)(struct _cef_v8value_t* self); + + /// + // Set whether this object will re-throw future exceptions. By default + // exceptions are not re-thrown. If a exception is re-thrown the current + // context should not be accessed again until after the exception has been + // caught and not re-thrown. Returns true (1) on success. This attribute + // exists only in the scope of the current CEF value object. + /// + int (CEF_CALLBACK *set_rethrow_exceptions)(struct _cef_v8value_t* self, + int rethrow); + + /// + // Returns true (1) if the object has a value with the specified identifier. + /// + int (CEF_CALLBACK *has_value_bykey)(struct _cef_v8value_t* self, + const cef_string_t* key); + + /// + // Returns true (1) if the object has a value with the specified identifier. + /// + int (CEF_CALLBACK *has_value_byindex)(struct _cef_v8value_t* self, int index); + + /// + // Deletes the value with the specified identifier and returns true (1) on + // success. Returns false (0) if this function is called incorrectly or an + // exception is thrown. For read-only and don't-delete values this function + // will return true (1) even though deletion failed. + /// + int (CEF_CALLBACK *delete_value_bykey)(struct _cef_v8value_t* self, + const cef_string_t* key); + + /// + // Deletes the value with the specified identifier and returns true (1) on + // success. Returns false (0) if this function is called incorrectly, deletion + // fails or an exception is thrown. For read-only and don't-delete values this + // function will return true (1) even though deletion failed. + /// + int (CEF_CALLBACK *delete_value_byindex)(struct _cef_v8value_t* self, + int index); + + /// + // Returns the value with the specified identifier on success. Returns NULL if + // this function is called incorrectly or an exception is thrown. + /// + struct _cef_v8value_t* (CEF_CALLBACK *get_value_bykey)( + struct _cef_v8value_t* self, const cef_string_t* key); + + /// + // Returns the value with the specified identifier on success. Returns NULL if + // this function is called incorrectly or an exception is thrown. + /// + struct _cef_v8value_t* (CEF_CALLBACK *get_value_byindex)( + struct _cef_v8value_t* self, int index); + + /// + // Associates a value with the specified identifier and returns true (1) on + // success. Returns false (0) if this function is called incorrectly or an + // exception is thrown. For read-only values this function will return true + // (1) even though assignment failed. + /// + int (CEF_CALLBACK *set_value_bykey)(struct _cef_v8value_t* self, + const cef_string_t* key, struct _cef_v8value_t* value, + cef_v8_propertyattribute_t attribute); + + /// + // Associates a value with the specified identifier and returns true (1) on + // success. Returns false (0) if this function is called incorrectly or an + // exception is thrown. For read-only values this function will return true + // (1) even though assignment failed. + /// + int (CEF_CALLBACK *set_value_byindex)(struct _cef_v8value_t* self, int index, + struct _cef_v8value_t* value); + + /// + // Registers an identifier and returns true (1) on success. Access to the + // identifier will be forwarded to the cef_v8accessor_t instance passed to + // cef_v8value_t::cef_v8value_create_object(). Returns false (0) if this + // function is called incorrectly or an exception is thrown. For read-only + // values this function will return true (1) even though assignment failed. + /// + int (CEF_CALLBACK *set_value_byaccessor)(struct _cef_v8value_t* self, + const cef_string_t* key, cef_v8_accesscontrol_t settings, + cef_v8_propertyattribute_t attribute); + + /// + // Read the keys for the object's values into the specified vector. Integer- + // based keys will also be returned as strings. + /// + int (CEF_CALLBACK *get_keys)(struct _cef_v8value_t* self, + cef_string_list_t keys); + + /// + // Sets the user data for this object and returns true (1) on success. Returns + // false (0) if this function is called incorrectly. This function can only be + // called on user created objects. + /// + int (CEF_CALLBACK *set_user_data)(struct _cef_v8value_t* self, + struct _cef_base_t* user_data); + + /// + // Returns the user data, if any, assigned to this object. + /// + struct _cef_base_t* (CEF_CALLBACK *get_user_data)( + struct _cef_v8value_t* self); + + /// + // Returns the amount of externally allocated memory registered for the + // object. + /// + int (CEF_CALLBACK *get_externally_allocated_memory)( + struct _cef_v8value_t* self); + + /// + // Adjusts the amount of registered external memory for the object. Used to + // give V8 an indication of the amount of externally allocated memory that is + // kept alive by JavaScript objects. V8 uses this information to decide when + // to perform global garbage collection. Each cef_v8value_t tracks the amount + // of external memory associated with it and automatically decreases the + // global total by the appropriate amount on its destruction. + // |change_in_bytes| specifies the number of bytes to adjust by. This function + // returns the number of bytes associated with the object after the + // adjustment. This function can only be called on user created objects. + /// + int (CEF_CALLBACK *adjust_externally_allocated_memory)( + struct _cef_v8value_t* self, int change_in_bytes); + + + // ARRAY METHODS - These functions are only available on arrays. + + /// + // Returns the number of elements in the array. + /// + int (CEF_CALLBACK *get_array_length)(struct _cef_v8value_t* self); + + + // FUNCTION METHODS - These functions are only available on functions. + + /// + // Returns the function name. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_function_name)( + struct _cef_v8value_t* self); + + /// + // Returns the function handler or NULL if not a CEF-created function. + /// + struct _cef_v8handler_t* (CEF_CALLBACK *get_function_handler)( + struct _cef_v8value_t* self); + + /// + // Execute the function using the current V8 context. This function should + // only be called from within the scope of a cef_v8handler_t or + // cef_v8accessor_t callback, or in combination with calling enter() and + // exit() on a stored cef_v8context_t reference. |object| is the receiver + // ('this' object) of the function. If |object| is NULL the current context's + // global object will be used. |arguments| is the list of arguments that will + // be passed to the function. Returns the function return value on success. + // Returns NULL if this function is called incorrectly or an exception is + // thrown. + /// + struct _cef_v8value_t* (CEF_CALLBACK *execute_function)( + struct _cef_v8value_t* self, struct _cef_v8value_t* object, + size_t argumentsCount, struct _cef_v8value_t* const* arguments); + + /// + // Execute the function using the specified V8 context. |object| is the + // receiver ('this' object) of the function. If |object| is NULL the specified + // context's global object will be used. |arguments| is the list of arguments + // that will be passed to the function. Returns the function return value on + // success. Returns NULL if this function is called incorrectly or an + // exception is thrown. + /// + struct _cef_v8value_t* (CEF_CALLBACK *execute_function_with_context)( + struct _cef_v8value_t* self, struct _cef_v8context_t* context, + struct _cef_v8value_t* object, size_t argumentsCount, + struct _cef_v8value_t* const* arguments); +} cef_v8value_t; + + +/// +// Create a new cef_v8value_t object of type undefined. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_undefined(); + +/// +// Create a new cef_v8value_t object of type null. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_null(); + +/// +// Create a new cef_v8value_t object of type bool. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_bool(int value); + +/// +// Create a new cef_v8value_t object of type int. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_int(int32 value); + +/// +// Create a new cef_v8value_t object of type unsigned int. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_uint(uint32 value); + +/// +// Create a new cef_v8value_t object of type double. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_double(double value); + +/// +// Create a new cef_v8value_t object of type Date. This function should only be +// called from within the scope of a cef_v8context_tHandler, cef_v8handler_t or +// cef_v8accessor_t callback, or in combination with calling enter() and exit() +// on a stored cef_v8context_t reference. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_date(const cef_time_t* date); + +/// +// Create a new cef_v8value_t object of type string. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_string(const cef_string_t* value); + +/// +// Create a new cef_v8value_t object of type object with optional accessor. This +// function should only be called from within the scope of a +// cef_v8context_tHandler, cef_v8handler_t or cef_v8accessor_t callback, or in +// combination with calling enter() and exit() on a stored cef_v8context_t +// reference. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_object(cef_v8accessor_t* accessor); + +/// +// Create a new cef_v8value_t object of type array with the specified |length|. +// If |length| is negative the returned array will have length 0. This function +// should only be called from within the scope of a cef_v8context_tHandler, +// cef_v8handler_t or cef_v8accessor_t callback, or in combination with calling +// enter() and exit() on a stored cef_v8context_t reference. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_array(int length); + +/// +// Create a new cef_v8value_t object of type function. This function should only +// be called from within the scope of a cef_v8context_tHandler, cef_v8handler_t +// or cef_v8accessor_t callback, or in combination with calling enter() and +// exit() on a stored cef_v8context_t reference. +/// +CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const cef_string_t* name, + cef_v8handler_t* handler); + + +/// +// Structure representing a V8 stack trace handle. V8 handles can only be +// accessed from the thread on which they are created. Valid threads for +// creating a V8 handle include the render process main thread (TID_RENDERER) +// and WebWorker threads. A task runner for posting tasks on the associated +// thread can be retrieved via the cef_v8context_t::get_task_runner() function. +/// +typedef struct _cef_v8stack_trace_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if the underlying handle is valid and it can be accessed + // on the current thread. Do not call any other functions if this function + // returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_v8stack_trace_t* self); + + /// + // Returns the number of stack frames. + /// + int (CEF_CALLBACK *get_frame_count)(struct _cef_v8stack_trace_t* self); + + /// + // Returns the stack frame at the specified 0-based index. + /// + struct _cef_v8stack_frame_t* (CEF_CALLBACK *get_frame)( + struct _cef_v8stack_trace_t* self, int index); +} cef_v8stack_trace_t; + + +/// +// Returns the stack trace for the currently active context. |frame_limit| is +// the maximum number of frames that will be captured. +/// +CEF_EXPORT cef_v8stack_trace_t* cef_v8stack_trace_get_current(int frame_limit); + + +/// +// Structure representing a V8 stack frame handle. V8 handles can only be +// accessed from the thread on which they are created. Valid threads for +// creating a V8 handle include the render process main thread (TID_RENDERER) +// and WebWorker threads. A task runner for posting tasks on the associated +// thread can be retrieved via the cef_v8context_t::get_task_runner() function. +/// +typedef struct _cef_v8stack_frame_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if the underlying handle is valid and it can be accessed + // on the current thread. Do not call any other functions if this function + // returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_v8stack_frame_t* self); + + /// + // Returns the name of the resource script that contains the function. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_script_name)( + struct _cef_v8stack_frame_t* self); + + /// + // Returns the name of the resource script that contains the function or the + // sourceURL value if the script name is undefined and its source ends with a + // "//@ sourceURL=..." string. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_script_name_or_source_url)( + struct _cef_v8stack_frame_t* self); + + /// + // Returns the name of the function. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_function_name)( + struct _cef_v8stack_frame_t* self); + + /// + // Returns the 1-based line number for the function call or 0 if unknown. + /// + int (CEF_CALLBACK *get_line_number)(struct _cef_v8stack_frame_t* self); + + /// + // Returns the 1-based column offset on the line for the function call or 0 if + // unknown. + /// + int (CEF_CALLBACK *get_column)(struct _cef_v8stack_frame_t* self); + + /// + // Returns true (1) if the function was compiled using eval(). + /// + int (CEF_CALLBACK *is_eval)(struct _cef_v8stack_frame_t* self); + + /// + // Returns true (1) if the function was called as a constructor via "new". + /// + int (CEF_CALLBACK *is_constructor)(struct _cef_v8stack_frame_t* self); +} cef_v8stack_frame_t; + + +/// +// Register a new V8 extension with the specified JavaScript extension code and +// handler. Functions implemented by the handler are prototyped using the +// keyword 'native'. The calling of a native function is restricted to the scope +// in which the prototype of the native function is defined. This function may +// only be called on the render process main thread. +// +// Example JavaScript extension code:
+//   // create the 'example' global object if it doesn't already exist.
+//   if (!example)
+//     example = {};
+//   // create the 'example.test' global object if it doesn't already exist.
+//   if (!example.test)
+//     example.test = {};
+//   (function() {
+//     // Define the function 'example.test.myfunction'.
+//     example.test.myfunction = function() {
+//       // Call CefV8Handler::Execute() with the function name 'MyFunction'
+//       // and no arguments.
+//       native function MyFunction();
+//       return MyFunction();
+//     };
+//     // Define the getter function for parameter 'example.test.myparam'.
+//     example.test.__defineGetter__('myparam', function() {
+//       // Call CefV8Handler::Execute() with the function name 'GetMyParam'
+//       // and no arguments.
+//       native function GetMyParam();
+//       return GetMyParam();
+//     });
+//     // Define the setter function for parameter 'example.test.myparam'.
+//     example.test.__defineSetter__('myparam', function(b) {
+//       // Call CefV8Handler::Execute() with the function name 'SetMyParam'
+//       // and a single argument.
+//       native function SetMyParam();
+//       if(b) SetMyParam(b);
+//     });
+//
+//     // Extension definitions can also contain normal JavaScript variables
+//     // and functions.
+//     var myint = 0;
+//     example.test.increment = function() {
+//       myint += 1;
+//       return myint;
+//     };
+//   })();
+// 
Example usage in the page:
+//   // Call the function.
+//   example.test.myfunction();
+//   // Set the parameter.
+//   example.test.myparam = value;
+//   // Get the parameter.
+//   value = example.test.myparam;
+//   // Call another function.
+//   example.test.increment();
+// 
+/// +CEF_EXPORT int cef_register_extension(const cef_string_t* extension_name, + const cef_string_t* javascript_code, cef_v8handler_t* handler); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_V8_CAPI_H_ diff --git a/include/capi/cef_values_capi.h b/include/capi/cef_values_capi.h new file mode 100644 index 000000000..e2f6b2325 --- /dev/null +++ b/include/capi/cef_values_capi.h @@ -0,0 +1,463 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_VALUES_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_VALUES_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct _cef_dictionary_value_t; +struct _cef_list_value_t; + +/// +// Structure representing a binary value. Can be used on any process and thread. +/// +typedef struct _cef_binary_value_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_binary_value_t* self); + + /// + // Returns true (1) if this object is currently owned by another object. + /// + int (CEF_CALLBACK *is_owned)(struct _cef_binary_value_t* self); + + /// + // Returns a copy of this object. The data in this object will also be copied. + /// + struct _cef_binary_value_t* (CEF_CALLBACK *copy)( + struct _cef_binary_value_t* self); + + /// + // Returns the data size. + /// + size_t (CEF_CALLBACK *get_size)(struct _cef_binary_value_t* self); + + /// + // Read up to |buffer_size| number of bytes into |buffer|. Reading begins at + // the specified byte |data_offset|. Returns the number of bytes read. + /// + size_t (CEF_CALLBACK *get_data)(struct _cef_binary_value_t* self, + void* buffer, size_t buffer_size, size_t data_offset); +} cef_binary_value_t; + + +/// +// Creates a new object that is not owned by any other object. The specified +// |data| will be copied. +/// +CEF_EXPORT cef_binary_value_t* cef_binary_value_create(const void* data, + size_t data_size); + + +/// +// Structure representing a dictionary value. Can be used on any process and +// thread. +/// +typedef struct _cef_dictionary_value_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_dictionary_value_t* self); + + /// + // Returns true (1) if this object is currently owned by another object. + /// + int (CEF_CALLBACK *is_owned)(struct _cef_dictionary_value_t* self); + + /// + // Returns true (1) if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_dictionary_value_t* self); + + /// + // Returns a writable copy of this object. If |exclude_NULL_children| is true + // (1) any NULL dictionaries or lists will be excluded from the copy. + /// + struct _cef_dictionary_value_t* (CEF_CALLBACK *copy)( + struct _cef_dictionary_value_t* self, int exclude_empty_children); + + /// + // Returns the number of values. + /// + size_t (CEF_CALLBACK *get_size)(struct _cef_dictionary_value_t* self); + + /// + // Removes all values. Returns true (1) on success. + /// + int (CEF_CALLBACK *clear)(struct _cef_dictionary_value_t* self); + + /// + // Returns true (1) if the current dictionary has a value for the given key. + /// + int (CEF_CALLBACK *has_key)(struct _cef_dictionary_value_t* self, + const cef_string_t* key); + + /// + // Reads all keys for this dictionary into the specified vector. + /// + int (CEF_CALLBACK *get_keys)(struct _cef_dictionary_value_t* self, + cef_string_list_t keys); + + /// + // Removes the value at the specified key. Returns true (1) is the value was + // removed successfully. + /// + int (CEF_CALLBACK *remove)(struct _cef_dictionary_value_t* self, + const cef_string_t* key); + + /// + // Returns the value type for the specified key. + /// + cef_value_type_t (CEF_CALLBACK *get_type)( + struct _cef_dictionary_value_t* self, const cef_string_t* key); + + /// + // Returns the value at the specified key as type bool. + /// + int (CEF_CALLBACK *get_bool)(struct _cef_dictionary_value_t* self, + const cef_string_t* key); + + /// + // Returns the value at the specified key as type int. + /// + int (CEF_CALLBACK *get_int)(struct _cef_dictionary_value_t* self, + const cef_string_t* key); + + /// + // Returns the value at the specified key as type double. + /// + double (CEF_CALLBACK *get_double)(struct _cef_dictionary_value_t* self, + const cef_string_t* key); + + /// + // Returns the value at the specified key as type string. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_string)( + struct _cef_dictionary_value_t* self, const cef_string_t* key); + + /// + // Returns the value at the specified key as type binary. + /// + struct _cef_binary_value_t* (CEF_CALLBACK *get_binary)( + struct _cef_dictionary_value_t* self, const cef_string_t* key); + + /// + // Returns the value at the specified key as type dictionary. + /// + struct _cef_dictionary_value_t* (CEF_CALLBACK *get_dictionary)( + struct _cef_dictionary_value_t* self, const cef_string_t* key); + + /// + // Returns the value at the specified key as type list. + /// + struct _cef_list_value_t* (CEF_CALLBACK *get_list)( + struct _cef_dictionary_value_t* self, const cef_string_t* key); + + /// + // Sets the value at the specified key as type null. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_null)(struct _cef_dictionary_value_t* self, + const cef_string_t* key); + + /// + // Sets the value at the specified key as type bool. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_bool)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, int value); + + /// + // Sets the value at the specified key as type int. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_int)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, int value); + + /// + // Sets the value at the specified key as type double. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_double)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, double value); + + /// + // Sets the value at the specified key as type string. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_string)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, const cef_string_t* value); + + /// + // Sets the value at the specified key as type binary. Returns true (1) if the + // value was set successfully. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + int (CEF_CALLBACK *set_binary)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, struct _cef_binary_value_t* value); + + /// + // Sets the value at the specified key as type dict. Returns true (1) if the + // value was set successfully. After calling this function the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + int (CEF_CALLBACK *set_dictionary)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, struct _cef_dictionary_value_t* value); + + /// + // Sets the value at the specified key as type list. Returns true (1) if the + // value was set successfully. After calling this function the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + int (CEF_CALLBACK *set_list)(struct _cef_dictionary_value_t* self, + const cef_string_t* key, struct _cef_list_value_t* value); +} cef_dictionary_value_t; + + +/// +// Creates a new object that is not owned by any other object. +/// +CEF_EXPORT cef_dictionary_value_t* cef_dictionary_value_create(); + + +/// +// Structure representing a list value. Can be used on any process and thread. +/// +typedef struct _cef_list_value_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns true (1) if this object is valid. Do not call any other functions + // if this function returns false (0). + /// + int (CEF_CALLBACK *is_valid)(struct _cef_list_value_t* self); + + /// + // Returns true (1) if this object is currently owned by another object. + /// + int (CEF_CALLBACK *is_owned)(struct _cef_list_value_t* self); + + /// + // Returns true (1) if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + int (CEF_CALLBACK *is_read_only)(struct _cef_list_value_t* self); + + /// + // Returns a writable copy of this object. + /// + struct _cef_list_value_t* (CEF_CALLBACK *copy)( + struct _cef_list_value_t* self); + + /// + // Sets the number of values. If the number of values is expanded all new + // value slots will default to type null. Returns true (1) on success. + /// + int (CEF_CALLBACK *set_size)(struct _cef_list_value_t* self, size_t size); + + /// + // Returns the number of values. + /// + size_t (CEF_CALLBACK *get_size)(struct _cef_list_value_t* self); + + /// + // Removes all values. Returns true (1) on success. + /// + int (CEF_CALLBACK *clear)(struct _cef_list_value_t* self); + + /// + // Removes the value at the specified index. + /// + int (CEF_CALLBACK *remove)(struct _cef_list_value_t* self, int index); + + /// + // Returns the value type at the specified index. + /// + cef_value_type_t (CEF_CALLBACK *get_type)(struct _cef_list_value_t* self, + int index); + + /// + // Returns the value at the specified index as type bool. + /// + int (CEF_CALLBACK *get_bool)(struct _cef_list_value_t* self, int index); + + /// + // Returns the value at the specified index as type int. + /// + int (CEF_CALLBACK *get_int)(struct _cef_list_value_t* self, int index); + + /// + // Returns the value at the specified index as type double. + /// + double (CEF_CALLBACK *get_double)(struct _cef_list_value_t* self, int index); + + /// + // Returns the value at the specified index as type string. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_string)( + struct _cef_list_value_t* self, int index); + + /// + // Returns the value at the specified index as type binary. + /// + struct _cef_binary_value_t* (CEF_CALLBACK *get_binary)( + struct _cef_list_value_t* self, int index); + + /// + // Returns the value at the specified index as type dictionary. + /// + struct _cef_dictionary_value_t* (CEF_CALLBACK *get_dictionary)( + struct _cef_list_value_t* self, int index); + + /// + // Returns the value at the specified index as type list. + /// + struct _cef_list_value_t* (CEF_CALLBACK *get_list)( + struct _cef_list_value_t* self, int index); + + /// + // Sets the value at the specified index as type null. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_null)(struct _cef_list_value_t* self, int index); + + /// + // Sets the value at the specified index as type bool. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_bool)(struct _cef_list_value_t* self, int index, + int value); + + /// + // Sets the value at the specified index as type int. Returns true (1) if the + // value was set successfully. + /// + int (CEF_CALLBACK *set_int)(struct _cef_list_value_t* self, int index, + int value); + + /// + // Sets the value at the specified index as type double. Returns true (1) if + // the value was set successfully. + /// + int (CEF_CALLBACK *set_double)(struct _cef_list_value_t* self, int index, + double value); + + /// + // Sets the value at the specified index as type string. Returns true (1) if + // the value was set successfully. + /// + int (CEF_CALLBACK *set_string)(struct _cef_list_value_t* self, int index, + const cef_string_t* value); + + /// + // Sets the value at the specified index as type binary. Returns true (1) if + // the value was set successfully. After calling this function the |value| + // object will no longer be valid. If |value| is currently owned by another + // object then the value will be copied and the |value| reference will not + // change. Otherwise, ownership will be transferred to this object and the + // |value| reference will be invalidated. + /// + int (CEF_CALLBACK *set_binary)(struct _cef_list_value_t* self, int index, + struct _cef_binary_value_t* value); + + /// + // Sets the value at the specified index as type dict. Returns true (1) if the + // value was set successfully. After calling this function the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + int (CEF_CALLBACK *set_dictionary)(struct _cef_list_value_t* self, int index, + struct _cef_dictionary_value_t* value); + + /// + // Sets the value at the specified index as type list. Returns true (1) if the + // value was set successfully. After calling this function the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + int (CEF_CALLBACK *set_list)(struct _cef_list_value_t* self, int index, + struct _cef_list_value_t* value); +} cef_list_value_t; + + +/// +// Creates a new object that is not owned by any other object. +/// +CEF_EXPORT cef_list_value_t* cef_list_value_create(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_VALUES_CAPI_H_ diff --git a/include/capi/cef_web_plugin_capi.h b/include/capi/cef_web_plugin_capi.h new file mode 100644 index 000000000..05a779a1c --- /dev/null +++ b/include/capi/cef_web_plugin_capi.h @@ -0,0 +1,195 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_WEB_PLUGIN_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_WEB_PLUGIN_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_browser_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Information about a specific web plugin. +/// +typedef struct _cef_web_plugin_info_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the plugin name (i.e. Flash). + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_name)( + struct _cef_web_plugin_info_t* self); + + /// + // Returns the plugin file path (DLL/bundle/library). + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_path)( + struct _cef_web_plugin_info_t* self); + + /// + // Returns the version of the plugin (may be OS-specific). + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_version)( + struct _cef_web_plugin_info_t* self); + + /// + // Returns a description of the plugin from the version information. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_description)( + struct _cef_web_plugin_info_t* self); +} cef_web_plugin_info_t; + + +/// +// Structure to implement for visiting web plugin information. The functions of +// this structure will be called on the browser process UI thread. +/// +typedef struct _cef_web_plugin_info_visitor_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be called once for each plugin. |count| is the 0-based + // index for the current plugin. |total| is the total number of plugins. + // Return false (0) to stop visiting plugins. This function may never be + // called if no plugins are found. + /// + int (CEF_CALLBACK *visit)(struct _cef_web_plugin_info_visitor_t* self, + struct _cef_web_plugin_info_t* info, int count, int total); +} cef_web_plugin_info_visitor_t; + + +/// +// Structure to implement for receiving unstable plugin information. The +// functions of this structure will be called on the browser process IO thread. +/// +typedef struct _cef_web_plugin_unstable_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be called for the requested plugin. |unstable| will be + // true (1) if the plugin has reached the crash count threshold of 3 times in + // 120 seconds. + /// + void (CEF_CALLBACK *is_unstable)( + struct _cef_web_plugin_unstable_callback_t* self, + const cef_string_t* path, int unstable); +} cef_web_plugin_unstable_callback_t; + + +/// +// Visit web plugin information. Can be called on any thread in the browser +// process. +/// +CEF_EXPORT void cef_visit_web_plugin_info( + cef_web_plugin_info_visitor_t* visitor); + +/// +// Cause the plugin list to refresh the next time it is accessed regardless of +// whether it has already been loaded. Can be called on any thread in the +// browser process. +/// +CEF_EXPORT void cef_refresh_web_plugins(); + +/// +// Add a plugin path (directory + file). This change may not take affect until +// after cef_refresh_web_plugins() is called. Can be called on any thread in the +// browser process. +/// +CEF_EXPORT void cef_add_web_plugin_path(const cef_string_t* path); + +/// +// Add a plugin directory. This change may not take affect until after +// cef_refresh_web_plugins() is called. Can be called on any thread in the +// browser process. +/// +CEF_EXPORT void cef_add_web_plugin_directory(const cef_string_t* dir); + +/// +// Remove a plugin path (directory + file). This change may not take affect +// until after cef_refresh_web_plugins() is called. Can be called on any thread +// in the browser process. +/// +CEF_EXPORT void cef_remove_web_plugin_path(const cef_string_t* path); + +/// +// Unregister an internal plugin. This may be undone the next time +// cef_refresh_web_plugins() is called. Can be called on any thread in the +// browser process. +/// +CEF_EXPORT void cef_unregister_internal_web_plugin(const cef_string_t* path); + +/// +// Force a plugin to shutdown. Can be called on any thread in the browser +// process but will be executed on the IO thread. +/// +CEF_EXPORT void cef_force_web_plugin_shutdown(const cef_string_t* path); + +/// +// Register a plugin crash. Can be called on any thread in the browser process +// but will be executed on the IO thread. +/// +CEF_EXPORT void cef_register_web_plugin_crash(const cef_string_t* path); + +/// +// Query if a plugin is unstable. Can be called on any thread in the browser +// process. +/// +CEF_EXPORT void cef_is_web_plugin_unstable(const cef_string_t* path, + cef_web_plugin_unstable_callback_t* callback); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_WEB_PLUGIN_CAPI_H_ diff --git a/include/capi/cef_xml_reader_capi.h b/include/capi/cef_xml_reader_capi.h new file mode 100644 index 000000000..263bcfe1f --- /dev/null +++ b/include/capi/cef_xml_reader_capi.h @@ -0,0 +1,278 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_XML_READER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_XML_READER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_stream_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure that supports the reading of XML data via the libxml streaming API. +// The functions of this structure should only be called on the thread that +// creates the object. +/// +typedef struct _cef_xml_reader_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Moves the cursor to the next node in the document. This function must be + // called at least once to set the current cursor position. Returns true (1) + // if the cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_next_node)(struct _cef_xml_reader_t* self); + + /// + // Close the document. This should be called directly to ensure that cleanup + // occurs on the correct thread. + /// + int (CEF_CALLBACK *close)(struct _cef_xml_reader_t* self); + + /// + // Returns true (1) if an error has been reported by the XML parser. + /// + int (CEF_CALLBACK *has_error)(struct _cef_xml_reader_t* self); + + /// + // Returns the error string. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_error)( + struct _cef_xml_reader_t* self); + + + // The below functions retrieve data for the node at the current cursor + // position. + + /// + // Returns the node type. + /// + cef_xml_node_type_t (CEF_CALLBACK *get_type)(struct _cef_xml_reader_t* self); + + /// + // Returns the node depth. Depth starts at 0 for the root node. + /// + int (CEF_CALLBACK *get_depth)(struct _cef_xml_reader_t* self); + + /// + // Returns the local name. See http://www.w3.org/TR/REC-xml-names/#NT- + // LocalPart for additional details. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_local_name)( + struct _cef_xml_reader_t* self); + + /// + // Returns the namespace prefix. See http://www.w3.org/TR/REC-xml-names/ for + // additional details. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_prefix)( + struct _cef_xml_reader_t* self); + + /// + // Returns the qualified name, equal to (Prefix:)LocalName. See + // http://www.w3.org/TR/REC-xml-names/#ns-qualnames for additional details. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_qualified_name)( + struct _cef_xml_reader_t* self); + + /// + // Returns the URI defining the namespace associated with the node. See + // http://www.w3.org/TR/REC-xml-names/ for additional details. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_namespace_uri)( + struct _cef_xml_reader_t* self); + + /// + // Returns the base URI of the node. See http://www.w3.org/TR/xmlbase/ for + // additional details. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_base_uri)( + struct _cef_xml_reader_t* self); + + /// + // Returns the xml:lang scope within which the node resides. See + // http://www.w3.org/TR/REC-xml/#sec-lang-tag for additional details. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_xml_lang)( + struct _cef_xml_reader_t* self); + + /// + // Returns true (1) if the node represents an NULL element.
is considered + // NULL but is not. + /// + int (CEF_CALLBACK *is_empty_element)(struct _cef_xml_reader_t* self); + + /// + // Returns true (1) if the node has a text value. + /// + int (CEF_CALLBACK *has_value)(struct _cef_xml_reader_t* self); + + /// + // Returns the text value. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_value)( + struct _cef_xml_reader_t* self); + + /// + // Returns true (1) if the node has attributes. + /// + int (CEF_CALLBACK *has_attributes)(struct _cef_xml_reader_t* self); + + /// + // Returns the number of attributes. + /// + size_t (CEF_CALLBACK *get_attribute_count)(struct _cef_xml_reader_t* self); + + /// + // Returns the value of the attribute at the specified 0-based index. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_attribute_byindex)( + struct _cef_xml_reader_t* self, int index); + + /// + // Returns the value of the attribute with the specified qualified name. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_attribute_byqname)( + struct _cef_xml_reader_t* self, const cef_string_t* qualifiedName); + + /// + // Returns the value of the attribute with the specified local name and + // namespace URI. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_attribute_bylname)( + struct _cef_xml_reader_t* self, const cef_string_t* localName, + const cef_string_t* namespaceURI); + + /// + // Returns an XML representation of the current node's children. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_inner_xml)( + struct _cef_xml_reader_t* self); + + /// + // Returns an XML representation of the current node including its children. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_outer_xml)( + struct _cef_xml_reader_t* self); + + /// + // Returns the line number for the current node. + /// + int (CEF_CALLBACK *get_line_number)(struct _cef_xml_reader_t* self); + + + // Attribute nodes are not traversed by default. The below functions can be + // used to move the cursor to an attribute node. move_to_carrying_element() + // can be called afterwards to return the cursor to the carrying element. The + // depth of an attribute node will be 1 + the depth of the carrying element. + + /// + // Moves the cursor to the attribute at the specified 0-based index. Returns + // true (1) if the cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_attribute_byindex)(struct _cef_xml_reader_t* self, + int index); + + /// + // Moves the cursor to the attribute with the specified qualified name. + // Returns true (1) if the cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_attribute_byqname)(struct _cef_xml_reader_t* self, + const cef_string_t* qualifiedName); + + /// + // Moves the cursor to the attribute with the specified local name and + // namespace URI. Returns true (1) if the cursor position was set + // successfully. + /// + int (CEF_CALLBACK *move_to_attribute_bylname)(struct _cef_xml_reader_t* self, + const cef_string_t* localName, const cef_string_t* namespaceURI); + + /// + // Moves the cursor to the first attribute in the current element. Returns + // true (1) if the cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_first_attribute)(struct _cef_xml_reader_t* self); + + /// + // Moves the cursor to the next attribute in the current element. Returns true + // (1) if the cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_next_attribute)(struct _cef_xml_reader_t* self); + + /// + // Moves the cursor back to the carrying element. Returns true (1) if the + // cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_carrying_element)(struct _cef_xml_reader_t* self); +} cef_xml_reader_t; + + +/// +// Create a new cef_xml_reader_t object. The returned object's functions can +// only be called from the thread that created the object. +/// +CEF_EXPORT cef_xml_reader_t* cef_xml_reader_create( + struct _cef_stream_reader_t* stream, cef_xml_encoding_type_t encodingType, + const cef_string_t* URI); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_XML_READER_CAPI_H_ diff --git a/include/capi/cef_zip_reader_capi.h b/include/capi/cef_zip_reader_capi.h new file mode 100644 index 000000000..eceb32db9 --- /dev/null +++ b/include/capi/cef_zip_reader_capi.h @@ -0,0 +1,149 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef CEF_INCLUDE_CAPI_CEF_ZIP_READER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_ZIP_READER_CAPI_H_ +#pragma once + +#include "include/capi/cef_base_capi.h" +#include "include/capi/cef_stream_capi.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/// +// Structure that supports the reading of zip archives via the zlib unzip API. +// The functions of this structure should only be called on the thread that +// creates the object. +/// +typedef struct _cef_zip_reader_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Moves the cursor to the first file in the archive. Returns true (1) if the + // cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_first_file)(struct _cef_zip_reader_t* self); + + /// + // Moves the cursor to the next file in the archive. Returns true (1) if the + // cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_next_file)(struct _cef_zip_reader_t* self); + + /// + // Moves the cursor to the specified file in the archive. If |caseSensitive| + // is true (1) then the search will be case sensitive. Returns true (1) if the + // cursor position was set successfully. + /// + int (CEF_CALLBACK *move_to_file)(struct _cef_zip_reader_t* self, + const cef_string_t* fileName, int caseSensitive); + + /// + // Closes the archive. This should be called directly to ensure that cleanup + // occurs on the correct thread. + /// + int (CEF_CALLBACK *close)(struct _cef_zip_reader_t* self); + + + // The below functions act on the file at the current cursor position. + + /// + // Returns the name of the file. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_file_name)( + struct _cef_zip_reader_t* self); + + /// + // Returns the uncompressed size of the file. + /// + int64 (CEF_CALLBACK *get_file_size)(struct _cef_zip_reader_t* self); + + /// + // Returns the last modified timestamp for the file. + /// + time_t (CEF_CALLBACK *get_file_last_modified)(struct _cef_zip_reader_t* self); + + /// + // Opens the file for reading of uncompressed data. A read password may + // optionally be specified. + /// + int (CEF_CALLBACK *open_file)(struct _cef_zip_reader_t* self, + const cef_string_t* password); + + /// + // Closes the file. + /// + int (CEF_CALLBACK *close_file)(struct _cef_zip_reader_t* self); + + /// + // Read uncompressed file contents into the specified buffer. Returns < 0 if + // an error occurred, 0 if at the end of file, or the number of bytes read. + /// + int (CEF_CALLBACK *read_file)(struct _cef_zip_reader_t* self, void* buffer, + size_t bufferSize); + + /// + // Returns the current offset in the uncompressed file contents. + /// + int64 (CEF_CALLBACK *tell)(struct _cef_zip_reader_t* self); + + /// + // Returns true (1) if at end of the file contents. + /// + int (CEF_CALLBACK *eof)(struct _cef_zip_reader_t* self); +} cef_zip_reader_t; + + +/// +// Create a new cef_zip_reader_t object. The returned object's functions can +// only be called from the thread that created the object. +/// +CEF_EXPORT cef_zip_reader_t* cef_zip_reader_create( + struct _cef_stream_reader_t* stream); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_ZIP_READER_CAPI_H_ diff --git a/include/cef_app.h b/include/cef_app.h new file mode 100644 index 000000000..bac622812 --- /dev/null +++ b/include/cef_app.h @@ -0,0 +1,192 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + + +#ifndef CEF_INCLUDE_CEF_APP_H_ +#define CEF_INCLUDE_CEF_APP_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser_process_handler.h" +#include "include/cef_command_line.h" +#include "include/cef_render_process_handler.h" +#include "include/cef_resource_bundle_handler.h" +#include "include/cef_scheme.h" + +class CefApp; + +/// +// This function should be called from the application entry point function to +// execute a secondary process. It can be used to run secondary processes from +// the browser client executable (default behavior) or from a separate +// executable specified by the CefSettings.browser_subprocess_path value. If +// called for the browser process (identified by no "type" command-line value) +// it will return immediately with a value of -1. If called for a recognized +// secondary process it will block until the process should exit and then return +// the process exit code. The |application| parameter may be empty. The +// |windows_sandbox_info| parameter is only used on Windows and may be NULL (see +// cef_sandbox_win.h for details). +/// +/*--cef(api_hash_check,optional_param=application, + optional_param=windows_sandbox_info)--*/ +int CefExecuteProcess(const CefMainArgs& args, + CefRefPtr application, + void* windows_sandbox_info); + +/// +// This function should be called on the main application thread to initialize +// the CEF browser process. The |application| parameter may be empty. A return +// value of true indicates that it succeeded and false indicates that it failed. +// The |windows_sandbox_info| parameter is only used on Windows and may be NULL +// (see cef_sandbox_win.h for details). +/// +/*--cef(api_hash_check,optional_param=application, + optional_param=windows_sandbox_info)--*/ +bool CefInitialize(const CefMainArgs& args, + const CefSettings& settings, + CefRefPtr application, + void* windows_sandbox_info); + +/// +// This function should be called on the main application thread to shut down +// the CEF browser process before the application exits. +/// +/*--cef()--*/ +void CefShutdown(); + +/// +// Perform a single iteration of CEF message loop processing. This function is +// used to integrate the CEF message loop into an existing application message +// loop. Care must be taken to balance performance against excessive CPU usage. +// This function should only be called on the main application thread and only +// if CefInitialize() is called with a CefSettings.multi_threaded_message_loop +// value of false. This function will not block. +/// +/*--cef()--*/ +void CefDoMessageLoopWork(); + +/// +// Run the CEF message loop. Use this function instead of an application- +// provided message loop to get the best balance between performance and CPU +// usage. This function should only be called on the main application thread and +// only if CefInitialize() is called with a +// CefSettings.multi_threaded_message_loop value of false. This function will +// block until a quit message is received by the system. +/// +/*--cef()--*/ +void CefRunMessageLoop(); + +/// +// Quit the CEF message loop that was started by calling CefRunMessageLoop(). +// This function should only be called on the main application thread and only +// if CefRunMessageLoop() was used. +/// +/*--cef()--*/ +void CefQuitMessageLoop(); + +/// +// Set to true before calling Windows APIs like TrackPopupMenu that enter a +// modal message loop. Set to false after exiting the modal message loop. +/// +/*--cef()--*/ +void CefSetOSModalLoop(bool osModalLoop); + +/// +// Implement this interface to provide handler implementations. Methods will be +// called by the process and/or thread indicated. +/// +/*--cef(source=client,no_debugct_check)--*/ +class CefApp : public virtual CefBase { + public: + /// + // Provides an opportunity to view and/or modify command-line arguments before + // processing by CEF and Chromium. The |process_type| value will be empty for + // the browser process. Do not keep a reference to the CefCommandLine object + // passed to this method. The CefSettings.command_line_args_disabled value + // can be used to start with an empty command-line object. Any values + // specified in CefSettings that equate to command-line arguments will be set + // before this method is called. Be cautious when using this method to modify + // command-line arguments for non-browser processes as this may result in + // undefined behavior including crashes. + /// + /*--cef(optional_param=process_type)--*/ + virtual void OnBeforeCommandLineProcessing( + const CefString& process_type, + CefRefPtr command_line) { + } + + /// + // Provides an opportunity to register custom schemes. Do not keep a reference + // to the |registrar| object. This method is called on the main thread for + // each process and the registered schemes should be the same across all + // processes. + /// + /*--cef()--*/ + virtual void OnRegisterCustomSchemes( + CefRefPtr registrar) { + } + + /// + // Return the handler for resource bundle events. If + // CefSettings.pack_loading_disabled is true a handler must be returned. If no + // handler is returned resources will be loaded from pack files. This method + // is called by the browser and render processes on multiple threads. + /// + /*--cef()--*/ + virtual CefRefPtr GetResourceBundleHandler() { + return NULL; + } + + /// + // Return the handler for functionality specific to the browser process. This + // method is called on multiple threads in the browser process. + /// + /*--cef()--*/ + virtual CefRefPtr GetBrowserProcessHandler() { + return NULL; + } + + /// + // Return the handler for functionality specific to the render process. This + // method is called on the render process main thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetRenderProcessHandler() { + return NULL; + } +}; + +#endif // CEF_INCLUDE_CEF_APP_H_ diff --git a/include/cef_application_mac.h b/include/cef_application_mac.h new file mode 100644 index 000000000..b4e85db22 --- /dev/null +++ b/include/cef_application_mac.h @@ -0,0 +1,200 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_CEF_APPLICATION_MAC_H_ +#define CEF_INCLUDE_CEF_APPLICATION_MAC_H_ +#pragma once + +#include "include/cef_base.h" + +#if defined(OS_MACOSX) && defined(__OBJC__) + +#ifdef BUILDING_CEF_SHARED + +// Use the existing CrAppControlProtocol definition. +#import "base/mac/scoped_sending_event.h" + +// Use the existing CrAppProtocol definition. +#import "base/message_loop/message_pump_mac.h" + +// Use the existing UnderlayableSurface definition. +#import "ui/base/cocoa/underlay_opengl_hosting_window.h" + +// Use the existing empty protocol definitions. +#import "base/mac/cocoa_protocols.h" + +// Use the existing empty protocol definitions. +#import "base/mac/sdk_forward_declarations.h" + +#else // BUILDING_CEF_SHARED + +#import +#import + +// Copy of definition from base/message_loop/message_pump_mac.h. +@protocol CrAppProtocol +// Must return true if -[NSApplication sendEvent:] is currently on the stack. +- (BOOL)isHandlingSendEvent; +@end + +// Copy of definition from base/mac/scoped_sending_event.h. +@protocol CrAppControlProtocol +- (void)setHandlingSendEvent:(BOOL)handlingSendEvent; +@end + +// Copy of definition from ui/base/cocoa/underlay_opengl_hosting_window.h. +// Common base class for windows that host a OpenGL surface that renders under +// the window. Contains methods relating to hole punching so that the OpenGL +// surface is visible through the window. +@interface UnderlayOpenGLHostingWindow : NSWindow +@end + +// Copy of definitions from base/mac/sdk_forward_declarations.h. +// Forward declarations for APIs that are part of the 10.7 SDK. This will allow +// using them when building with the 10.6 SDK. + +#if !defined(MAC_OS_X_VERSION_10_7) || \ + MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7 + +enum { + NSEventPhaseNone = 0, // event not associated with a phase. + NSEventPhaseBegan = 0x1 << 0, + NSEventPhaseStationary = 0x1 << 1, + NSEventPhaseChanged = 0x1 << 2, + NSEventPhaseEnded = 0x1 << 3, + NSEventPhaseCancelled = 0x1 << 4, +}; +typedef NSUInteger NSEventPhase; + +@interface NSEvent (LionSDK) ++ (BOOL)isSwipeTrackingFromScrollEventsEnabled; + +- (NSEventPhase)phase; +- (CGFloat)scrollingDeltaX; +- (CGFloat)scrollingDeltaY; +- (BOOL)isDirectionInvertedFromDevice; +@end + +@interface NSScreen (LionSDK) +- (CGFloat)backingScaleFactor; +- (NSRect)convertRectToBacking:(NSRect)aRect; +@end + +@interface NSWindow (LionSDK) +- (CGFloat)backingScaleFactor; +@end + +#endif // MAC_OS_X_VERSION_10_7 + +// The Mac OS X 10.6 SDK introduced new protocols used for delegates. These +// protocol defintions were not present in earlier releases of the Mac OS X +// SDK. In order to support building against the new SDK, which requires +// delegates to conform to these protocols, and earlier SDKs, which do not +// define these protocols at all, this file will provide empty protocol +// definitions when used with earlier SDK versions. + +#if !defined(MAC_OS_X_VERSION_10_6) || \ +MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_6 + +#define DEFINE_EMPTY_PROTOCOL(p) \ +@protocol p \ +@end + +DEFINE_EMPTY_PROTOCOL(NSAlertDelegate) +DEFINE_EMPTY_PROTOCOL(NSApplicationDelegate) +DEFINE_EMPTY_PROTOCOL(NSControlTextEditingDelegate) +DEFINE_EMPTY_PROTOCOL(NSMatrixDelegate) +DEFINE_EMPTY_PROTOCOL(NSMenuDelegate) +DEFINE_EMPTY_PROTOCOL(NSOpenSavePanelDelegate) +DEFINE_EMPTY_PROTOCOL(NSOutlineViewDataSource) +DEFINE_EMPTY_PROTOCOL(NSOutlineViewDelegate) +DEFINE_EMPTY_PROTOCOL(NSSpeechSynthesizerDelegate) +DEFINE_EMPTY_PROTOCOL(NSSplitViewDelegate) +DEFINE_EMPTY_PROTOCOL(NSTableViewDataSource) +DEFINE_EMPTY_PROTOCOL(NSTableViewDelegate) +DEFINE_EMPTY_PROTOCOL(NSTextFieldDelegate) +DEFINE_EMPTY_PROTOCOL(NSTextViewDelegate) +DEFINE_EMPTY_PROTOCOL(NSWindowDelegate) + +#undef DEFINE_EMPTY_PROTOCOL + +#endif + +#endif // BUILDING_CEF_SHARED + +// Forward declarations for APIs that are part of the 10.7 SDK. This will allow +// using them when building with the 10.6 SDK. + +#if !defined(MAC_OS_X_VERSION_10_7) || \ + MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7 + +@interface NSView (NSOpenGLSurfaceResolutionLionAPI) +- (void)setWantsBestResolutionOpenGLSurface:(BOOL)flag; +@end + +@interface NSView (LionAPI) +- (NSSize)convertSizeToBacking:(NSSize)aSize; +- (NSRect)convertRectToBacking:(NSRect)aRect; +- (NSRect)convertRectFromBacking:(NSRect)aRect; +@end + +static NSString* const NSWindowDidChangeBackingPropertiesNotification = + @"NSWindowDidChangeBackingPropertiesNotification"; +static NSString* const NSBackingPropertyOldScaleFactorKey = + @"NSBackingPropertyOldScaleFactorKey"; + +#endif // MAC_OS_X_VERSION_10_7 + +// All CEF client applications must subclass NSApplication and implement this +// protocol. +@protocol CefAppProtocol +@end + +// Controls the state of |isHandlingSendEvent| in the event loop so that it is +// reset properly. +class CefScopedSendingEvent { + public: + CefScopedSendingEvent() + : app_(static_cast*>( + [NSApplication sharedApplication])), + handling_([app_ isHandlingSendEvent]) { + [app_ setHandlingSendEvent:YES]; + } + ~CefScopedSendingEvent() { + [app_ setHandlingSendEvent:handling_]; + } + + private: + NSApplication* app_; + BOOL handling_; +}; + +#endif // defined(OS_MACOSX) && defined(__OBJC__) + +#endif // CEF_INCLUDE_CEF_APPLICATION_MAC_H_ diff --git a/include/cef_auth_callback.h b/include/cef_auth_callback.h new file mode 100644 index 000000000..86d249ad3 --- /dev/null +++ b/include/cef_auth_callback.h @@ -0,0 +1,64 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ +#define CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Callback interface used for asynchronous continuation of authentication +// requests. +/// +/*--cef(source=library)--*/ +class CefAuthCallback : public virtual CefBase { + public: + /// + // Continue the authentication request. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue(const CefString& username, + const CefString& password) =0; + + /// + // Cancel the authentication request. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +#endif // CEF_INCLUDE_CEF_AUTH_CALLBACK_H_ diff --git a/include/cef_base.h b/include/cef_base.h new file mode 100644 index 000000000..c237b9e8d --- /dev/null +++ b/include/cef_base.h @@ -0,0 +1,180 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_CEF_BASE_H_ +#define CEF_INCLUDE_CEF_BASE_H_ +#pragma once + +#include "include/base/cef_atomic_ref_count.h" +#include "include/base/cef_build.h" +#include "include/base/cef_macros.h" + +// Bring in common C++ type definitions used by CEF consumers. +#include "include/internal/cef_ptr.h" +#include "include/internal/cef_types_wrappers.h" +#if defined(OS_WIN) +#include "include/internal/cef_win.h" +#elif defined(OS_MACOSX) +#include "include/internal/cef_mac.h" +#elif defined(OS_LINUX) +#include "include/internal/cef_linux.h" +#endif + +/// +// Interface defining the reference count implementation methods. All framework +// classes must extend the CefBase class. +/// +class CefBase { + public: + /// + // Called to increment the reference count for the object. Should be called + // for every new copy of a pointer to a given object. + /// + virtual void AddRef() const =0; + + /// + // Called to decrement the reference count for the object. Returns true if + // the reference count is 0, in which case the object should self-delete. + /// + virtual bool Release() const =0; + + /// + // Returns true if the reference count is 1. + /// + virtual bool HasOneRef() const =0; + + protected: + virtual ~CefBase() {} +}; + +/// +// Class that implements atomic reference counting. +/// +class CefRefCount { + public: + CefRefCount() : ref_count_(0) {} + + /// + // Increment the reference count. + /// + void AddRef() const { + base::AtomicRefCountInc(&ref_count_); + } + + /// + // Decrement the reference count. Returns true if the reference count is 0. + /// + bool Release() const { + return !base::AtomicRefCountDec(&ref_count_); + } + + /// + // Returns true if the reference count is 1. + /// + bool HasOneRef() const { + return base::AtomicRefCountIsOne(&ref_count_); + } + + private: + mutable base::AtomicRefCount ref_count_; + DISALLOW_COPY_AND_ASSIGN(CefRefCount); +}; + +/// +// Macro that provides a reference counting implementation for classes extending +// CefBase. +/// +#define IMPLEMENT_REFCOUNTING(ClassName) \ + public: \ + void AddRef() const { \ + ref_count_.AddRef(); \ + } \ + bool Release() const { \ + if (ref_count_.Release()) { \ + delete static_cast(this); \ + return true; \ + } \ + return false; \ + } \ + bool HasOneRef() const { \ + return ref_count_.HasOneRef(); \ + } \ + private: \ + CefRefCount ref_count_; + +/// +// Macro that provides a locking implementation. Use the Lock() and Unlock() +// methods to protect a section of code from simultaneous access by multiple +// threads. The AutoLock class is a helper that will hold the lock while in +// scope. +// +// THIS MACRO IS DEPRECATED. Use an explicit base::Lock member variable and +// base::AutoLock instead. For example: +// +// #include "include/base/cef_lock.h" +// +// // Class declaration. +// class MyClass : public CefBase { +// public: +// MyClass() : value_(0) {} +// // Method that may be called on multiple threads. +// void IncrementValue(); +// private: +// // Value that may be accessed on multiple theads. +// int value_; +// // Lock used to protect access to |value_|. +// base::Lock lock_; +// IMPLEMENT_REFCOUNTING(MyClass); +// }; +// +// // Class implementation. +// void MyClass::IncrementValue() { +// // Acquire the lock for the scope of this method. +// base::AutoLock lock_scope(lock_); +// // |value_| can now be modified safely. +// value_++; +// } +/// +#define IMPLEMENT_LOCKING(ClassName) \ + public: \ + class AutoLock { \ + public: \ + explicit AutoLock(ClassName* base) : base_(base) { base_->Lock(); } \ + ~AutoLock() { base_->Unlock(); } \ + private: \ + ClassName* base_; \ + DISALLOW_COPY_AND_ASSIGN(AutoLock); \ + }; \ + void Lock() { lock_.Acquire(); } \ + void Unlock() { lock_.Release(); } \ + private: \ + base::Lock lock_; + +#endif // CEF_INCLUDE_CEF_BASE_H_ diff --git a/include/cef_browser.h b/include/cef_browser.h new file mode 100644 index 000000000..653053f0e --- /dev/null +++ b/include/cef_browser.h @@ -0,0 +1,645 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_BROWSER_H_ +#define CEF_INCLUDE_CEF_BROWSER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_drag_data.h" +#include "include/cef_frame.h" +#include "include/cef_navigation_entry.h" +#include "include/cef_process_message.h" +#include "include/cef_request_context.h" +#include + +class CefBrowserHost; +class CefClient; + + +/// +// Class used to represent a browser window. When used in the browser process +// the methods of this class may be called on any thread unless otherwise +// indicated in the comments. When used in the render process the methods of +// this class may only be called on the main thread. +/// +/*--cef(source=library)--*/ +class CefBrowser : public virtual CefBase { + public: + /// + // Returns the browser host object. This method can only be called in the + // browser process. + /// + /*--cef()--*/ + virtual CefRefPtr GetHost() =0; + + /// + // Returns true if the browser can navigate backwards. + /// + /*--cef()--*/ + virtual bool CanGoBack() =0; + + /// + // Navigate backwards. + /// + /*--cef()--*/ + virtual void GoBack() =0; + + /// + // Returns true if the browser can navigate forwards. + /// + /*--cef()--*/ + virtual bool CanGoForward() =0; + + /// + // Navigate forwards. + /// + /*--cef()--*/ + virtual void GoForward() =0; + + /// + // Returns true if the browser is currently loading. + /// + /*--cef()--*/ + virtual bool IsLoading() =0; + + /// + // Reload the current page. + /// + /*--cef()--*/ + virtual void Reload() =0; + + /// + // Reload the current page ignoring any cached data. + /// + /*--cef()--*/ + virtual void ReloadIgnoreCache() =0; + + /// + // Stop loading the page. + /// + /*--cef()--*/ + virtual void StopLoad() =0; + + /// + // Returns the globally unique identifier for this browser. + /// + /*--cef()--*/ + virtual int GetIdentifier() =0; + + /// + // Returns true if this object is pointing to the same handle as |that| + // object. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr that) =0; + + /// + // Returns true if the window is a popup window. + /// + /*--cef()--*/ + virtual bool IsPopup() =0; + + /// + // Returns true if a document has been loaded in the browser. + /// + /*--cef()--*/ + virtual bool HasDocument() =0; + + /// + // Returns the main (top-level) frame for the browser window. + /// + /*--cef()--*/ + virtual CefRefPtr GetMainFrame() =0; + + /// + // Returns the focused frame for the browser window. + /// + /*--cef()--*/ + virtual CefRefPtr GetFocusedFrame() =0; + + /// + // Returns the frame with the specified identifier, or NULL if not found. + /// + /*--cef(capi_name=get_frame_byident)--*/ + virtual CefRefPtr GetFrame(int64 identifier) =0; + + /// + // Returns the frame with the specified name, or NULL if not found. + /// + /*--cef(optional_param=name)--*/ + virtual CefRefPtr GetFrame(const CefString& name) =0; + + /// + // Returns the number of frames that currently exist. + /// + /*--cef()--*/ + virtual size_t GetFrameCount() =0; + + /// + // Returns the identifiers of all existing frames. + /// + /*--cef(count_func=identifiers:GetFrameCount)--*/ + virtual void GetFrameIdentifiers(std::vector& identifiers) =0; + + /// + // Returns the names of all existing frames. + /// + /*--cef()--*/ + virtual void GetFrameNames(std::vector& names) =0; + + // + // Send a message to the specified |target_process|. Returns true if the + // message was sent successfully. + /// + /*--cef()--*/ + virtual bool SendProcessMessage(CefProcessId target_process, + CefRefPtr message) =0; +}; + + +/// +// Callback interface for CefBrowserHost::RunFileDialog. The methods of this +// class will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefRunFileDialogCallback : public virtual CefBase { + public: + /// + // Called asynchronously after the file dialog is dismissed. + // |selected_accept_filter| is the 0-based index of the value selected from + // the accept filters array passed to CefBrowserHost::RunFileDialog. + // |file_paths| will be a single value or a list of values depending on the + // dialog mode. If the selection was cancelled |file_paths| will be empty. + /// + /*--cef(index_param=selected_accept_filter,optional_param=file_paths)--*/ + virtual void OnFileDialogDismissed( + int selected_accept_filter, + const std::vector& file_paths) =0; +}; + + +/// +// Callback interface for CefBrowserHost::GetNavigationEntries. The methods of +// this class will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefNavigationEntryVisitor : public virtual CefBase { + public: + /// + // Method that will be executed. Do not keep a reference to |entry| outside of + // this callback. Return true to continue visiting entries or false to stop. + // |current| is true if this entry is the currently loaded navigation entry. + // |index| is the 0-based index of this entry and |total| is the total number + // of entries. + /// + /*--cef()--*/ + virtual bool Visit(CefRefPtr entry, + bool current, + int index, + int total) =0; +}; + + +/// +// Class used to represent the browser process aspects of a browser window. The +// methods of this class can only be called in the browser process. They may be +// called on any thread in that process unless otherwise indicated in the +// comments. +/// +/*--cef(source=library)--*/ +class CefBrowserHost : public virtual CefBase { + public: + typedef cef_drag_operations_mask_t DragOperationsMask; + typedef cef_file_dialog_mode_t FileDialogMode; + typedef cef_mouse_button_type_t MouseButtonType; + typedef cef_paint_element_type_t PaintElementType; + + /// + // Create a new browser window using the window parameters specified by + // |windowInfo|. All values will be copied internally and the actual window + // will be created on the UI thread. If |request_context| is empty the + // global request context will be used. This method can be called on any + // browser process thread and will not block. + /// + /*--cef(optional_param=client,optional_param=url, + optional_param=request_context)--*/ + static bool CreateBrowser(const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefRefPtr request_context); + + /// + // Create a new browser window using the window parameters specified by + // |windowInfo|. If |request_context| is empty the global request context + // will be used. This method can only be called on the browser process UI + // thread. + /// + /*--cef(optional_param=client,optional_param=url, + optional_param=request_context)--*/ + static CefRefPtr CreateBrowserSync( + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefRefPtr request_context); + + /// + // Returns the hosted browser object. + /// + /*--cef()--*/ + virtual CefRefPtr GetBrowser() =0; + + /// + // Request that the browser close. The JavaScript 'onbeforeunload' event will + // be fired. If |force_close| is false the event handler, if any, will be + // allowed to prompt the user and the user can optionally cancel the close. + // If |force_close| is true the prompt will not be displayed and the close + // will proceed. Results in a call to CefLifeSpanHandler::DoClose() if the + // event handler allows the close or if |force_close| is true. See + // CefLifeSpanHandler::DoClose() documentation for additional usage + // information. + /// + /*--cef()--*/ + virtual void CloseBrowser(bool force_close) =0; + + /// + // Set whether the browser is focused. + /// + /*--cef()--*/ + virtual void SetFocus(bool focus) =0; + + /// + // Set whether the window containing the browser is visible + // (minimized/unminimized, app hidden/unhidden, etc). Only used on Mac OS X. + /// + /*--cef()--*/ + virtual void SetWindowVisibility(bool visible) =0; + + /// + // Retrieve the window handle for this browser. + /// + /*--cef()--*/ + virtual CefWindowHandle GetWindowHandle() =0; + + /// + // Retrieve the window handle of the browser that opened this browser. Will + // return NULL for non-popup windows. This method can be used in combination + // with custom handling of modal windows. + /// + /*--cef()--*/ + virtual CefWindowHandle GetOpenerWindowHandle() =0; + + /// + // Returns the client for this browser. + /// + /*--cef()--*/ + virtual CefRefPtr GetClient() =0; + + /// + // Returns the request context for this browser. + /// + /*--cef()--*/ + virtual CefRefPtr GetRequestContext() =0; + + /// + // Get the current zoom level. The default zoom level is 0.0. This method can + // only be called on the UI thread. + /// + /*--cef()--*/ + virtual double GetZoomLevel() =0; + + /// + // Change the zoom level to the specified value. Specify 0.0 to reset the + // zoom level. If called on the UI thread the change will be applied + // immediately. Otherwise, the change will be applied asynchronously on the + // UI thread. + /// + /*--cef()--*/ + virtual void SetZoomLevel(double zoomLevel) =0; + + /// + // Call to run a file chooser dialog. Only a single file chooser dialog may be + // pending at any given time. |mode| represents the type of dialog to display. + // |title| to the title to be used for the dialog and may be empty to show the + // default title ("Open" or "Save" depending on the mode). |default_file_path| + // is the path with optional directory and/or file name component that will be + // initially selected in the dialog. |accept_filters| are used to restrict the + // selectable file types and may any combination of (a) valid lower-cased MIME + // types (e.g. "text/*" or "image/*"), (b) individual file extensions (e.g. + // ".txt" or ".png"), or (c) combined description and file extension delimited + // using "|" and ";" (e.g. "Image Types|.png;.gif;.jpg"). + // |selected_accept_filter| is the 0-based index of the filter that will be + // selected by default. |callback| will be executed after the dialog is + // dismissed or immediately if another dialog is already pending. The dialog + // will be initiated asynchronously on the UI thread. + /// + /*--cef(optional_param=title,optional_param=default_file_path, + optional_param=accept_filters,index_param=selected_accept_filter)--*/ + virtual void RunFileDialog(FileDialogMode mode, + const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, + int selected_accept_filter, + CefRefPtr callback) =0; + + /// + // Download the file at |url| using CefDownloadHandler. + /// + /*--cef()--*/ + virtual void StartDownload(const CefString& url) =0; + + /// + // Print the current browser contents. + /// + /*--cef()--*/ + virtual void Print() =0; + + /// + // Search for |searchText|. |identifier| can be used to have multiple searches + // running simultaniously. |forward| indicates whether to search forward or + // backward within the page. |matchCase| indicates whether the search should + // be case-sensitive. |findNext| indicates whether this is the first request + // or a follow-up. The CefFindHandler instance, if any, returned via + // CefClient::GetFindHandler will be called to report find results. + /// + /*--cef()--*/ + virtual void Find(int identifier, const CefString& searchText, + bool forward, bool matchCase, bool findNext) =0; + + /// + // Cancel all searches that are currently going on. + /// + /*--cef()--*/ + virtual void StopFinding(bool clearSelection) =0; + + /// + // Open developer tools in its own window. If |inspect_element_at| is non- + // empty the element at the specified (x,y) location will be inspected. + /// + /*--cef(optional_param=inspect_element_at)--*/ + virtual void ShowDevTools(const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) =0; + + /// + // Explicitly close the developer tools window if one exists for this browser + // instance. + /// + /*--cef()--*/ + virtual void CloseDevTools() =0; + + /// + // Retrieve a snapshot of current navigation entries as values sent to the + // specified visitor. If |current_only| is true only the current navigation + // entry will be sent, otherwise all navigation entries will be sent. + /// + /// + /*--cef()--*/ + virtual void GetNavigationEntries( + CefRefPtr visitor, + bool current_only) =0; + + /// + // Set whether mouse cursor change is disabled. + /// + /*--cef()--*/ + virtual void SetMouseCursorChangeDisabled(bool disabled) =0; + + /// + // Returns true if mouse cursor change is disabled. + /// + /*--cef()--*/ + virtual bool IsMouseCursorChangeDisabled() =0; + + /// + // If a misspelled word is currently selected in an editable node calling + // this method will replace it with the specified |word|. + /// + /*--cef()--*/ + virtual void ReplaceMisspelling(const CefString& word) =0; + + /// + // Add the specified |word| to the spelling dictionary. + /// + /*--cef()--*/ + virtual void AddWordToDictionary(const CefString& word) =0; + + /// + // Returns true if window rendering is disabled. + /// + /*--cef()--*/ + virtual bool IsWindowRenderingDisabled() =0; + + /// + // Notify the browser that the widget has been resized. The browser will first + // call CefRenderHandler::GetViewRect to get the new size and then call + // CefRenderHandler::OnPaint asynchronously with the updated regions. This + // method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void WasResized() =0; + + /// + // Notify the browser that it has been hidden or shown. Layouting and + // CefRenderHandler::OnPaint notification will stop when the browser is + // hidden. This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void WasHidden(bool hidden) =0; + + /// + // Send a notification to the browser that the screen info has changed. The + // browser will then call CefRenderHandler::GetScreenInfo to update the + // screen information with the new values. This simulates moving the webview + // window from one display to another, or changing the properties of the + // current display. This method is only used when window rendering is + // disabled. + /// + /*--cef()--*/ + virtual void NotifyScreenInfoChanged() =0; + + /// + // Invalidate the view. The browser will call CefRenderHandler::OnPaint + // asynchronously. This method is only used when window rendering is + // disabled. + /// + /*--cef()--*/ + virtual void Invalidate(PaintElementType type) =0; + + /// + // Send a key event to the browser. + /// + /*--cef()--*/ + virtual void SendKeyEvent(const CefKeyEvent& event) =0; + + /// + // Send a mouse click event to the browser. The |x| and |y| coordinates are + // relative to the upper-left corner of the view. + /// + /*--cef()--*/ + virtual void SendMouseClickEvent(const CefMouseEvent& event, + MouseButtonType type, + bool mouseUp, int clickCount) =0; + + /// + // Send a mouse move event to the browser. The |x| and |y| coordinates are + // relative to the upper-left corner of the view. + /// + /*--cef()--*/ + virtual void SendMouseMoveEvent(const CefMouseEvent& event, + bool mouseLeave) =0; + + /// + // Send a mouse wheel event to the browser. The |x| and |y| coordinates are + // relative to the upper-left corner of the view. The |deltaX| and |deltaY| + // values represent the movement delta in the X and Y directions respectively. + // In order to scroll inside select popups with window rendering disabled + // CefRenderHandler::GetScreenPoint should be implemented properly. + /// + /*--cef()--*/ + virtual void SendMouseWheelEvent(const CefMouseEvent& event, + int deltaX, int deltaY) =0; + + /// + // Send a focus event to the browser. + /// + /*--cef()--*/ + virtual void SendFocusEvent(bool setFocus) =0; + + /// + // Send a capture lost event to the browser. + /// + /*--cef()--*/ + virtual void SendCaptureLostEvent() =0; + + /// + // Notify the browser that the window hosting it is about to be moved or + // resized. This method is only used on Windows and Linux. + /// + /*--cef()--*/ + virtual void NotifyMoveOrResizeStarted() =0; + + /// + // Get the NSTextInputContext implementation for enabling IME on Mac when + // window rendering is disabled. + /// + /*--cef(default_retval=NULL)--*/ + virtual CefTextInputContext GetNSTextInputContext() =0; + + /// + // Handles a keyDown event prior to passing it through the NSTextInputClient + // machinery. + /// + /*--cef()--*/ + virtual void HandleKeyEventBeforeTextInputClient(CefEventHandle keyEvent) =0; + + /// + // Performs any additional actions after NSTextInputClient handles the event. + /// + /*--cef()--*/ + virtual void HandleKeyEventAfterTextInputClient(CefEventHandle keyEvent) =0; + + /// + // Call this method when the user drags the mouse into the web view (before + // calling DragTargetDragOver/DragTargetLeave/DragTargetDrop). + // |drag_data| should not contain file contents as this type of data is not + // allowed to be dragged into the web view. File contents can be removed using + // CefDragData::ResetFileContents (for example, if |drag_data| comes from + // CefRenderHandler::StartDragging). + // This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void DragTargetDragEnter(CefRefPtr drag_data, + const CefMouseEvent& event, + DragOperationsMask allowed_ops) =0; + + /// + // Call this method each time the mouse is moved across the web view during + // a drag operation (after calling DragTargetDragEnter and before calling + // DragTargetDragLeave/DragTargetDrop). + // This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void DragTargetDragOver(const CefMouseEvent& event, + DragOperationsMask allowed_ops) =0; + + /// + // Call this method when the user drags the mouse out of the web view (after + // calling DragTargetDragEnter). + // This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void DragTargetDragLeave() =0; + + /// + // Call this method when the user completes the drag operation by dropping + // the object onto the web view (after calling DragTargetDragEnter). + // The object being dropped is |drag_data|, given as an argument to + // the previous DragTargetDragEnter call. + // This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void DragTargetDrop(const CefMouseEvent& event) =0; + + /// + // Call this method when the drag operation started by a + // CefRenderHandler::StartDragging call has ended either in a drop or + // by being cancelled. |x| and |y| are mouse coordinates relative to the + // upper-left corner of the view. If the web view is both the drag source + // and the drag target then all DragTarget* methods should be called before + // DragSource* mthods. + // This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void DragSourceEndedAt(int x, int y, DragOperationsMask op) =0; + + /// + // Call this method when the drag operation started by a + // CefRenderHandler::StartDragging call has completed. This method may be + // called immediately without first calling DragSourceEndedAt to cancel a + // drag operation. If the web view is both the drag source and the drag + // target then all DragTarget* methods should be called before DragSource* + // mthods. + // This method is only used when window rendering is disabled. + /// + /*--cef()--*/ + virtual void DragSourceSystemDragEnded() =0; +}; + +#endif // CEF_INCLUDE_CEF_BROWSER_H_ diff --git a/include/cef_browser_process_handler.h b/include/cef_browser_process_handler.h new file mode 100644 index 000000000..5d62cb30c --- /dev/null +++ b/include/cef_browser_process_handler.h @@ -0,0 +1,92 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_BROWSER_PROCESS_HANDLER_H_ +#define CEF_INCLUDE_CEF_BROWSER_PROCESS_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_command_line.h" +#include "include/cef_print_handler.h" +#include "include/cef_values.h" + +/// +// Class used to implement browser process callbacks. The methods of this class +// will be called on the browser process main thread unless otherwise indicated. +/// +/*--cef(source=client)--*/ +class CefBrowserProcessHandler : public virtual CefBase { + public: + /// + // Called on the browser process UI thread immediately after the CEF context + // has been initialized. + /// + /*--cef()--*/ + virtual void OnContextInitialized() {} + + /// + // Called before a child process is launched. Will be called on the browser + // process UI thread when launching a render process and on the browser + // process IO thread when launching a GPU or plugin process. Provides an + // opportunity to modify the child process command line. Do not keep a + // reference to |command_line| outside of this method. + /// + /*--cef()--*/ + virtual void OnBeforeChildProcessLaunch( + CefRefPtr command_line) {} + + /// + // Called on the browser process IO thread after the main thread has been + // created for a new render process. Provides an opportunity to specify extra + // information that will be passed to + // CefRenderProcessHandler::OnRenderThreadCreated() in the render process. Do + // not keep a reference to |extra_info| outside of this method. + /// + /*--cef()--*/ + virtual void OnRenderProcessThreadCreated( + CefRefPtr extra_info) {} + + /// + // Return the handler for printing on Linux. If a print handler is not + // provided then printing will not be supported on the Linux platform. + /// + /*--cef()--*/ + virtual CefRefPtr GetPrintHandler() { + return NULL; + } +}; + +#endif // CEF_INCLUDE_CEF_BROWSER_PROCESS_HANDLER_H_ diff --git a/include/cef_callback.h b/include/cef_callback.h new file mode 100644 index 000000000..e5efebd2d --- /dev/null +++ b/include/cef_callback.h @@ -0,0 +1,75 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_CALLBACK_H_ +#define CEF_INCLUDE_CEF_CALLBACK_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Generic callback interface used for asynchronous continuation. +/// +/*--cef(source=library)--*/ +class CefCallback : public virtual CefBase { + public: + /// + // Continue processing. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue() =0; + + /// + // Cancel processing. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +/// +// Generic callback interface used for asynchronous completion. +/// +/*--cef(source=client)--*/ +class CefCompletionCallback : public virtual CefBase { + public: + /// + // Method that will be called once the task is complete. + /// + /*--cef()--*/ + virtual void OnComplete() =0; +}; + +#endif // CEF_INCLUDE_CEF_CALLBACK_H_ diff --git a/include/cef_client.h b/include/cef_client.h new file mode 100644 index 000000000..81a67ebae --- /dev/null +++ b/include/cef_client.h @@ -0,0 +1,194 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_CLIENT_H_ +#define CEF_INCLUDE_CEF_CLIENT_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_context_menu_handler.h" +#include "include/cef_dialog_handler.h" +#include "include/cef_display_handler.h" +#include "include/cef_download_handler.h" +#include "include/cef_drag_handler.h" +#include "include/cef_find_handler.h" +#include "include/cef_focus_handler.h" +#include "include/cef_geolocation_handler.h" +#include "include/cef_jsdialog_handler.h" +#include "include/cef_keyboard_handler.h" +#include "include/cef_life_span_handler.h" +#include "include/cef_load_handler.h" +#include "include/cef_process_message.h" +#include "include/cef_render_handler.h" +#include "include/cef_request_handler.h" + +/// +// Implement this interface to provide handler implementations. +/// +/*--cef(source=client,no_debugct_check)--*/ +class CefClient : public virtual CefBase { + public: + /// + // Return the handler for context menus. If no handler is provided the default + // implementation will be used. + /// + /*--cef()--*/ + virtual CefRefPtr GetContextMenuHandler() { + return NULL; + } + + /// + // Return the handler for dialogs. If no handler is provided the default + // implementation will be used. + /// + /*--cef()--*/ + virtual CefRefPtr GetDialogHandler() { + return NULL; + } + + /// + // Return the handler for browser display state events. + /// + /*--cef()--*/ + virtual CefRefPtr GetDisplayHandler() { + return NULL; + } + + /// + // Return the handler for download events. If no handler is returned downloads + // will not be allowed. + /// + /*--cef()--*/ + virtual CefRefPtr GetDownloadHandler() { + return NULL; + } + + /// + // Return the handler for drag events. + /// + /*--cef()--*/ + virtual CefRefPtr GetDragHandler() { + return NULL; + } + + /// + // Return the handler for find result events. + /// + /*--cef()--*/ + virtual CefRefPtr GetFindHandler() { + return NULL; + } + + /// + // Return the handler for focus events. + /// + /*--cef()--*/ + virtual CefRefPtr GetFocusHandler() { + return NULL; + } + + /// + // Return the handler for geolocation permissions requests. If no handler is + // provided geolocation access will be denied by default. + /// + /*--cef()--*/ + virtual CefRefPtr GetGeolocationHandler() { + return NULL; + } + + /// + // Return the handler for JavaScript dialogs. If no handler is provided the + // default implementation will be used. + /// + /*--cef()--*/ + virtual CefRefPtr GetJSDialogHandler() { + return NULL; + } + + /// + // Return the handler for keyboard events. + /// + /*--cef()--*/ + virtual CefRefPtr GetKeyboardHandler() { + return NULL; + } + + /// + // Return the handler for browser life span events. + /// + /*--cef()--*/ + virtual CefRefPtr GetLifeSpanHandler() { + return NULL; + } + + /// + // Return the handler for browser load status events. + /// + /*--cef()--*/ + virtual CefRefPtr GetLoadHandler() { + return NULL; + } + + /// + // Return the handler for off-screen rendering events. + /// + /*--cef()--*/ + virtual CefRefPtr GetRenderHandler() { + return NULL; + } + + /// + // Return the handler for browser request events. + /// + /*--cef()--*/ + virtual CefRefPtr GetRequestHandler() { + return NULL; + } + + /// + // Called when a new message is received from a different process. Return true + // if the message was handled or false otherwise. Do not keep a reference to + // or attempt to access the message outside of this callback. + /// + /*--cef()--*/ + virtual bool OnProcessMessageReceived(CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) { + return false; + } +}; + +#endif // CEF_INCLUDE_CEF_CLIENT_H_ diff --git a/include/cef_command_line.h b/include/cef_command_line.h new file mode 100644 index 000000000..96241cf43 --- /dev/null +++ b/include/cef_command_line.h @@ -0,0 +1,208 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_COMMAND_LINE_H_ +#define CEF_INCLUDE_CEF_COMMAND_LINE_H_ +#pragma once + +#include "include/cef_base.h" +#include +#include + +/// +// Class used to create and/or parse command line arguments. Arguments with +// '--', '-' and, on Windows, '/' prefixes are considered switches. Switches +// will always precede any arguments without switch prefixes. Switches can +// optionally have a value specified using the '=' delimiter (e.g. +// "-switch=value"). An argument of "--" will terminate switch parsing with all +// subsequent tokens, regardless of prefix, being interpreted as non-switch +// arguments. Switch names are considered case-insensitive. This class can be +// used before CefInitialize() is called. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefCommandLine : public virtual CefBase { + public: + typedef std::vector ArgumentList; + typedef std::map SwitchMap; + + /// + // Create a new CefCommandLine instance. + /// + /*--cef(api_hash_check)--*/ + static CefRefPtr CreateCommandLine(); + + /// + // Returns the singleton global CefCommandLine object. The returned object + // will be read-only. + /// + /*--cef(api_hash_check)--*/ + static CefRefPtr GetGlobalCommandLine(); + + /// + // Returns true if this object is valid. Do not call any other methods if this + // function returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns a writable copy of this object. + /// + /*--cef()--*/ + virtual CefRefPtr Copy() =0; + + /// + // Initialize the command line with the specified |argc| and |argv| values. + // The first argument must be the name of the program. This method is only + // supported on non-Windows platforms. + /// + /*--cef()--*/ + virtual void InitFromArgv(int argc, const char* const* argv) =0; + + /// + // Initialize the command line with the string returned by calling + // GetCommandLineW(). This method is only supported on Windows. + /// + /*--cef()--*/ + virtual void InitFromString(const CefString& command_line) =0; + + /// + // Reset the command-line switches and arguments but leave the program + // component unchanged. + /// + /*--cef()--*/ + virtual void Reset() =0; + + /// + // Retrieve the original command line string as a vector of strings. + // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* } + /// + /*--cef()--*/ + virtual void GetArgv(std::vector& argv) =0; + + /// + // Constructs and returns the represented command line string. Use this method + // cautiously because quoting behavior is unclear. + /// + /*--cef()--*/ + virtual CefString GetCommandLineString() =0; + + /// + // Get the program part of the command line string (the first item). + /// + /*--cef()--*/ + virtual CefString GetProgram() =0; + + /// + // Set the program part of the command line string (the first item). + /// + /*--cef()--*/ + virtual void SetProgram(const CefString& program) =0; + + /// + // Returns true if the command line has switches. + /// + /*--cef()--*/ + virtual bool HasSwitches() =0; + + /// + // Returns true if the command line contains the given switch. + /// + /*--cef()--*/ + virtual bool HasSwitch(const CefString& name) =0; + + /// + // Returns the value associated with the given switch. If the switch has no + // value or isn't present this method returns the empty string. + /// + /*--cef()--*/ + virtual CefString GetSwitchValue(const CefString& name) =0; + + /// + // Returns the map of switch names and values. If a switch has no value an + // empty string is returned. + /// + /*--cef()--*/ + virtual void GetSwitches(SwitchMap& switches) =0; + + /// + // Add a switch to the end of the command line. If the switch has no value + // pass an empty value string. + /// + /*--cef()--*/ + virtual void AppendSwitch(const CefString& name) =0; + + /// + // Add a switch with the specified value to the end of the command line. + /// + /*--cef()--*/ + virtual void AppendSwitchWithValue(const CefString& name, + const CefString& value) =0; + + /// + // True if there are remaining command line arguments. + /// + /*--cef()--*/ + virtual bool HasArguments() =0; + + /// + // Get the remaining command line arguments. + /// + /*--cef()--*/ + virtual void GetArguments(ArgumentList& arguments) =0; + + /// + // Add an argument to the end of the command line. + /// + /*--cef()--*/ + virtual void AppendArgument(const CefString& argument) =0; + + /// + // Insert a command before the current command. + // Common for debuggers, like "valgrind" or "gdb --args". + /// + /*--cef()--*/ + virtual void PrependWrapper(const CefString& wrapper) =0; +}; + +#endif // CEF_INCLUDE_CEF_COMMAND_LINE_H_ diff --git a/include/cef_context_menu_handler.h b/include/cef_context_menu_handler.h new file mode 100644 index 000000000..f841722de --- /dev/null +++ b/include/cef_context_menu_handler.h @@ -0,0 +1,238 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_CONTEXT_MENU_HANDLER_H_ +#define CEF_INCLUDE_CEF_CONTEXT_MENU_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_menu_model.h" + +class CefContextMenuParams; + +/// +// Implement this interface to handle context menu events. The methods of this +// class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefContextMenuHandler : public virtual CefBase { + public: + typedef cef_event_flags_t EventFlags; + + /// + // Called before a context menu is displayed. |params| provides information + // about the context menu state. |model| initially contains the default + // context menu. The |model| can be cleared to show no context menu or + // modified to show a custom menu. Do not keep references to |params| or + // |model| outside of this callback. + /// + /*--cef()--*/ + virtual void OnBeforeContextMenu(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + CefRefPtr model) {} + + /// + // Called to execute a command selected from the context menu. Return true if + // the command was handled or false for the default implementation. See + // cef_menu_id_t for the command ids that have default implementations. All + // user-defined command ids should be between MENU_ID_USER_FIRST and + // MENU_ID_USER_LAST. |params| will have the same values as what was passed to + // OnBeforeContextMenu(). Do not keep a reference to |params| outside of this + // callback. + /// + /*--cef()--*/ + virtual bool OnContextMenuCommand(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + int command_id, + EventFlags event_flags) { return false; } + + /// + // Called when the context menu is dismissed irregardless of whether the menu + // was empty or a command was selected. + /// + /*--cef()--*/ + virtual void OnContextMenuDismissed(CefRefPtr browser, + CefRefPtr frame) {} +}; + + +/// +// Provides information about the context menu state. The ethods of this class +// can only be accessed on browser process the UI thread. +/// +/*--cef(source=library)--*/ +class CefContextMenuParams : public virtual CefBase { + public: + typedef cef_context_menu_type_flags_t TypeFlags; + typedef cef_context_menu_media_type_t MediaType; + typedef cef_context_menu_media_state_flags_t MediaStateFlags; + typedef cef_context_menu_edit_state_flags_t EditStateFlags; + + /// + // Returns the X coordinate of the mouse where the context menu was invoked. + // Coords are relative to the associated RenderView's origin. + /// + /*--cef()--*/ + virtual int GetXCoord() =0; + + /// + // Returns the Y coordinate of the mouse where the context menu was invoked. + // Coords are relative to the associated RenderView's origin. + /// + /*--cef()--*/ + virtual int GetYCoord() =0; + + /// + // Returns flags representing the type of node that the context menu was + // invoked on. + /// + /*--cef(default_retval=CM_TYPEFLAG_NONE)--*/ + virtual TypeFlags GetTypeFlags() =0; + + /// + // Returns the URL of the link, if any, that encloses the node that the + // context menu was invoked on. + /// + /*--cef()--*/ + virtual CefString GetLinkUrl() =0; + + /// + // Returns the link URL, if any, to be used ONLY for "copy link address". We + // don't validate this field in the frontend process. + /// + /*--cef()--*/ + virtual CefString GetUnfilteredLinkUrl() =0; + + /// + // Returns the source URL, if any, for the element that the context menu was + // invoked on. Example of elements with source URLs are img, audio, and video. + /// + /*--cef()--*/ + virtual CefString GetSourceUrl() =0; + + /// + // Returns true if the context menu was invoked on an image which has + // non-empty contents. + /// + /*--cef()--*/ + virtual bool HasImageContents() =0; + + /// + // Returns the URL of the top level page that the context menu was invoked on. + /// + /*--cef()--*/ + virtual CefString GetPageUrl() =0; + + /// + // Returns the URL of the subframe that the context menu was invoked on. + /// + /*--cef()--*/ + virtual CefString GetFrameUrl() =0; + + /// + // Returns the character encoding of the subframe that the context menu was + // invoked on. + /// + /*--cef()--*/ + virtual CefString GetFrameCharset() =0; + + /// + // Returns the type of context node that the context menu was invoked on. + /// + /*--cef(default_retval=CM_MEDIATYPE_NONE)--*/ + virtual MediaType GetMediaType() =0; + + /// + // Returns flags representing the actions supported by the media element, if + // any, that the context menu was invoked on. + /// + /*--cef(default_retval=CM_MEDIAFLAG_NONE)--*/ + virtual MediaStateFlags GetMediaStateFlags() =0; + + /// + // Returns the text of the selection, if any, that the context menu was + // invoked on. + /// + /*--cef()--*/ + virtual CefString GetSelectionText() =0; + + /// + // Returns the text of the misspelled word, if any, that the context menu was + // invoked on. + /// + /*--cef()--*/ + virtual CefString GetMisspelledWord() =0; + + /// + // Returns the hash of the misspelled word, if any, that the context menu was + // invoked on. + /// + /*--cef()--*/ + virtual int GetMisspellingHash() =0; + + /// + // Returns true if suggestions exist, false otherwise. Fills in |suggestions| + // from the spell check service for the misspelled word if there is one. + /// + /*--cef()--*/ + virtual bool GetDictionarySuggestions(std::vector& suggestions) =0; + + /// + // Returns true if the context menu was invoked on an editable node. + /// + /*--cef()--*/ + virtual bool IsEditable() =0; + + /// + // Returns true if the context menu was invoked on an editable node where + // spell-check is enabled. + /// + /*--cef()--*/ + virtual bool IsSpellCheckEnabled() =0; + + /// + // Returns flags representing the actions supported by the editable node, if + // any, that the context menu was invoked on. + /// + /*--cef(default_retval=CM_EDITFLAG_NONE)--*/ + virtual EditStateFlags GetEditStateFlags() =0; +}; + +#endif // CEF_INCLUDE_CEF_CONTEXT_MENU_HANDLER_H_ diff --git a/include/cef_cookie.h b/include/cef_cookie.h new file mode 100644 index 000000000..73506dc46 --- /dev/null +++ b/include/cef_cookie.h @@ -0,0 +1,166 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_COOKIE_H_ +#define CEF_INCLUDE_CEF_COOKIE_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_callback.h" +#include + +class CefCookieVisitor; + + +/// +// Class used for managing cookies. The methods of this class may be called on +// any thread unless otherwise indicated. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefCookieManager : public virtual CefBase { + public: + /// + // Returns the global cookie manager. By default data will be stored at + // CefSettings.cache_path if specified or in memory otherwise. + /// + /*--cef()--*/ + static CefRefPtr GetGlobalManager(); + + /// + // Creates a new cookie manager. If |path| is empty data will be stored in + // memory only. Otherwise, data will be stored at the specified |path|. To + // persist session cookies (cookies without an expiry date or validity + // interval) set |persist_session_cookies| to true. Session cookies are + // generally intended to be transient and most Web browsers do not persist + // them. Returns NULL if creation fails. + /// + /*--cef(optional_param=path)--*/ + static CefRefPtr CreateManager( + const CefString& path, + bool persist_session_cookies); + + /// + // Set the schemes supported by this manager. By default only "http" and + // "https" schemes are supported. Must be called before any cookies are + // accessed. + /// + /*--cef()--*/ + virtual void SetSupportedSchemes(const std::vector& schemes) =0; + + /// + // Visit all cookies. The returned cookies are ordered by longest path, then + // by earliest creation date. Returns false if cookies cannot be accessed. + /// + /*--cef()--*/ + virtual bool VisitAllCookies(CefRefPtr visitor) =0; + + /// + // Visit a subset of cookies. The results are filtered by the given url + // scheme, host, domain and path. If |includeHttpOnly| is true HTTP-only + // cookies will also be included in the results. The returned cookies are + // ordered by longest path, then by earliest creation date. Returns false if + // cookies cannot be accessed. + /// + /*--cef()--*/ + virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, + CefRefPtr visitor) =0; + + /// + // Sets a cookie given a valid URL and explicit user-provided cookie + // attributes. This function expects each attribute to be well-formed. It will + // check for disallowed characters (e.g. the ';' character is disallowed + // within the cookie value attribute) and will return false without setting + // the cookie if such characters are found. This method must be called on the + // IO thread. + /// + /*--cef()--*/ + virtual bool SetCookie(const CefString& url, const CefCookie& cookie) =0; + + /// + // Delete all cookies that match the specified parameters. If both |url| and + // values |cookie_name| are specified all host and domain cookies matching + // both will be deleted. If only |url| is specified all host cookies (but not + // domain cookies) irrespective of path will be deleted. If |url| is empty all + // cookies for all hosts and domains will be deleted. Returns false if a non- + // empty invalid URL is specified or if cookies cannot be accessed. This + // method must be called on the IO thread. + /// + /*--cef(optional_param=url,optional_param=cookie_name)--*/ + virtual bool DeleteCookies(const CefString& url, + const CefString& cookie_name) =0; + + /// + // Sets the directory path that will be used for storing cookie data. If + // |path| is empty data will be stored in memory only. Otherwise, data will be + // stored at the specified |path|. To persist session cookies (cookies without + // an expiry date or validity interval) set |persist_session_cookies| to true. + // Session cookies are generally intended to be transient and most Web browsers + // do not persist them. Returns false if cookies cannot be accessed. + /// + /*--cef(optional_param=path)--*/ + virtual bool SetStoragePath(const CefString& path, + bool persist_session_cookies) =0; + + /// + // Flush the backing store (if any) to disk and execute the specified + // |callback| on the IO thread when done. Returns false if cookies cannot be + // accessed. + /// + /*--cef(optional_param=handler)--*/ + virtual bool FlushStore(CefRefPtr callback) =0; +}; + + +/// +// Interface to implement for visiting cookie values. The methods of this class +// will always be called on the IO thread. +/// +/*--cef(source=client)--*/ +class CefCookieVisitor : public virtual CefBase { + public: + /// + // Method that will be called once for each cookie. |count| is the 0-based + // index for the current cookie. |total| is the total number of cookies. + // Set |deleteCookie| to true to delete the cookie currently being visited. + // Return false to stop visiting cookies. This method may never be called if + // no cookies are found. + /// + /*--cef()--*/ + virtual bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) =0; +}; + +#endif // CEF_INCLUDE_CEF_COOKIE_H_ diff --git a/include/cef_dialog_handler.h b/include/cef_dialog_handler.h new file mode 100644 index 000000000..93cd5de7c --- /dev/null +++ b/include/cef_dialog_handler.h @@ -0,0 +1,107 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DIALOG_HANDLER_H_ +#define CEF_INCLUDE_CEF_DIALOG_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Callback interface for asynchronous continuation of file dialog requests. +/// +/*--cef(source=library)--*/ +class CefFileDialogCallback : public virtual CefBase { + public: + /// + // Continue the file selection. |selected_accept_filter| should be the 0-based + // index of the value selected from the accept filters array passed to + // CefDialogHandler::OnFileDialog. |file_paths| should be a single value or a + // list of values depending on the dialog mode. An empty |file_paths| value is + // treated the same as calling Cancel(). + /// + /*--cef(capi_name=cont,index_param=selected_accept_filter, + optional_param=file_paths)--*/ + virtual void Continue(int selected_accept_filter, + const std::vector& file_paths) =0; + + /// + // Cancel the file selection. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + + +/// +// Implement this interface to handle dialog events. The methods of this class +// will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefDialogHandler : public virtual CefBase { + public: + typedef cef_file_dialog_mode_t FileDialogMode; + + /// + // Called to run a file chooser dialog. |mode| represents the type of dialog + // to display. |title| to the title to be used for the dialog and may be empty + // to show the default title ("Open" or "Save" depending on the mode). + // |default_file_path| is the path with optional directory and/or file name + // component that should be initially selected in the dialog. |accept_filters| + // are used to restrict the selectable file types and may any combination of + // (a) valid lower-cased MIME types (e.g. "text/*" or "image/*"), + // (b) individual file extensions (e.g. ".txt" or ".png"), or (c) combined + // description and file extension delimited using "|" and ";" (e.g. + // "Image Types|.png;.gif;.jpg"). |selected_accept_filter| is the 0-based + // index of the filter that should be selected by default. To display a custom + // dialog return true and execute |callback| either inline or at a later time. + // To display the default dialog return false. + /// + /*--cef(optional_param=title,optional_param=default_file_path, + optional_param=accept_filters,index_param=selected_accept_filter)--*/ + virtual bool OnFileDialog(CefRefPtr browser, + FileDialogMode mode, + const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, + int selected_accept_filter, + CefRefPtr callback) { + return false; + } +}; + +#endif // CEF_INCLUDE_CEF_DIALOG_HANDLER_H_ diff --git a/include/cef_display_handler.h b/include/cef_display_handler.h new file mode 100644 index 000000000..69917886f --- /dev/null +++ b/include/cef_display_handler.h @@ -0,0 +1,105 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DISPLAY_HANDLER_H_ +#define CEF_INCLUDE_CEF_DISPLAY_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" + +/// +// Implement this interface to handle events related to browser display state. +// The methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefDisplayHandler : public virtual CefBase { + public: + /// + // Called when a frame's address has changed. + /// + /*--cef()--*/ + virtual void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) {} + + /// + // Called when the page title changes. + /// + /*--cef(optional_param=title)--*/ + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) {} + + /// + // Called when the page icon changes. + /// + /*--cef(optional_param=icon_urls)--*/ + virtual void OnFaviconURLChange(CefRefPtr browser, + const std::vector& icon_urls) {} + + /// + // Called when the browser is about to display a tooltip. |text| contains the + // text that will be displayed in the tooltip. To handle the display of the + // tooltip yourself return true. Otherwise, you can optionally modify |text| + // and then return false to allow the browser to display the tooltip. + // When window rendering is disabled the application is responsible for + // drawing tooltips and the return value is ignored. + /// + /*--cef(optional_param=text)--*/ + virtual bool OnTooltip(CefRefPtr browser, + CefString& text) { return false; } + + /// + // Called when the browser receives a status message. |value| contains the + // text that will be displayed in the status message. + /// + /*--cef(optional_param=value)--*/ + virtual void OnStatusMessage(CefRefPtr browser, + const CefString& value) {} + + /// + // Called to display a console message. Return true to stop the message from + // being output to the console. + /// + /*--cef(optional_param=message,optional_param=source)--*/ + virtual bool OnConsoleMessage(CefRefPtr browser, + const CefString& message, + const CefString& source, + int line) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_DISPLAY_HANDLER_H_ diff --git a/include/cef_dom.h b/include/cef_dom.h new file mode 100644 index 000000000..9f9a3d5ae --- /dev/null +++ b/include/cef_dom.h @@ -0,0 +1,328 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DOM_H_ +#define CEF_INCLUDE_CEF_DOM_H_ +#pragma once + +#include "include/cef_base.h" +#include + +class CefDOMDocument; +class CefDOMNode; + +/// +// Interface to implement for visiting the DOM. The methods of this class will +// be called on the render process main thread. +/// +/*--cef(source=client)--*/ +class CefDOMVisitor : public virtual CefBase { + public: + /// + // Method executed for visiting the DOM. The document object passed to this + // method represents a snapshot of the DOM at the time this method is + // executed. DOM objects are only valid for the scope of this method. Do not + // keep references to or attempt to access any DOM objects outside the scope + // of this method. + /// + /*--cef()--*/ + virtual void Visit(CefRefPtr document) =0; +}; + + +/// +// Class used to represent a DOM document. The methods of this class should only +// be called on the render process main thread thread. +/// +/*--cef(source=library)--*/ +class CefDOMDocument : public virtual CefBase { + public: + typedef cef_dom_document_type_t Type; + + /// + // Returns the document type. + /// + /*--cef(default_retval=DOM_DOCUMENT_TYPE_UNKNOWN)--*/ + virtual Type GetType() =0; + + /// + // Returns the root document node. + /// + /*--cef()--*/ + virtual CefRefPtr GetDocument() =0; + + /// + // Returns the BODY node of an HTML document. + /// + /*--cef()--*/ + virtual CefRefPtr GetBody() =0; + + /// + // Returns the HEAD node of an HTML document. + /// + /*--cef()--*/ + virtual CefRefPtr GetHead() =0; + + /// + // Returns the title of an HTML document. + /// + /*--cef()--*/ + virtual CefString GetTitle() =0; + + /// + // Returns the document element with the specified ID value. + /// + /*--cef()--*/ + virtual CefRefPtr GetElementById(const CefString& id) =0; + + /// + // Returns the node that currently has keyboard focus. + /// + /*--cef()--*/ + virtual CefRefPtr GetFocusedNode() =0; + + /// + // Returns true if a portion of the document is selected. + /// + /*--cef()--*/ + virtual bool HasSelection() =0; + + /// + // Returns the selection offset within the start node. + /// + /*--cef()--*/ + virtual int GetSelectionStartOffset() =0; + + /// + // Returns the selection offset within the end node. + /// + /*--cef()--*/ + virtual int GetSelectionEndOffset() =0; + + /// + // Returns the contents of this selection as markup. + /// + /*--cef()--*/ + virtual CefString GetSelectionAsMarkup() =0; + + /// + // Returns the contents of this selection as text. + /// + /*--cef()--*/ + virtual CefString GetSelectionAsText() =0; + + /// + // Returns the base URL for the document. + /// + /*--cef()--*/ + virtual CefString GetBaseURL() =0; + + /// + // Returns a complete URL based on the document base URL and the specified + // partial URL. + /// + /*--cef()--*/ + virtual CefString GetCompleteURL(const CefString& partialURL) =0; +}; + + +/// +// Class used to represent a DOM node. The methods of this class should only be +// called on the render process main thread. +/// +/*--cef(source=library)--*/ +class CefDOMNode : public virtual CefBase { + public: + typedef std::map AttributeMap; + typedef cef_dom_node_type_t Type; + + /// + // Returns the type for this node. + /// + /*--cef(default_retval=DOM_NODE_TYPE_UNSUPPORTED)--*/ + virtual Type GetType() =0; + + /// + // Returns true if this is a text node. + /// + /*--cef()--*/ + virtual bool IsText() =0; + + /// + // Returns true if this is an element node. + /// + /*--cef()--*/ + virtual bool IsElement() =0; + + /// + // Returns true if this is an editable node. + /// + /*--cef()--*/ + virtual bool IsEditable() =0; + + /// + // Returns true if this is a form control element node. + /// + /*--cef()--*/ + virtual bool IsFormControlElement() =0; + + /// + // Returns the type of this form control element node. + /// + /*--cef()--*/ + virtual CefString GetFormControlElementType() =0; + + /// + // Returns true if this object is pointing to the same handle as |that| + // object. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr that) =0; + + /// + // Returns the name of this node. + /// + /*--cef()--*/ + virtual CefString GetName() =0; + + /// + // Returns the value of this node. + /// + /*--cef()--*/ + virtual CefString GetValue() =0; + + /// + // Set the value of this node. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetValue(const CefString& value) =0; + + /// + // Returns the contents of this node as markup. + /// + /*--cef()--*/ + virtual CefString GetAsMarkup() =0; + + /// + // Returns the document associated with this node. + /// + /*--cef()--*/ + virtual CefRefPtr GetDocument() =0; + + /// + // Returns the parent node. + /// + /*--cef()--*/ + virtual CefRefPtr GetParent() =0; + + /// + // Returns the previous sibling node. + /// + /*--cef()--*/ + virtual CefRefPtr GetPreviousSibling() =0; + + /// + // Returns the next sibling node. + /// + /*--cef()--*/ + virtual CefRefPtr GetNextSibling() =0; + + /// + // Returns true if this node has child nodes. + /// + /*--cef()--*/ + virtual bool HasChildren() =0; + + /// + // Return the first child node. + /// + /*--cef()--*/ + virtual CefRefPtr GetFirstChild() =0; + + /// + // Returns the last child node. + /// + /*--cef()--*/ + virtual CefRefPtr GetLastChild() =0; + + // The following methods are valid only for element nodes. + + /// + // Returns the tag name of this element. + /// + /*--cef()--*/ + virtual CefString GetElementTagName() =0; + + /// + // Returns true if this element has attributes. + /// + /*--cef()--*/ + virtual bool HasElementAttributes() =0; + + /// + // Returns true if this element has an attribute named |attrName|. + /// + /*--cef()--*/ + virtual bool HasElementAttribute(const CefString& attrName) =0; + + /// + // Returns the element attribute named |attrName|. + /// + /*--cef()--*/ + virtual CefString GetElementAttribute(const CefString& attrName) =0; + + /// + // Returns a map of all element attributes. + /// + /*--cef()--*/ + virtual void GetElementAttributes(AttributeMap& attrMap) =0; + + /// + // Set the value for the element attribute named |attrName|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool SetElementAttribute(const CefString& attrName, + const CefString& value) =0; + + /// + // Returns the inner text of the element. + /// + /*--cef()--*/ + virtual CefString GetElementInnerText() =0; +}; + +#endif // CEF_INCLUDE_CEF_DOM_H_ diff --git a/include/cef_download_handler.h b/include/cef_download_handler.h new file mode 100644 index 000000000..4f58af485 --- /dev/null +++ b/include/cef_download_handler.h @@ -0,0 +1,124 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DOWNLOAD_HANDLER_H_ +#define CEF_INCLUDE_CEF_DOWNLOAD_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_download_item.h" + + +/// +// Callback interface used to asynchronously continue a download. +/// +/*--cef(source=library)--*/ +class CefBeforeDownloadCallback : public virtual CefBase { + public: + /// + // Call to continue the download. Set |download_path| to the full file path + // for the download including the file name or leave blank to use the + // suggested name and the default temp directory. Set |show_dialog| to true + // if you do wish to show the default "Save As" dialog. + /// + /*--cef(capi_name=cont,optional_param=download_path)--*/ + virtual void Continue(const CefString& download_path, bool show_dialog) =0; +}; + + +/// +// Callback interface used to asynchronously cancel a download. +/// +/*--cef(source=library)--*/ +class CefDownloadItemCallback : public virtual CefBase { + public: + /// + // Call to cancel the download. + /// + /*--cef()--*/ + virtual void Cancel() =0; + + /// + // Call to pause the download. + /// + /*--cef()--*/ + virtual void Pause() =0; + + /// + // Call to resume the download. + /// + /*--cef()--*/ + virtual void Resume() =0; +}; + + +/// +// Class used to handle file downloads. The methods of this class will called +// on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefDownloadHandler : public virtual CefBase { + public: + /// + // Called before a download begins. |suggested_name| is the suggested name for + // the download file. By default the download will be canceled. Execute + // |callback| either asynchronously or in this method to continue the download + // if desired. Do not keep a reference to |download_item| outside of this + // method. + /// + /*--cef()--*/ + virtual void OnBeforeDownload( + CefRefPtr browser, + CefRefPtr download_item, + const CefString& suggested_name, + CefRefPtr callback) =0; + + /// + // Called when a download's status or progress information has been updated. + // This may be called multiple times before and after OnBeforeDownload(). + // Execute |callback| either asynchronously or in this method to cancel the + // download if desired. Do not keep a reference to |download_item| outside of + // this method. + /// + /*--cef()--*/ + virtual void OnDownloadUpdated( + CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) {} +}; + +#endif // CEF_INCLUDE_CEF_DOWNLOAD_HANDLER_H_ diff --git a/include/cef_download_item.h b/include/cef_download_item.h new file mode 100644 index 000000000..988ef6bde --- /dev/null +++ b/include/cef_download_item.h @@ -0,0 +1,154 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DOWNLOAD_ITEM_H_ +#define CEF_INCLUDE_CEF_DOWNLOAD_ITEM_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Class used to represent a download item. +/// +/*--cef(source=library)--*/ +class CefDownloadItem : public virtual CefBase { + public: + /// + // Returns true if this object is valid. Do not call any other methods if this + // function returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if the download is in progress. + /// + /*--cef()--*/ + virtual bool IsInProgress() =0; + + /// + // Returns true if the download is complete. + /// + /*--cef()--*/ + virtual bool IsComplete() =0; + + /// + // Returns true if the download has been canceled or interrupted. + /// + /*--cef()--*/ + virtual bool IsCanceled() =0; + + /// + // Returns a simple speed estimate in bytes/s. + /// + /*--cef()--*/ + virtual int64 GetCurrentSpeed() =0; + + /// + // Returns the rough percent complete or -1 if the receive total size is + // unknown. + /// + /*--cef()--*/ + virtual int GetPercentComplete() =0; + + /// + // Returns the total number of bytes. + /// + /*--cef()--*/ + virtual int64 GetTotalBytes() =0; + + /// + // Returns the number of received bytes. + /// + /*--cef()--*/ + virtual int64 GetReceivedBytes() =0; + + /// + // Returns the time that the download started. + /// + /*--cef()--*/ + virtual CefTime GetStartTime() =0; + + /// + // Returns the time that the download ended. + /// + /*--cef()--*/ + virtual CefTime GetEndTime() =0; + + /// + // Returns the full path to the downloaded or downloading file. + /// + /*--cef()--*/ + virtual CefString GetFullPath() =0; + + /// + // Returns the unique identifier for this download. + /// + /*--cef()--*/ + virtual uint32 GetId() =0; + + /// + // Returns the URL. + /// + /*--cef()--*/ + virtual CefString GetURL() =0; + + /// + // Returns the original URL before any redirections. + /// + /*--cef()--*/ + virtual CefString GetOriginalUrl() =0; + + /// + // Returns the suggested file name. + /// + /*--cef()--*/ + virtual CefString GetSuggestedFileName() =0; + + /// + // Returns the content disposition. + /// + /*--cef()--*/ + virtual CefString GetContentDisposition() =0; + + /// + // Returns the mime type. + /// + /*--cef()--*/ + virtual CefString GetMimeType() =0; +}; + +#endif // CEF_INCLUDE_CEF_DOWNLOAD_ITEM_H_ diff --git a/include/cef_drag_data.h b/include/cef_drag_data.h new file mode 100644 index 000000000..8f8094b44 --- /dev/null +++ b/include/cef_drag_data.h @@ -0,0 +1,198 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DRAG_DATA_H_ +#define CEF_INCLUDE_CEF_DRAG_DATA_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_stream.h" +#include + +/// +// Class used to represent drag data. The methods of this class may be called +// on any thread. +/// +/*--cef(source=library)--*/ +class CefDragData : public virtual CefBase { + public: + /// + // Create a new CefDragData object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns a copy of the current object. + /// + /*--cef()--*/ + virtual CefRefPtr Clone() =0; + + /// + // Returns true if this object is read-only. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns true if the drag data is a link. + /// + /*--cef()--*/ + virtual bool IsLink() =0; + + /// + // Returns true if the drag data is a text or html fragment. + /// + /*--cef()--*/ + virtual bool IsFragment() =0; + + /// + // Returns true if the drag data is a file. + /// + /*--cef()--*/ + virtual bool IsFile() =0; + + /// + // Return the link URL that is being dragged. + /// + /*--cef()--*/ + virtual CefString GetLinkURL() =0; + + /// + // Return the title associated with the link being dragged. + /// + /*--cef()--*/ + virtual CefString GetLinkTitle() =0; + + /// + // Return the metadata, if any, associated with the link being dragged. + /// + /*--cef()--*/ + virtual CefString GetLinkMetadata() =0; + + /// + // Return the plain text fragment that is being dragged. + /// + /*--cef()--*/ + virtual CefString GetFragmentText() =0; + + /// + // Return the text/html fragment that is being dragged. + /// + /*--cef()--*/ + virtual CefString GetFragmentHtml() =0; + + /// + // Return the base URL that the fragment came from. This value is used for + // resolving relative URLs and may be empty. + /// + /*--cef()--*/ + virtual CefString GetFragmentBaseURL() =0; + + /// + // Return the name of the file being dragged out of the browser window. + /// + /*--cef()--*/ + virtual CefString GetFileName() =0; + + /// + // Write the contents of the file being dragged out of the web view into + // |writer|. Returns the number of bytes sent to |writer|. If |writer| is + // NULL this method will return the size of the file contents in bytes. + // Call GetFileName() to get a suggested name for the file. + /// + /*--cef(optional_param=writer)--*/ + virtual size_t GetFileContents(CefRefPtr writer) =0; + + /// + // Retrieve the list of file names that are being dragged into the browser + // window. + /// + /*--cef()--*/ + virtual bool GetFileNames(std::vector& names) =0; + + /// + // Set the link URL that is being dragged. + /// + /*--cef(optional_param=url)--*/ + virtual void SetLinkURL(const CefString& url) =0; + + /// + // Set the title associated with the link being dragged. + /// + /*--cef(optional_param=title)--*/ + virtual void SetLinkTitle(const CefString& title) =0; + + /// + // Set the metadata associated with the link being dragged. + /// + /*--cef(optional_param=data)--*/ + virtual void SetLinkMetadata(const CefString& data) =0; + + /// + // Set the plain text fragment that is being dragged. + /// + /*--cef(optional_param=text)--*/ + virtual void SetFragmentText(const CefString& text) =0; + + /// + // Set the text/html fragment that is being dragged. + /// + /*--cef(optional_param=html)--*/ + virtual void SetFragmentHtml(const CefString& html) =0; + + /// + // Set the base URL that the fragment came from. + /// + /*--cef(optional_param=base_url)--*/ + virtual void SetFragmentBaseURL(const CefString& base_url) =0; + + /// + // Reset the file contents. You should do this before calling + // CefBrowserHost::DragTargetDragEnter as the web view does not allow us to + // drag in this kind of data. + /// + /*--cef()--*/ + virtual void ResetFileContents() =0; + + /// + // Add a file that is being dragged into the webview. + /// + /*--cef(optional_param=display_name)--*/ + virtual void AddFile(const CefString& path, const CefString& display_name) =0; +}; + +#endif // CEF_INCLUDE_CEF_DRAG_DATA_H_ diff --git a/include/cef_drag_handler.h b/include/cef_drag_handler.h new file mode 100644 index 000000000..7cfc40ba5 --- /dev/null +++ b/include/cef_drag_handler.h @@ -0,0 +1,66 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_DRAG_HANDLER_H_ +#define CEF_INCLUDE_CEF_DRAG_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_drag_data.h" +#include "include/cef_browser.h" + +/// +// Implement this interface to handle events related to dragging. The methods of +// this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefDragHandler : public virtual CefBase { + public: + typedef cef_drag_operations_mask_t DragOperationsMask; + + /// + // Called when an external drag event enters the browser window. |dragData| + // contains the drag event data and |mask| represents the type of drag + // operation. Return false for default drag handling behavior or true to + // cancel the drag event. + /// + /*--cef()--*/ + virtual bool OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, + DragOperationsMask mask) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_DRAG_HANDLER_H_ diff --git a/include/cef_find_handler.h b/include/cef_find_handler.h new file mode 100644 index 000000000..410cf5fec --- /dev/null +++ b/include/cef_find_handler.h @@ -0,0 +1,68 @@ +// Copyright (c) 2015 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_FIND_HANDLER_H_ +#define CEF_INCLUDE_CEF_FIND_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Implement this interface to handle events related to find results. The +// methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefFindHandler : public virtual CefBase { + public: + /// + // Called to report find results returned by CefBrowserHost::Find(). + // |identifer| is the identifier passed to Find(), |count| is the number of + // matches currently identified, |selectionRect| is the location of where the + // match was found (in window coordinates), |activeMatchOrdinal| is the + // current position in the search results, and |finalUpdate| is true if this + // is the last find notification. + /// + /*--cef()--*/ + virtual void OnFindResult(CefRefPtr browser, + int identifier, + int count, + const CefRect& selectionRect, + int activeMatchOrdinal, + bool finalUpdate) {} +}; + +#endif // CEF_INCLUDE_CEF_FIND_HANDLER_H_ diff --git a/include/cef_focus_handler.h b/include/cef_focus_handler.h new file mode 100644 index 000000000..1d91c42ab --- /dev/null +++ b/include/cef_focus_handler.h @@ -0,0 +1,81 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_FOCUS_HANDLER_H_ +#define CEF_INCLUDE_CEF_FOCUS_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_dom.h" +#include "include/cef_frame.h" + +/// +// Implement this interface to handle events related to focus. The methods of +// this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefFocusHandler : public virtual CefBase { + public: + typedef cef_focus_source_t FocusSource; + + /// + // Called when the browser component is about to loose focus. For instance, if + // focus was on the last HTML element and the user pressed the TAB key. |next| + // will be true if the browser is giving focus to the next component and false + // if the browser is giving focus to the previous component. + /// + /*--cef()--*/ + virtual void OnTakeFocus(CefRefPtr browser, + bool next) {} + + /// + // Called when the browser component is requesting focus. |source| indicates + // where the focus request is originating from. Return false to allow the + // focus to be set or true to cancel setting the focus. + /// + /*--cef()--*/ + virtual bool OnSetFocus(CefRefPtr browser, + FocusSource source) { return false; } + + /// + // Called when the browser component has received focus. + /// + /*--cef()--*/ + virtual void OnGotFocus(CefRefPtr browser) {} +}; + +#endif // CEF_INCLUDE_CEF_FOCUS_HANDLER_H_ diff --git a/include/cef_frame.h b/include/cef_frame.h new file mode 100644 index 000000000..adba66f1e --- /dev/null +++ b/include/cef_frame.h @@ -0,0 +1,224 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_FRAME_H_ +#define CEF_INCLUDE_CEF_FRAME_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_dom.h" +#include "include/cef_request.h" +#include "include/cef_stream.h" +#include "include/cef_string_visitor.h" + +class CefBrowser; +class CefV8Context; + +/// +// Class used to represent a frame in the browser window. When used in the +// browser process the methods of this class may be called on any thread unless +// otherwise indicated in the comments. When used in the render process the +// methods of this class may only be called on the main thread. +/// +/*--cef(source=library)--*/ +class CefFrame : public virtual CefBase { + public: + /// + // True if this object is currently attached to a valid frame. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Execute undo in this frame. + /// + /*--cef()--*/ + virtual void Undo() =0; + + /// + // Execute redo in this frame. + /// + /*--cef()--*/ + virtual void Redo() =0; + + /// + // Execute cut in this frame. + /// + /*--cef()--*/ + virtual void Cut() =0; + + /// + // Execute copy in this frame. + /// + /*--cef()--*/ + virtual void Copy() =0; + + /// + // Execute paste in this frame. + /// + /*--cef()--*/ + virtual void Paste() =0; + + /// + // Execute delete in this frame. + /// + /*--cef(capi_name=del)--*/ + virtual void Delete() =0; + + /// + // Execute select all in this frame. + /// + /*--cef()--*/ + virtual void SelectAll() =0; + + /// + // Save this frame's HTML source to a temporary file and open it in the + // default text viewing application. This method can only be called from the + // browser process. + /// + /*--cef()--*/ + virtual void ViewSource() =0; + + /// + // Retrieve this frame's HTML source as a string sent to the specified + // visitor. + /// + /*--cef()--*/ + virtual void GetSource(CefRefPtr visitor) =0; + + /// + // Retrieve this frame's display text as a string sent to the specified + // visitor. + /// + /*--cef()--*/ + virtual void GetText(CefRefPtr visitor) =0; + + /// + // Load the request represented by the |request| object. + /// + /*--cef()--*/ + virtual void LoadRequest(CefRefPtr request) =0; + + /// + // Load the specified |url|. + /// + /*--cef()--*/ + virtual void LoadURL(const CefString& url) =0; + + /// + // Load the contents of |string_val| with the specified dummy |url|. |url| + // should have a standard scheme (for example, http scheme) or behaviors like + // link clicks and web security restrictions may not behave as expected. + /// + /*--cef()--*/ + virtual void LoadString(const CefString& string_val, + const CefString& url) =0; + + /// + // Execute a string of JavaScript code in this frame. The |script_url| + // parameter is the URL where the script in question can be found, if any. + // The renderer may request this URL to show the developer the source of the + // error. The |start_line| parameter is the base line number to use for error + // reporting. + /// + /*--cef(optional_param=script_url)--*/ + virtual void ExecuteJavaScript(const CefString& code, + const CefString& script_url, + int start_line) =0; + + /// + // Returns true if this is the main (top-level) frame. + /// + /*--cef()--*/ + virtual bool IsMain() =0; + + /// + // Returns true if this is the focused frame. + /// + /*--cef()--*/ + virtual bool IsFocused() =0; + + /// + // Returns the name for this frame. If the frame has an assigned name (for + // example, set via the iframe "name" attribute) then that value will be + // returned. Otherwise a unique name will be constructed based on the frame + // parent hierarchy. The main (top-level) frame will always have an empty name + // value. + /// + /*--cef()--*/ + virtual CefString GetName() =0; + + /// + // Returns the globally unique identifier for this frame. + /// + /*--cef()--*/ + virtual int64 GetIdentifier() =0; + + /// + // Returns the parent of this frame or NULL if this is the main (top-level) + // frame. + /// + /*--cef()--*/ + virtual CefRefPtr GetParent() =0; + + /// + // Returns the URL currently loaded in this frame. + /// + /*--cef()--*/ + virtual CefString GetURL() =0; + + /// + // Returns the browser that this frame belongs to. + /// + /*--cef()--*/ + virtual CefRefPtr GetBrowser() =0; + + /// + // Get the V8 context associated with the frame. This method can only be + // called from the render process. + /// + /*--cef()--*/ + virtual CefRefPtr GetV8Context() =0; + + /// + // Visit the DOM document. This method can only be called from the render + // process. + /// + /*--cef()--*/ + virtual void VisitDOM(CefRefPtr visitor) =0; +}; + +#endif // CEF_INCLUDE_CEF_FRAME_H_ diff --git a/include/cef_geolocation.h b/include/cef_geolocation.h new file mode 100644 index 000000000..69c08779c --- /dev/null +++ b/include/cef_geolocation.h @@ -0,0 +1,66 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_GEOLOCATION_H_ +#define CEF_INCLUDE_CEF_GEOLOCATION_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Implement this interface to receive geolocation updates. The methods of this +// class will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefGetGeolocationCallback : public virtual CefBase { + public: + /// + // Called with the 'best available' location information or, if the location + // update failed, with error information. + /// + /*--cef()--*/ + virtual void OnLocationUpdate(const CefGeoposition& position) =0; +}; + +/// +// Request a one-time geolocation update. This function bypasses any user +// permission checks so should only be used by code that is allowed to access +// location information. +/// +/*--cef()--*/ +bool CefGetGeolocation(CefRefPtr callback); + +#endif // CEF_INCLUDE_CEF_GEOLOCATION_H_ diff --git a/include/cef_geolocation_handler.h b/include/cef_geolocation_handler.h new file mode 100644 index 000000000..679621a1f --- /dev/null +++ b/include/cef_geolocation_handler.h @@ -0,0 +1,97 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_GEOLOCATION_HANDLER_H_ +#define CEF_INCLUDE_CEF_GEOLOCATION_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Callback interface used for asynchronous continuation of geolocation +// permission requests. +/// +/*--cef(source=library)--*/ +class CefGeolocationCallback : public virtual CefBase { + public: + /// + // Call to allow or deny geolocation access. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue(bool allow) =0; +}; + + +/// +// Implement this interface to handle events related to geolocation permission +// requests. The methods of this class will be called on the browser process UI +// thread. +/// +/*--cef(source=client)--*/ +class CefGeolocationHandler : public virtual CefBase { + public: + /// + // Called when a page requests permission to access geolocation information. + // |requesting_url| is the URL requesting permission and |request_id| is the + // unique ID for the permission request. Return true and call + // CefGeolocationCallback::Continue() either in this method or at a later + // time to continue or cancel the request. Return false to cancel the request + // immediately. + /// + /*--cef()--*/ + virtual bool OnRequestGeolocationPermission( + CefRefPtr browser, + const CefString& requesting_url, + int request_id, + CefRefPtr callback) { + return false; + } + + /// + // Called when a geolocation access request is canceled. |requesting_url| is + // the URL that originally requested permission and |request_id| is the unique + // ID for the permission request. + /// + /*--cef()--*/ + virtual void OnCancelGeolocationPermission( + CefRefPtr browser, + const CefString& requesting_url, + int request_id) { + } +}; + +#endif // CEF_INCLUDE_CEF_GEOLOCATION_HANDLER_H_ diff --git a/include/cef_jsdialog_handler.h b/include/cef_jsdialog_handler.h new file mode 100644 index 000000000..29548966e --- /dev/null +++ b/include/cef_jsdialog_handler.h @@ -0,0 +1,128 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_JSDIALOG_HANDLER_H_ +#define CEF_INCLUDE_CEF_JSDIALOG_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Callback interface used for asynchronous continuation of JavaScript dialog +// requests. +/// +/*--cef(source=library)--*/ +class CefJSDialogCallback : public virtual CefBase { + public: + /// + // Continue the JS dialog request. Set |success| to true if the OK button was + // pressed. The |user_input| value should be specified for prompt dialogs. + /// + /*--cef(capi_name=cont,optional_param=user_input)--*/ + virtual void Continue(bool success, + const CefString& user_input) =0; +}; + + +/// +// Implement this interface to handle events related to JavaScript dialogs. The +// methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefJSDialogHandler : public virtual CefBase { + public: + typedef cef_jsdialog_type_t JSDialogType; + + /// + // Called to run a JavaScript dialog. The |default_prompt_text| value will be + // specified for prompt dialogs only. Set |suppress_message| to true and + // return false to suppress the message (suppressing messages is preferable + // to immediately executing the callback as this is used to detect presumably + // malicious behavior like spamming alert messages in onbeforeunload). Set + // |suppress_message| to false and return false to use the default + // implementation (the default implementation will show one modal dialog at a + // time and suppress any additional dialog requests until the displayed dialog + // is dismissed). Return true if the application will use a custom dialog or + // if the callback has been executed immediately. Custom dialogs may be either + // modal or modeless. If a custom dialog is used the application must execute + // |callback| once the custom dialog is dismissed. + /// + /*--cef(optional_param=origin_url,optional_param=accept_lang, + optional_param=message_text,optional_param=default_prompt_text)--*/ + virtual bool OnJSDialog(CefRefPtr browser, + const CefString& origin_url, + const CefString& accept_lang, + JSDialogType dialog_type, + const CefString& message_text, + const CefString& default_prompt_text, + CefRefPtr callback, + bool& suppress_message) { + return false; + } + + /// + // Called to run a dialog asking the user if they want to leave a page. Return + // false to use the default dialog implementation. Return true if the + // application will use a custom dialog or if the callback has been executed + // immediately. Custom dialogs may be either modal or modeless. If a custom + // dialog is used the application must execute |callback| once the custom + // dialog is dismissed. + /// + /*--cef(optional_param=message_text)--*/ + virtual bool OnBeforeUnloadDialog(CefRefPtr browser, + const CefString& message_text, + bool is_reload, + CefRefPtr callback) { + return false; + } + + /// + // Called to cancel any pending dialogs and reset any saved dialog state. Will + // be called due to events like page navigation irregardless of whether any + // dialogs are currently pending. + /// + /*--cef()--*/ + virtual void OnResetDialogState(CefRefPtr browser) {} + + /// + // Called when the default implementation dialog is closed. + /// + /*--cef()--*/ + virtual void OnDialogClosed(CefRefPtr browser) {} +}; + +#endif // CEF_INCLUDE_CEF_JSDIALOG_HANDLER_H_ diff --git a/include/cef_keyboard_handler.h b/include/cef_keyboard_handler.h new file mode 100644 index 000000000..55cb57ef8 --- /dev/null +++ b/include/cef_keyboard_handler.h @@ -0,0 +1,74 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_KEYBOARD_HANDLER_H_ +#define CEF_INCLUDE_CEF_KEYBOARD_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Implement this interface to handle events related to keyboard input. The +// methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefKeyboardHandler : public virtual CefBase { + public: + // Called before a keyboard event is sent to the renderer. |event| contains + // information about the keyboard event. |os_event| is the operating system + // event message, if any. Return true if the event was handled or false + // otherwise. If the event will be handled in OnKeyEvent() as a keyboard + // shortcut set |is_keyboard_shortcut| to true and return false. + /*--cef()--*/ + virtual bool OnPreKeyEvent(CefRefPtr browser, + const CefKeyEvent& event, + CefEventHandle os_event, + bool* is_keyboard_shortcut) { return false; } + + /// + // Called after the renderer and JavaScript in the page has had a chance to + // handle the event. |event| contains information about the keyboard event. + // |os_event| is the operating system event message, if any. Return true if + // the keyboard event was handled or false otherwise. + /// + /*--cef()--*/ + virtual bool OnKeyEvent(CefRefPtr browser, + const CefKeyEvent& event, + CefEventHandle os_event) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_KEYBOARD_HANDLER_H_ diff --git a/include/cef_life_span_handler.h b/include/cef_life_span_handler.h new file mode 100644 index 000000000..14534961c --- /dev/null +++ b/include/cef_life_span_handler.h @@ -0,0 +1,164 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_LIFE_SPAN_HANDLER_H_ +#define CEF_INCLUDE_CEF_LIFE_SPAN_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +class CefClient; + +/// +// Implement this interface to handle events related to browser life span. The +// methods of this class will be called on the UI thread unless otherwise +// indicated. +/// +/*--cef(source=client)--*/ +class CefLifeSpanHandler : public virtual CefBase { + public: + /// + // Called on the IO thread before a new popup window is created. The |browser| + // and |frame| parameters represent the source of the popup request. The + // |target_url| and |target_frame_name| values may be empty if none were + // specified with the request. The |popupFeatures| structure contains + // information about the requested popup window. To allow creation of the + // popup window optionally modify |windowInfo|, |client|, |settings| and + // |no_javascript_access| and return false. To cancel creation of the popup + // window return true. The |client| and |settings| values will default to the + // source browser's values. The |no_javascript_access| value indicates whether + // the new browser window should be scriptable and in the same process as the + // source browser. + /*--cef(optional_param=target_url,optional_param=target_frame_name)--*/ + virtual bool OnBeforePopup(CefRefPtr browser, + CefRefPtr frame, + const CefString& target_url, + const CefString& target_frame_name, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + CefRefPtr& client, + CefBrowserSettings& settings, + bool* no_javascript_access) { + return false; + } + + /// + // Called after a new browser is created. + /// + /*--cef()--*/ + virtual void OnAfterCreated(CefRefPtr browser) {} + + /// + // Called when a modal window is about to display and the modal loop should + // begin running. Return false to use the default modal loop implementation or + // true to use a custom implementation. + /// + /*--cef()--*/ + virtual bool RunModal(CefRefPtr browser) { return false; } + + /// + // Called when a browser has recieved a request to close. This may result + // directly from a call to CefBrowserHost::CloseBrowser() or indirectly if the + // browser is a top-level OS window created by CEF and the user attempts to + // close the window. This method will be called after the JavaScript + // 'onunload' event has been fired. It will not be called for browsers after + // the associated OS window has been destroyed (for those browsers it is no + // longer possible to cancel the close). + // + // If CEF created an OS window for the browser returning false will send an OS + // close notification to the browser window's top-level owner (e.g. WM_CLOSE + // on Windows, performClose: on OS-X and "delete_event" on Linux). If no OS + // window exists (window rendering disabled) returning false will cause the + // browser object to be destroyed immediately. Return true if the browser is + // parented to another window and that other window needs to receive close + // notification via some non-standard technique. + // + // If an application provides its own top-level window it should handle OS + // close notifications by calling CefBrowserHost::CloseBrowser(false) instead + // of immediately closing (see the example below). This gives CEF an + // opportunity to process the 'onbeforeunload' event and optionally cancel the + // close before DoClose() is called. + // + // The CefLifeSpanHandler::OnBeforeClose() method will be called immediately + // before the browser object is destroyed. The application should only exit + // after OnBeforeClose() has been called for all existing browsers. + // + // If the browser represents a modal window and a custom modal loop + // implementation was provided in CefLifeSpanHandler::RunModal() this callback + // should be used to restore the opener window to a usable state. + // + // By way of example consider what should happen during window close when the + // browser is parented to an application-provided top-level OS window. + // 1. User clicks the window close button which sends an OS close + // notification (e.g. WM_CLOSE on Windows, performClose: on OS-X and + // "delete_event" on Linux). + // 2. Application's top-level window receives the close notification and: + // A. Calls CefBrowserHost::CloseBrowser(false). + // B. Cancels the window close. + // 3. JavaScript 'onbeforeunload' handler executes and shows the close + // confirmation dialog (which can be overridden via + // CefJSDialogHandler::OnBeforeUnloadDialog()). + // 4. User approves the close. + // 5. JavaScript 'onunload' handler executes. + // 6. Application's DoClose() handler is called. Application will: + // A. Set a flag to indicate that the next close attempt will be allowed. + // B. Return false. + // 7. CEF sends an OS close notification. + // 8. Application's top-level window receives the OS close notification and + // allows the window to close based on the flag from #6B. + // 9. Browser OS window is destroyed. + // 10. Application's CefLifeSpanHandler::OnBeforeClose() handler is called and + // the browser object is destroyed. + // 11. Application exits by calling CefQuitMessageLoop() if no other browsers + // exist. + /// + /*--cef()--*/ + virtual bool DoClose(CefRefPtr browser) { return false; } + + /// + // Called just before a browser is destroyed. Release all references to the + // browser object and do not attempt to execute any methods on the browser + // object after this callback returns. If this is a modal window and a custom + // modal loop implementation was provided in RunModal() this callback should + // be used to exit the custom modal loop. See DoClose() documentation for + // additional usage information. + /// + /*--cef()--*/ + virtual void OnBeforeClose(CefRefPtr browser) {} +}; + +#endif // CEF_INCLUDE_CEF_LIFE_SPAN_HANDLER_H_ diff --git a/include/cef_load_handler.h b/include/cef_load_handler.h new file mode 100644 index 000000000..02d9d9f1a --- /dev/null +++ b/include/cef_load_handler.h @@ -0,0 +1,107 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_LOAD_HANDLER_H_ +#define CEF_INCLUDE_CEF_LOAD_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" + +/// +// Implement this interface to handle events related to browser load status. The +// methods of this class will be called on the browser process UI thread or +// render process main thread (TID_RENDERER). +/// +/*--cef(source=client)--*/ +class CefLoadHandler : public virtual CefBase { + public: + typedef cef_errorcode_t ErrorCode; + + /// + // Called when the loading state has changed. This callback will be executed + // twice -- once when loading is initiated either programmatically or by user + // action, and once when loading is terminated due to completion, cancellation + // of failure. + /// + /*--cef()--*/ + virtual void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) {} + + /// + // Called when the browser begins loading a frame. The |frame| value will + // never be empty -- call the IsMain() method to check if this frame is the + // main frame. Multiple frames may be loading at the same time. Sub-frames may + // start or continue loading after the main frame load has ended. This method + // may not be called for a particular frame if the load request for that frame + // fails. For notification of overall browser load status use + // OnLoadingStateChange instead. + /// + /*--cef()--*/ + virtual void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) {} + + /// + // Called when the browser is done loading a frame. The |frame| value will + // never be empty -- call the IsMain() method to check if this frame is the + // main frame. Multiple frames may be loading at the same time. Sub-frames may + // start or continue loading after the main frame load has ended. This method + // will always be called for all frames irrespective of whether the request + // completes successfully. + /// + /*--cef()--*/ + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) {} + + /// + // Called when the resource load for a navigation fails or is canceled. + // |errorCode| is the error code number, |errorText| is the error text and + // |failedUrl| is the URL that failed to load. See net\base\net_error_list.h + // for complete descriptions of the error codes. + /// + /*--cef(optional_param=errorText)--*/ + virtual void OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) {} +}; + +#endif // CEF_INCLUDE_CEF_LOAD_HANDLER_H_ diff --git a/include/cef_menu_model.h b/include/cef_menu_model.h new file mode 100644 index 000000000..84728c58b --- /dev/null +++ b/include/cef_menu_model.h @@ -0,0 +1,402 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_MENU_MODEL_H_ +#define CEF_INCLUDE_CEF_MENU_MODEL_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Supports creation and modification of menus. See cef_menu_id_t for the +// command ids that have default implementations. All user-defined command ids +// should be between MENU_ID_USER_FIRST and MENU_ID_USER_LAST. The methods of +// this class can only be accessed on the browser process the UI thread. +/// +/*--cef(source=library)--*/ +class CefMenuModel : public virtual CefBase { + public: + typedef cef_menu_item_type_t MenuItemType; + + /// + // Clears the menu. Returns true on success. + /// + /*--cef()--*/ + virtual bool Clear() =0; + + /// + // Returns the number of items in this menu. + /// + /*--cef()--*/ + virtual int GetCount() =0; + + // + // Add a separator to the menu. Returns true on success. + /// + /*--cef()--*/ + virtual bool AddSeparator() =0; + + // + // Add an item to the menu. Returns true on success. + /// + /*--cef()--*/ + virtual bool AddItem(int command_id, + const CefString& label) =0; + + // + // Add a check item to the menu. Returns true on success. + /// + /*--cef()--*/ + virtual bool AddCheckItem(int command_id, + const CefString& label) =0; + // + // Add a radio item to the menu. Only a single item with the specified + // |group_id| can be checked at a time. Returns true on success. + /// + /*--cef()--*/ + virtual bool AddRadioItem(int command_id, + const CefString& label, + int group_id) =0; + + // + // Add a sub-menu to the menu. The new sub-menu is returned. + /// + /*--cef()--*/ + virtual CefRefPtr AddSubMenu(int command_id, + const CefString& label) =0; + + // + // Insert a separator in the menu at the specified |index|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool InsertSeparatorAt(int index) =0; + + // + // Insert an item in the menu at the specified |index|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool InsertItemAt(int index, + int command_id, + const CefString& label) =0; + + // + // Insert a check item in the menu at the specified |index|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool InsertCheckItemAt(int index, + int command_id, + const CefString& label) =0; + + // + // Insert a radio item in the menu at the specified |index|. Only a single + // item with the specified |group_id| can be checked at a time. Returns true + // on success. + /// + /*--cef()--*/ + virtual bool InsertRadioItemAt(int index, + int command_id, + const CefString& label, + int group_id) =0; + + // + // Insert a sub-menu in the menu at the specified |index|. The new sub-menu + // is returned. + /// + /*--cef()--*/ + virtual CefRefPtr InsertSubMenuAt(int index, + int command_id, + const CefString& label) =0; + + /// + // Removes the item with the specified |command_id|. Returns true on success. + /// + /*--cef()--*/ + virtual bool Remove(int command_id) =0; + + /// + // Removes the item at the specified |index|. Returns true on success. + /// + /*--cef()--*/ + virtual bool RemoveAt(int index) =0; + + /// + // Returns the index associated with the specified |command_id| or -1 if not + // found due to the command id not existing in the menu. + /// + /*--cef()--*/ + virtual int GetIndexOf(int command_id) =0; + + /// + // Returns the command id at the specified |index| or -1 if not found due to + // invalid range or the index being a separator. + /// + /*--cef()--*/ + virtual int GetCommandIdAt(int index) =0; + + /// + // Sets the command id at the specified |index|. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetCommandIdAt(int index, int command_id) =0; + + /// + // Returns the label for the specified |command_id| or empty if not found. + /// + /*--cef()--*/ + virtual CefString GetLabel(int command_id) =0; + + /// + // Returns the label at the specified |index| or empty if not found due to + // invalid range or the index being a separator. + /// + /*--cef()--*/ + virtual CefString GetLabelAt(int index) =0; + + /// + // Sets the label for the specified |command_id|. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetLabel(int command_id, const CefString& label) =0; + + /// + // Set the label at the specified |index|. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetLabelAt(int index, const CefString& label) =0; + + /// + // Returns the item type for the specified |command_id|. + /// + /*--cef(default_retval=MENUITEMTYPE_NONE)--*/ + virtual MenuItemType GetType(int command_id) =0; + + /// + // Returns the item type at the specified |index|. + /// + /*--cef(default_retval=MENUITEMTYPE_NONE)--*/ + virtual MenuItemType GetTypeAt(int index) =0; + + /// + // Returns the group id for the specified |command_id| or -1 if invalid. + /// + /*--cef()--*/ + virtual int GetGroupId(int command_id) =0; + + /// + // Returns the group id at the specified |index| or -1 if invalid. + /// + /*--cef()--*/ + virtual int GetGroupIdAt(int index) =0; + + /// + // Sets the group id for the specified |command_id|. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetGroupId(int command_id, int group_id) =0; + + /// + // Sets the group id at the specified |index|. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetGroupIdAt(int index, int group_id) =0; + + /// + // Returns the submenu for the specified |command_id| or empty if invalid. + /// + /*--cef()--*/ + virtual CefRefPtr GetSubMenu(int command_id) =0; + + /// + // Returns the submenu at the specified |index| or empty if invalid. + /// + /*--cef()--*/ + virtual CefRefPtr GetSubMenuAt(int index) =0; + + // + // Returns true if the specified |command_id| is visible. + /// + /*--cef()--*/ + virtual bool IsVisible(int command_id) =0; + + // + // Returns true if the specified |index| is visible. + /// + /*--cef()--*/ + virtual bool IsVisibleAt(int index) =0; + + // + // Change the visibility of the specified |command_id|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool SetVisible(int command_id, bool visible) =0; + + // + // Change the visibility at the specified |index|. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetVisibleAt(int index, bool visible) =0; + + // + // Returns true if the specified |command_id| is enabled. + /// + /*--cef()--*/ + virtual bool IsEnabled(int command_id) =0; + + // + // Returns true if the specified |index| is enabled. + /// + /*--cef()--*/ + virtual bool IsEnabledAt(int index) =0; + + // + // Change the enabled status of the specified |command_id|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool SetEnabled(int command_id, bool enabled) =0; + + // + // Change the enabled status at the specified |index|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool SetEnabledAt(int index, bool enabled) =0; + + // + // Returns true if the specified |command_id| is checked. Only applies to + // check and radio items. + /// + /*--cef()--*/ + virtual bool IsChecked(int command_id) =0; + + // + // Returns true if the specified |index| is checked. Only applies to check + // and radio items. + /// + /*--cef()--*/ + virtual bool IsCheckedAt(int index) =0; + + // + // Check the specified |command_id|. Only applies to check and radio items. + // Returns true on success. + /// + /*--cef()--*/ + virtual bool SetChecked(int command_id, bool checked) =0; + + // + // Check the specified |index|. Only applies to check and radio items. Returns + // true on success. + /// + /*--cef()--*/ + virtual bool SetCheckedAt(int index, bool checked) =0; + + // + // Returns true if the specified |command_id| has a keyboard accelerator + // assigned. + /// + /*--cef()--*/ + virtual bool HasAccelerator(int command_id) =0; + + // + // Returns true if the specified |index| has a keyboard accelerator assigned. + /// + /*--cef()--*/ + virtual bool HasAcceleratorAt(int index) =0; + + // + // Set the keyboard accelerator for the specified |command_id|. |key_code| can + // be any virtual key or character value. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetAccelerator(int command_id, + int key_code, + bool shift_pressed, + bool ctrl_pressed, + bool alt_pressed) =0; + + // + // Set the keyboard accelerator at the specified |index|. |key_code| can be + // any virtual key or character value. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetAcceleratorAt(int index, + int key_code, + bool shift_pressed, + bool ctrl_pressed, + bool alt_pressed) =0; + + // + // Remove the keyboard accelerator for the specified |command_id|. Returns + // true on success. + /// + /*--cef()--*/ + virtual bool RemoveAccelerator(int command_id) =0; + + // + // Remove the keyboard accelerator at the specified |index|. Returns true on + // success. + /// + /*--cef()--*/ + virtual bool RemoveAcceleratorAt(int index) =0; + + // + // Retrieves the keyboard accelerator for the specified |command_id|. Returns + // true on success. + /// + /*--cef()--*/ + virtual bool GetAccelerator(int command_id, + int& key_code, + bool& shift_pressed, + bool& ctrl_pressed, + bool& alt_pressed) =0; + + // + // Retrieves the keyboard accelerator for the specified |index|. Returns true + // on success. + /// + /*--cef()--*/ + virtual bool GetAcceleratorAt(int index, + int& key_code, + bool& shift_pressed, + bool& ctrl_pressed, + bool& alt_pressed) =0; +}; + +#endif // CEF_INCLUDE_CEF_MENU_MODEL_H_ diff --git a/include/cef_navigation_entry.h b/include/cef_navigation_entry.h new file mode 100644 index 000000000..708e39819 --- /dev/null +++ b/include/cef_navigation_entry.h @@ -0,0 +1,120 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_NAVIGATION_ENTRY_H_ +#define CEF_INCLUDE_CEF_NAVIGATION_ENTRY_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Class used to represent an entry in navigation history. +/// +/*--cef(source=library)--*/ +class CefNavigationEntry : public virtual CefBase { + public: + typedef cef_transition_type_t TransitionType; + + /// + // Returns true if this object is valid. Do not call any other methods if this + // function returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns the actual URL of the page. For some pages this may be data: URL or + // similar. Use GetDisplayURL() to return a display-friendly version. + /// + /*--cef()--*/ + virtual CefString GetURL() =0; + + /// + // Returns a display-friendly version of the URL. + /// + /*--cef()--*/ + virtual CefString GetDisplayURL() =0; + + /// + // Returns the original URL that was entered by the user before any redirects. + /// + /*--cef()--*/ + virtual CefString GetOriginalURL() =0; + + /// + // Returns the title set by the page. This value may be empty. + /// + /*--cef()--*/ + virtual CefString GetTitle() =0; + + /// + // Returns the transition type which indicates what the user did to move to + // this page from the previous page. + /// + /*--cef(default_retval=TT_EXPLICIT)--*/ + virtual TransitionType GetTransitionType() =0; + + /// + // Returns true if this navigation includes post data. + /// + /*--cef()--*/ + virtual bool HasPostData() =0; + + /// + // Returns the name of the sub-frame that navigated or an empty value if the + // main frame navigated. + /// + /*--cef()--*/ + virtual CefString GetFrameName() =0; + + /// + // Returns the time for the last known successful navigation completion. A + // navigation may be completed more than once if the page is reloaded. May be + // 0 if the navigation has not yet completed. + /// + /*--cef()--*/ + virtual CefTime GetCompletionTime() =0; + + /// + // Returns the HTTP status code for the last known successful navigation + // response. May be 0 if the response has not yet been received or if the + // navigation has not yet completed. + /// + /*--cef()--*/ + virtual int GetHttpStatusCode() =0; +}; + +#endif // CEF_INCLUDE_CEF_NAVIGATION_ENTRY_H_ diff --git a/include/cef_origin_whitelist.h b/include/cef_origin_whitelist.h new file mode 100644 index 000000000..7fed3453a --- /dev/null +++ b/include/cef_origin_whitelist.h @@ -0,0 +1,103 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_ORIGIN_WHITELIST_H_ +#define CEF_INCLUDE_CEF_ORIGIN_WHITELIST_H_ +#pragma once + +#include "include/cef_base.h" + + +/// +// Add an entry to the cross-origin access whitelist. +// +// The same-origin policy restricts how scripts hosted from different origins +// (scheme + domain + port) can communicate. By default, scripts can only access +// resources with the same origin. Scripts hosted on the HTTP and HTTPS schemes +// (but no other schemes) can use the "Access-Control-Allow-Origin" header to +// allow cross-origin requests. For example, https://source.example.com can make +// XMLHttpRequest requests on http://target.example.com if the +// http://target.example.com request returns an "Access-Control-Allow-Origin: +// https://source.example.com" response header. +// +// Scripts in separate frames or iframes and hosted from the same protocol and +// domain suffix can execute cross-origin JavaScript if both pages set the +// document.domain value to the same domain suffix. For example, +// scheme://foo.example.com and scheme://bar.example.com can communicate using +// JavaScript if both domains set document.domain="example.com". +// +// This method is used to allow access to origins that would otherwise violate +// the same-origin policy. Scripts hosted underneath the fully qualified +// |source_origin| URL (like http://www.example.com) will be allowed access to +// all resources hosted on the specified |target_protocol| and |target_domain|. +// If |target_domain| is non-empty and |allow_target_subdomains| if false only +// exact domain matches will be allowed. If |target_domain| contains a top- +// level domain component (like "example.com") and |allow_target_subdomains| is +// true sub-domain matches will be allowed. If |target_domain| is empty and +// |allow_target_subdomains| if true all domains and IP addresses will be +// allowed. +// +// This method cannot be used to bypass the restrictions on local or display +// isolated schemes. See the comments on CefRegisterCustomScheme for more +// information. +// +// This function may be called on any thread. Returns false if |source_origin| +// is invalid or the whitelist cannot be accessed. +/// +/*--cef(optional_param=target_domain)--*/ +bool CefAddCrossOriginWhitelistEntry(const CefString& source_origin, + const CefString& target_protocol, + const CefString& target_domain, + bool allow_target_subdomains); + +/// +// Remove an entry from the cross-origin access whitelist. Returns false if +// |source_origin| is invalid or the whitelist cannot be accessed. +/// +/*--cef(optional_param=target_domain)--*/ +bool CefRemoveCrossOriginWhitelistEntry(const CefString& source_origin, + const CefString& target_protocol, + const CefString& target_domain, + bool allow_target_subdomains); + +/// +// Remove all entries from the cross-origin access whitelist. Returns false if +// the whitelist cannot be accessed. +/// +/*--cef()--*/ +bool CefClearCrossOriginWhitelist(); + +#endif // CEF_INCLUDE_CEF_ORIGIN_WHITELIST_H_ diff --git a/include/cef_path_util.h b/include/cef_path_util.h new file mode 100644 index 000000000..552f4ba59 --- /dev/null +++ b/include/cef_path_util.h @@ -0,0 +1,52 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_PATH_UTIL_H_ +#define CEF_INCLUDE_CEF_PATH_UTIL_H_ +#pragma once + +#include "include/cef_base.h" + +typedef cef_path_key_t PathKey; + +/// +// Retrieve the path associated with the specified |key|. Returns true on +// success. Can be called on any thread in the browser process. +/// +/*--cef()--*/ +bool CefGetPath(PathKey key, CefString& path); + +#endif // CEF_INCLUDE_CEF_PATH_UTIL_H_ diff --git a/include/cef_print_handler.h b/include/cef_print_handler.h new file mode 100644 index 000000000..a157cbbd6 --- /dev/null +++ b/include/cef_print_handler.h @@ -0,0 +1,120 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_PRINT_HANDLER_H_ +#define CEF_INCLUDE_CEF_PRINT_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_print_settings.h" + +/// +// Callback interface for asynchronous continuation of print dialog requests. +/// +/*--cef(source=library)--*/ +class CefPrintDialogCallback : public virtual CefBase { + public: + /// + // Continue printing with the specified |settings|. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue(CefRefPtr settings) =0; + + /// + // Cancel the printing. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +/// +// Callback interface for asynchronous continuation of print job requests. +/// +/*--cef(source=library)--*/ +class CefPrintJobCallback : public virtual CefBase { + public: + /// + // Indicate completion of the print job. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue() =0; +}; + + +/// +// Implement this interface to handle printing on Linux. The methods of this +// class will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefPrintHandler : public virtual CefBase { + public: + /// + // Synchronize |settings| with client state. If |get_defaults| is true then + // populate |settings| with the default print settings. Do not keep a + // reference to |settings| outside of this callback. + /// + /*--cef()--*/ + virtual void OnPrintSettings(CefRefPtr settings, + bool get_defaults) =0; + + /// + // Show the print dialog. Execute |callback| once the dialog is dismissed. + // Return true if the dialog will be displayed or false to cancel the + // printing immediately. + /// + /*--cef()--*/ + virtual bool OnPrintDialog(bool has_selection, + CefRefPtr callback) =0; + + /// + // Send the print job to the printer. Execute |callback| once the job is + // completed. Return true if the job will proceed or false to cancel the job + // immediately. + /// + /*--cef()--*/ + virtual bool OnPrintJob(const CefString& document_name, + const CefString& pdf_file_path, + CefRefPtr callback) =0; + + /// + // Reset client state related to printing. + /// + /*--cef()--*/ + virtual void OnPrintReset() =0; +}; + +#endif // CEF_INCLUDE_CEF_PRINT_HANDLER_H_ diff --git a/include/cef_print_settings.h b/include/cef_print_settings.h new file mode 100644 index 000000000..af3fff4f5 --- /dev/null +++ b/include/cef_print_settings.h @@ -0,0 +1,208 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_PRINT_SETTINGS_H_ +#define CEF_INCLUDE_CEF_PRINT_SETTINGS_H_ +#pragma once + +#include + +#include "include/cef_base.h" + +/// +// Class representing print settings. +/// +/*--cef(source=library)--*/ +class CefPrintSettings : public virtual CefBase { + public: + typedef cef_color_model_t ColorModel; + typedef cef_duplex_mode_t DuplexMode; + typedef std::vector PageRangeList; + + /// + // Create a new CefPrintSettings object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is valid. Do not call any other methods if this + // function returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns a writable copy of this object. + /// + /*--cef()--*/ + virtual CefRefPtr Copy() =0; + + /// + // Set the page orientation. + /// + /*--cef()--*/ + virtual void SetOrientation(bool landscape) =0; + + /// + // Returns true if the orientation is landscape. + /// + /*--cef()--*/ + virtual bool IsLandscape() =0; + + /// + // Set the printer printable area in device units. + // Some platforms already provide flipped area. Set |landscape_needs_flip| + // to false on those platforms to avoid double flipping. + /// + /*--cef()--*/ + virtual void SetPrinterPrintableArea( + const CefSize& physical_size_device_units, + const CefRect& printable_area_device_units, + bool landscape_needs_flip) =0; + + /// + // Set the device name. + /// + /*--cef(optional_param=name)--*/ + virtual void SetDeviceName(const CefString& name) =0; + + /// + // Get the device name. + /// + /*--cef()--*/ + virtual CefString GetDeviceName() =0; + + /// + // Set the DPI (dots per inch). + /// + /*--cef()--*/ + virtual void SetDPI(int dpi) =0; + + /// + // Get the DPI (dots per inch). + /// + /*--cef()--*/ + virtual int GetDPI() =0; + + /// + // Set the page ranges. + /// + /*--cef()--*/ + virtual void SetPageRanges(const PageRangeList& ranges) =0; + + /// + // Returns the number of page ranges that currently exist. + /// + /*--cef()--*/ + virtual size_t GetPageRangesCount() =0; + + /// + // Retrieve the page ranges. + /// + /*--cef(count_func=ranges:GetPageRangesCount)--*/ + virtual void GetPageRanges(PageRangeList& ranges) =0; + + /// + // Set whether only the selection will be printed. + /// + /*--cef()--*/ + virtual void SetSelectionOnly(bool selection_only) =0; + + /// + // Returns true if only the selection will be printed. + /// + /*--cef()--*/ + virtual bool IsSelectionOnly() =0; + + /// + // Set whether pages will be collated. + /// + /*--cef()--*/ + virtual void SetCollate(bool collate) =0; + + /// + // Returns true if pages will be collated. + /// + /*--cef()--*/ + virtual bool WillCollate() =0; + + /// + // Set the color model. + /// + /*--cef()--*/ + virtual void SetColorModel(ColorModel model) =0; + + /// + // Get the color model. + /// + /*--cef(default_retval=COLOR_MODEL_UNKNOWN)--*/ + virtual ColorModel GetColorModel() =0; + + /// + // Set the number of copies. + /// + /*--cef()--*/ + virtual void SetCopies(int copies) =0; + + /// + // Get the number of copies. + /// + /*--cef()--*/ + virtual int GetCopies() =0; + + /// + // Set the duplex mode. + /// + /*--cef()--*/ + virtual void SetDuplexMode(DuplexMode mode) =0; + + /// + // Get the duplex mode. + /// + /*--cef(default_retval=DUPLEX_MODE_UNKNOWN)--*/ + virtual DuplexMode GetDuplexMode() =0; +}; + +#endif // CEF_INCLUDE_CEF_PRINT_SETTINGS_H_ + diff --git a/include/cef_process_message.h b/include/cef_process_message.h new file mode 100644 index 000000000..1e27bd681 --- /dev/null +++ b/include/cef_process_message.h @@ -0,0 +1,91 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_MESSAGE_H_ +#define CEF_INCLUDE_CEF_MESSAGE_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_values.h" + +typedef cef_process_id_t CefProcessId; + +/// +// Class representing a message. Can be used on any process and thread. +/// +/*--cef(source=library)--*/ +class CefProcessMessage : public virtual CefBase { + public: + /// + // Create a new CefProcessMessage object with the specified name. + /// + /*--cef()--*/ + static CefRefPtr Create(const CefString& name); + + /// + // Returns true if this object is valid. Do not call any other methods if this + // function returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns a writable copy of this object. + /// + /*--cef()--*/ + virtual CefRefPtr Copy() =0; + + /// + // Returns the message name. + /// + /*--cef()--*/ + virtual CefString GetName() =0; + + /// + // Returns the list of arguments. + /// + /*--cef()--*/ + virtual CefRefPtr GetArgumentList() =0; +}; + +#endif // CEF_INCLUDE_CEF_MESSAGE_H_ diff --git a/include/cef_process_util.h b/include/cef_process_util.h new file mode 100644 index 000000000..4fce778e7 --- /dev/null +++ b/include/cef_process_util.h @@ -0,0 +1,57 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_PROCESS_UTIL_H_ +#define CEF_INCLUDE_CEF_PROCESS_UTIL_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_command_line.h" + +/// +// Launches the process specified via |command_line|. Returns true upon +// success. Must be called on the browser process TID_PROCESS_LAUNCHER thread. +// +// Unix-specific notes: +// - All file descriptors open in the parent process will be closed in the +// child process except for stdin, stdout, and stderr. +// - If the first argument on the command line does not contain a slash, +// PATH will be searched. (See man execvp.) +/// +/*--cef()--*/ +bool CefLaunchProcess(CefRefPtr command_line); + +#endif // CEF_INCLUDE_CEF_PROCESS_UTIL_H_ diff --git a/include/cef_render_handler.h b/include/cef_render_handler.h new file mode 100644 index 000000000..66de6822c --- /dev/null +++ b/include/cef_render_handler.h @@ -0,0 +1,178 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_RENDER_HANDLER_H_ +#define CEF_INCLUDE_CEF_RENDER_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_drag_data.h" +#include + +/// +// Implement this interface to handle events when window rendering is disabled. +// The methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefRenderHandler : public virtual CefBase { + public: + typedef cef_cursor_type_t CursorType; + typedef cef_drag_operations_mask_t DragOperation; + typedef cef_drag_operations_mask_t DragOperationsMask; + typedef cef_paint_element_type_t PaintElementType; + typedef std::vector RectList; + + /// + // Called to retrieve the root window rectangle in screen coordinates. Return + // true if the rectangle was provided. + /// + /*--cef()--*/ + virtual bool GetRootScreenRect(CefRefPtr browser, + CefRect& rect) { return false; } + + /// + // Called to retrieve the view rectangle which is relative to screen + // coordinates. Return true if the rectangle was provided. + /// + /*--cef()--*/ + virtual bool GetViewRect(CefRefPtr browser, CefRect& rect) =0; + + /// + // Called to retrieve the translation from view coordinates to actual screen + // coordinates. Return true if the screen coordinates were provided. + /// + /*--cef()--*/ + virtual bool GetScreenPoint(CefRefPtr browser, + int viewX, + int viewY, + int& screenX, + int& screenY) { return false; } + + /// + // Called to allow the client to fill in the CefScreenInfo object with + // appropriate values. Return true if the |screen_info| structure has been + // modified. + // + // If the screen info rectangle is left empty the rectangle from GetViewRect + // will be used. If the rectangle is still empty or invalid popups may not be + // drawn correctly. + /// + /*--cef()--*/ + virtual bool GetScreenInfo(CefRefPtr browser, + CefScreenInfo& screen_info) { return false; } + + /// + // Called when the browser wants to show or hide the popup widget. The popup + // should be shown if |show| is true and hidden if |show| is false. + /// + /*--cef()--*/ + virtual void OnPopupShow(CefRefPtr browser, + bool show) {} + + /// + // Called when the browser wants to move or resize the popup widget. |rect| + // contains the new location and size in view coordinates. + /// + /*--cef()--*/ + virtual void OnPopupSize(CefRefPtr browser, + const CefRect& rect) {} + + /// + // Called when an element should be painted. Pixel values passed to this + // method are scaled relative to view coordinates based on the value of + // CefScreenInfo.device_scale_factor returned from GetScreenInfo. |type| + // indicates whether the element is the view or the popup widget. |buffer| + // contains the pixel data for the whole image. |dirtyRects| contains the set + // of rectangles in pixel coordinates that need to be repainted. |buffer| will + // be |width|*|height|*4 bytes in size and represents a BGRA image with an + // upper-left origin. + /// + /*--cef()--*/ + virtual void OnPaint(CefRefPtr browser, + PaintElementType type, + const RectList& dirtyRects, + const void* buffer, + int width, int height) =0; + + /// + // Called when the browser's cursor has changed. If |type| is CT_CUSTOM then + // |custom_cursor_info| will be populated with the custom cursor information. + /// + /*--cef()--*/ + virtual void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor, + CursorType type, + const CefCursorInfo& custom_cursor_info) {} + + /// + // Called when the user starts dragging content in the web view. Contextual + // information about the dragged content is supplied by |drag_data|. + // (|x|, |y|) is the drag start location in screen coordinates. + // OS APIs that run a system message loop may be used within the + // StartDragging call. + // + // Return false to abort the drag operation. Don't call any of + // CefBrowserHost::DragSource*Ended* methods after returning false. + // + // Return true to handle the drag operation. Call + // CefBrowserHost::DragSourceEndedAt and DragSourceSystemDragEnded either + // synchronously or asynchronously to inform the web view that the drag + // operation has ended. + /// + /*--cef()--*/ + virtual bool StartDragging(CefRefPtr browser, + CefRefPtr drag_data, + DragOperationsMask allowed_ops, + int x, int y) { return false; } + + /// + // Called when the web view wants to update the mouse cursor during a + // drag & drop operation. |operation| describes the allowed operation + // (none, move, copy, link). + /// + /*--cef()--*/ + virtual void UpdateDragCursor(CefRefPtr browser, + DragOperation operation) {} + + /// + // Called when the scroll offset has changed. + /// + /*--cef()--*/ + virtual void OnScrollOffsetChanged(CefRefPtr browser) {} +}; + +#endif // CEF_INCLUDE_CEF_RENDER_HANDLER_H_ diff --git a/include/cef_render_process_handler.h b/include/cef_render_process_handler.h new file mode 100644 index 000000000..98ab391bc --- /dev/null +++ b/include/cef_render_process_handler.h @@ -0,0 +1,168 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_RENDER_PROCESS_HANDLER_H_ +#define CEF_INCLUDE_CEF_RENDER_PROCESS_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_dom.h" +#include "include/cef_frame.h" +#include "include/cef_load_handler.h" +#include "include/cef_process_message.h" +#include "include/cef_v8.h" +#include "include/cef_values.h" + +/// +// Class used to implement render process callbacks. The methods of this class +// will be called on the render process main thread (TID_RENDERER) unless +// otherwise indicated. +/// +/*--cef(source=client)--*/ +class CefRenderProcessHandler : public virtual CefBase { + public: + typedef cef_navigation_type_t NavigationType; + + /// + // Called after the render process main thread has been created. |extra_info| + // is a read-only value originating from + // CefBrowserProcessHandler::OnRenderProcessThreadCreated(). Do not keep a + // reference to |extra_info| outside of this method. + /// + /*--cef()--*/ + virtual void OnRenderThreadCreated(CefRefPtr extra_info) {} + + /// + // Called after WebKit has been initialized. + /// + /*--cef()--*/ + virtual void OnWebKitInitialized() {} + + /// + // Called after a browser has been created. When browsing cross-origin a new + // browser will be created before the old browser with the same identifier is + // destroyed. + /// + /*--cef()--*/ + virtual void OnBrowserCreated(CefRefPtr browser) {} + + /// + // Called before a browser is destroyed. + /// + /*--cef()--*/ + virtual void OnBrowserDestroyed(CefRefPtr browser) {} + + /// + // Return the handler for browser load status events. + /// + /*--cef()--*/ + virtual CefRefPtr GetLoadHandler() { + return NULL; + } + + /// + // Called before browser navigation. Return true to cancel the navigation or + // false to allow the navigation to proceed. The |request| object cannot be + // modified in this callback. + /// + /*--cef()--*/ + virtual bool OnBeforeNavigation(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavigationType navigation_type, + bool is_redirect) { return false; } + + /// + // Called immediately after the V8 context for a frame has been created. To + // retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal() + // method. V8 handles can only be accessed from the thread on which they are + // created. A task runner for posting tasks on the associated thread can be + // retrieved via the CefV8Context::GetTaskRunner() method. + /// + /*--cef()--*/ + virtual void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) {} + + /// + // Called immediately before the V8 context for a frame is released. No + // references to the context should be kept after this method is called. + /// + /*--cef()--*/ + virtual void OnContextReleased(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) {} + + /// + // Called for global uncaught exceptions in a frame. Execution of this + // callback is disabled by default. To enable set + // CefSettings.uncaught_exception_stack_size > 0. + /// + /*--cef()--*/ + virtual void OnUncaughtException(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context, + CefRefPtr exception, + CefRefPtr stackTrace) {} + + /// + // Called when a new node in the the browser gets focus. The |node| value may + // be empty if no specific node has gained focus. The node object passed to + // this method represents a snapshot of the DOM at the time this method is + // executed. DOM objects are only valid for the scope of this method. Do not + // keep references to or attempt to access any DOM objects outside the scope + // of this method. + /// + /*--cef(optional_param=frame,optional_param=node)--*/ + virtual void OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) {} + + /// + // Called when a new message is received from a different process. Return true + // if the message was handled or false otherwise. Do not keep a reference to + // or attempt to access the message outside of this callback. + /// + /*--cef()--*/ + virtual bool OnProcessMessageReceived(CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) { + return false; + } +}; + +#endif // CEF_INCLUDE_CEF_RENDER_PROCESS_HANDLER_H_ diff --git a/include/cef_request.h b/include/cef_request.h new file mode 100644 index 000000000..8dd86791a --- /dev/null +++ b/include/cef_request.h @@ -0,0 +1,297 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_REQUEST_H_ +#define CEF_INCLUDE_CEF_REQUEST_H_ +#pragma once + +#include "include/cef_base.h" +#include +#include + +class CefPostData; +class CefPostDataElement; + +/// +// Class used to represent a web request. The methods of this class may be +// called on any thread. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefRequest : public virtual CefBase { + public: + typedef std::multimap HeaderMap; + typedef cef_resource_type_t ResourceType; + typedef cef_transition_type_t TransitionType; + + /// + // Create a new CefRequest object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is read-only. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Get the fully qualified URL. + /// + /*--cef()--*/ + virtual CefString GetURL() =0; + + /// + // Set the fully qualified URL. + /// + /*--cef()--*/ + virtual void SetURL(const CefString& url) =0; + + /// + // Get the request method type. The value will default to POST if post data + // is provided and GET otherwise. + /// + /*--cef()--*/ + virtual CefString GetMethod() =0; + + /// + // Set the request method type. + /// + /*--cef()--*/ + virtual void SetMethod(const CefString& method) =0; + + /// + // Get the post data. + /// + /*--cef()--*/ + virtual CefRefPtr GetPostData() =0; + + /// + // Set the post data. + /// + /*--cef()--*/ + virtual void SetPostData(CefRefPtr postData) =0; + + /// + // Get the header values. + /// + /*--cef()--*/ + virtual void GetHeaderMap(HeaderMap& headerMap) =0; + + /// + // Set the header values. + /// + /*--cef()--*/ + virtual void SetHeaderMap(const HeaderMap& headerMap) =0; + + /// + // Set all values at one time. + /// + /*--cef(optional_param=postData)--*/ + virtual void Set(const CefString& url, + const CefString& method, + CefRefPtr postData, + const HeaderMap& headerMap) =0; + + /// + // Get the flags used in combination with CefURLRequest. See + // cef_urlrequest_flags_t for supported values. + /// + /*--cef(default_retval=UR_FLAG_NONE)--*/ + virtual int GetFlags() =0; + + /// + // Set the flags used in combination with CefURLRequest. See + // cef_urlrequest_flags_t for supported values. + /// + /*--cef()--*/ + virtual void SetFlags(int flags) =0; + + /// + // Set the URL to the first party for cookies used in combination with + // CefURLRequest. + /// + /*--cef()--*/ + virtual CefString GetFirstPartyForCookies() =0; + + /// + // Get the URL to the first party for cookies used in combination with + // CefURLRequest. + /// + /*--cef()--*/ + virtual void SetFirstPartyForCookies(const CefString& url) =0; + + /// + // Get the resource type for this request. Only available in the browser + // process. + /// + /*--cef(default_retval=RT_SUB_RESOURCE)--*/ + virtual ResourceType GetResourceType() =0; + + /// + // Get the transition type for this request. Only available in the browser + // process and only applies to requests that represent a main frame or + // sub-frame navigation. + /// + /*--cef(default_retval=TT_EXPLICIT)--*/ + virtual TransitionType GetTransitionType() =0; +}; + + +/// +// Class used to represent post data for a web request. The methods of this +// class may be called on any thread. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefPostData : public virtual CefBase { + public: + typedef std::vector > ElementVector; + + /// + // Create a new CefPostData object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is read-only. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns the number of existing post data elements. + /// + /*--cef()--*/ + virtual size_t GetElementCount() =0; + + /// + // Retrieve the post data elements. + /// + /*--cef(count_func=elements:GetElementCount)--*/ + virtual void GetElements(ElementVector& elements) =0; + + /// + // Remove the specified post data element. Returns true if the removal + // succeeds. + /// + /*--cef()--*/ + virtual bool RemoveElement(CefRefPtr element) =0; + + /// + // Add the specified post data element. Returns true if the add succeeds. + /// + /*--cef()--*/ + virtual bool AddElement(CefRefPtr element) =0; + + /// + // Remove all existing post data elements. + /// + /*--cef()--*/ + virtual void RemoveElements() =0; +}; + + +/// +// Class used to represent a single element in the request post data. The +// methods of this class may be called on any thread. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefPostDataElement : public virtual CefBase { + public: + /// + // Post data elements may represent either bytes or files. + /// + typedef cef_postdataelement_type_t Type; + + /// + // Create a new CefPostDataElement object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is read-only. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Remove all contents from the post data element. + /// + /*--cef()--*/ + virtual void SetToEmpty() =0; + + /// + // The post data element will represent a file. + /// + /*--cef()--*/ + virtual void SetToFile(const CefString& fileName) =0; + + /// + // The post data element will represent bytes. The bytes passed + // in will be copied. + /// + /*--cef()--*/ + virtual void SetToBytes(size_t size, const void* bytes) =0; + + /// + // Return the type of this post data element. + /// + /*--cef(default_retval=PDE_TYPE_EMPTY)--*/ + virtual Type GetType() =0; + + /// + // Return the file name. + /// + /*--cef()--*/ + virtual CefString GetFile() =0; + + /// + // Return the number of bytes. + /// + /*--cef()--*/ + virtual size_t GetBytesCount() =0; + + /// + // Read up to |size| bytes into |bytes| and return the number of bytes + // actually read. + /// + /*--cef()--*/ + virtual size_t GetBytes(size_t size, void* bytes) =0; +}; + +#endif // CEF_INCLUDE_CEF_REQUEST_H_ diff --git a/include/cef_request_context.h b/include/cef_request_context.h new file mode 100644 index 000000000..32495a952 --- /dev/null +++ b/include/cef_request_context.h @@ -0,0 +1,94 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_REQUEST_CONTEXT_H_ +#define CEF_INCLUDE_CEF_REQUEST_CONTEXT_H_ +#pragma once + +#include "include/cef_request_context_handler.h" + +/// +// A request context provides request handling for a set of related browser +// objects. A request context is specified when creating a new browser object +// via the CefBrowserHost static factory methods. Browser objects with different +// request contexts will never be hosted in the same render process. Browser +// objects with the same request context may or may not be hosted in the same +// render process depending on the process model. Browser objects created +// indirectly via the JavaScript window.open function or targeted links will +// share the same render process and the same request context as the source +// browser. When running in single-process mode there is only a single render +// process (the main process) and so all browsers created in single-process mode +// will share the same request context. This will be the first request context +// passed into a CefBrowserHost static factory method and all other request +// context objects will be ignored. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefRequestContext : public virtual CefBase { + public: + /// + // Returns the global context object. + /// + /*--cef()--*/ + static CefRefPtr GetGlobalContext(); + + /// + // Creates a new context object with the specified handler. + /// + /*--cef(optional_param=handler)--*/ + static CefRefPtr CreateContext( + CefRefPtr handler); + + /// + // Returns true if this object is pointing to the same context as |that| + // object. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr other) =0; + + /// + // Returns true if this object is the global context. + /// + /*--cef()--*/ + virtual bool IsGlobal() =0; + + /// + // Returns the handler for this context if any. + /// + /*--cef()--*/ + virtual CefRefPtr GetHandler() =0; +}; + +#endif // CEF_INCLUDE_CEF_REQUEST_CONTEXT_H_ diff --git a/include/cef_request_context_handler.h b/include/cef_request_context_handler.h new file mode 100644 index 000000000..f77259efe --- /dev/null +++ b/include/cef_request_context_handler.h @@ -0,0 +1,58 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_REQUEST_CONTEXT_HANDLER_H_ +#define CEF_INCLUDE_CEF_REQUEST_CONTEXT_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_cookie.h" + +/// +// Implement this interface to provide handler implementations. +/// +/*--cef(source=client,no_debugct_check)--*/ +class CefRequestContextHandler : public virtual CefBase { + public: + /// + // Called on the IO thread to retrieve the cookie manager. The global cookie + // manager will be used if this method returns NULL. + /// + /*--cef()--*/ + virtual CefRefPtr GetCookieManager() { return NULL; } +}; + +#endif // CEF_INCLUDE_CEF_REQUEST_CONTEXT_HANDLER_H_ diff --git a/include/cef_request_handler.h b/include/cef_request_handler.h new file mode 100644 index 000000000..0f434310b --- /dev/null +++ b/include/cef_request_handler.h @@ -0,0 +1,245 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_REQUEST_HANDLER_H_ +#define CEF_INCLUDE_CEF_REQUEST_HANDLER_H_ +#pragma once + +#include "include/cef_auth_callback.h" +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_resource_handler.h" +#include "include/cef_response.h" +#include "include/cef_request.h" +#include "include/cef_web_plugin.h" + +/// +// Callback interface used for asynchronous continuation of quota requests. +/// +/*--cef(source=library)--*/ +class CefQuotaCallback : public virtual CefBase { + public: + /// + // Continue the quota request. If |allow| is true the request will be + // allowed. Otherwise, the request will be denied. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue(bool allow) =0; + + /// + // Cancel the quota request. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + + +/// +// Callback interface used for asynchronous continuation of url requests when +// invalid SSL certificates are encountered. +/// +/*--cef(source=library)--*/ +class CefAllowCertificateErrorCallback : public virtual CefBase { + public: + /// + // Continue the url request. If |allow| is true the request will be + // continued. Otherwise, the request will be canceled. + /// + /*--cef(capi_name=cont)--*/ + virtual void Continue(bool allow) =0; +}; + + +/// +// Implement this interface to handle events related to browser requests. The +// methods of this class will be called on the thread indicated. +/// +/*--cef(source=client)--*/ +class CefRequestHandler : public virtual CefBase { + public: + typedef cef_termination_status_t TerminationStatus; + + /// + // Called on the UI thread before browser navigation. Return true to cancel + // the navigation or false to allow the navigation to proceed. The |request| + // object cannot be modified in this callback. + // CefLoadHandler::OnLoadingStateChange will be called twice in all cases. + // If the navigation is allowed CefLoadHandler::OnLoadStart and + // CefLoadHandler::OnLoadEnd will be called. If the navigation is canceled + // CefLoadHandler::OnLoadError will be called with an |errorCode| value of + // ERR_ABORTED. + /// + /*--cef()--*/ + virtual bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) { + return false; + } + + /// + // Called on the IO thread before a resource request is loaded. The |request| + // object may be modified. To cancel the request return true otherwise return + // false. + /// + /*--cef()--*/ + virtual bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) { + return false; + } + + /// + // Called on the IO thread before a resource is loaded. To allow the resource + // to load normally return NULL. To specify a handler for the resource return + // a CefResourceHandler object. The |request| object should not be modified in + // this callback. + /// + /*--cef()--*/ + virtual CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) { + return NULL; + } + + /// + // Called on the IO thread when a resource load is redirected. The |old_url| + // parameter will contain the old URL. The |new_url| parameter will contain + // the new URL and can be changed if desired. + /// + /*--cef()--*/ + virtual void OnResourceRedirect(CefRefPtr browser, + CefRefPtr frame, + const CefString& old_url, + CefString& new_url) {} + + /// + // Called on the IO thread when the browser needs credentials from the user. + // |isProxy| indicates whether the host is a proxy server. |host| contains the + // hostname and |port| contains the port number. Return true to continue the + // request and call CefAuthCallback::Continue() when the authentication + // information is available. Return false to cancel the request. + /// + /*--cef(optional_param=realm)--*/ + virtual bool GetAuthCredentials(CefRefPtr browser, + CefRefPtr frame, + bool isProxy, + const CefString& host, + int port, + const CefString& realm, + const CefString& scheme, + CefRefPtr callback) { + return false; + } + + /// + // Called on the IO thread when JavaScript requests a specific storage quota + // size via the webkitStorageInfo.requestQuota function. |origin_url| is the + // origin of the page making the request. |new_size| is the requested quota + // size in bytes. Return true and call CefQuotaCallback::Continue() either in + // this method or at a later time to grant or deny the request. Return false + // to cancel the request. + /// + /*--cef()--*/ + virtual bool OnQuotaRequest(CefRefPtr browser, + const CefString& origin_url, + int64 new_size, + CefRefPtr callback) { + return false; + } + + /// + // Called on the UI thread to handle requests for URLs with an unknown + // protocol component. Set |allow_os_execution| to true to attempt execution + // via the registered OS protocol handler, if any. + // SECURITY WARNING: YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED + // ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION. + /// + /*--cef()--*/ + virtual void OnProtocolExecution(CefRefPtr browser, + const CefString& url, + bool& allow_os_execution) {} + + /// + // Called on the UI thread to handle requests for URLs with an invalid + // SSL certificate. Return true and call CefAllowCertificateErrorCallback:: + // Continue() either in this method or at a later time to continue or cancel + // the request. Return false to cancel the request immediately. If |callback| + // is empty the error cannot be recovered from and the request will be + // canceled automatically. If CefSettings.ignore_certificate_errors is set + // all invalid certificates will be accepted without calling this method. + /// + /*--cef()--*/ + virtual bool OnCertificateError( + cef_errorcode_t cert_error, + const CefString& request_url, + CefRefPtr callback) { + return false; + } + + /// + // Called on the browser process IO thread before a plugin is loaded. Return + // true to block loading of the plugin. + /// + /*--cef(optional_param=url,optional_param=policy_url)--*/ + virtual bool OnBeforePluginLoad(CefRefPtr browser, + const CefString& url, + const CefString& policy_url, + CefRefPtr info) { + return false; + } + + /// + // Called on the browser process UI thread when a plugin has crashed. + // |plugin_path| is the path of the plugin that crashed. + /// + /*--cef()--*/ + virtual void OnPluginCrashed(CefRefPtr browser, + const CefString& plugin_path) {} + + /// + // Called on the browser process UI thread when the render process + // terminates unexpectedly. |status| indicates how the process + // terminated. + /// + /*--cef()--*/ + virtual void OnRenderProcessTerminated(CefRefPtr browser, + TerminationStatus status) {} +}; + +#endif // CEF_INCLUDE_CEF_REQUEST_HANDLER_H_ diff --git a/include/cef_resource_bundle_handler.h b/include/cef_resource_bundle_handler.h new file mode 100644 index 000000000..2cd39a5eb --- /dev/null +++ b/include/cef_resource_bundle_handler.h @@ -0,0 +1,73 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_RESOURCE_BUNDLE_HANDLER_H_ +#define CEF_INCLUDE_CEF_RESOURCE_BUNDLE_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Class used to implement a custom resource bundle interface. The methods of +// this class may be called on multiple threads. +/// +/*--cef(source=client)--*/ +class CefResourceBundleHandler : public virtual CefBase { + public: + /// + // Called to retrieve a localized translation for the string specified by + // |message_id|. To provide the translation set |string| to the translation + // string and return true. To use the default translation return false. + // Supported message IDs are listed in cef_pack_strings.h. + /// + /*--cef()--*/ + virtual bool GetLocalizedString(int message_id, + CefString& string) =0; + + /// + // Called to retrieve data for the resource specified by |resource_id|. To + // provide the resource data set |data| and |data_size| to the data pointer + // and size respectively and return true. To use the default resource data + // return false. The resource data will not be copied and must remain resident + // in memory. Supported resource IDs are listed in cef_pack_resources.h. + /// + /*--cef()--*/ + virtual bool GetDataResource(int resource_id, + void*& data, + size_t& data_size) =0; +}; + +#endif // CEF_INCLUDE_CEF_RESOURCE_BUNDLE_HANDLER_H_ diff --git a/include/cef_resource_handler.h b/include/cef_resource_handler.h new file mode 100644 index 000000000..57c8b7fc0 --- /dev/null +++ b/include/cef_resource_handler.h @@ -0,0 +1,116 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_RESOURCE_HANDLER_H_ +#define CEF_INCLUDE_CEF_RESOURCE_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_callback.h" +#include "include/cef_cookie.h" +#include "include/cef_request.h" +#include "include/cef_response.h" + +/// +// Class used to implement a custom request handler interface. The methods of +// this class will always be called on the IO thread. +/// +/*--cef(source=client)--*/ +class CefResourceHandler : public virtual CefBase { + public: + /// + // Begin processing the request. To handle the request return true and call + // CefCallback::Continue() once the response header information is available + // (CefCallback::Continue() can also be called from inside this method if + // header information is available immediately). To cancel the request return + // false. + /// + /*--cef()--*/ + virtual bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) =0; + + /// + // Retrieve response header information. If the response length is not known + // set |response_length| to -1 and ReadResponse() will be called until it + // returns false. If the response length is known set |response_length| + // to a positive value and ReadResponse() will be called until it returns + // false or the specified number of bytes have been read. Use the |response| + // object to set the mime type, http status code and other optional header + // values. To redirect the request to a new URL set |redirectUrl| to the new + // URL. + /// + /*--cef()--*/ + virtual void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) =0; + + /// + // Read response data. If data is available immediately copy up to + // |bytes_to_read| bytes into |data_out|, set |bytes_read| to the number of + // bytes copied, and return true. To read the data at a later time set + // |bytes_read| to 0, return true and call CefCallback::Continue() when the + // data is available. To indicate response completion return false. + /// + /*--cef()--*/ + virtual bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) =0; + + /// + // Return true if the specified cookie can be sent with the request or false + // otherwise. If false is returned for any cookie then no cookies will be sent + // with the request. + /// + /*--cef()--*/ + virtual bool CanGetCookie(const CefCookie& cookie) { return true; } + + /// + // Return true if the specified cookie returned with the response can be set + // or false otherwise. + /// + /*--cef()--*/ + virtual bool CanSetCookie(const CefCookie& cookie) { return true; } + + /// + // Request processing has been canceled. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +#endif // CEF_INCLUDE_CEF_RESOURCE_HANDLER_H_ diff --git a/include/cef_response.h b/include/cef_response.h new file mode 100644 index 000000000..32fbef1b0 --- /dev/null +++ b/include/cef_response.h @@ -0,0 +1,120 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_RESPONSE_H_ +#define CEF_INCLUDE_CEF_RESPONSE_H_ +#pragma once + +#include "include/cef_base.h" +#include + +/// +// Class used to represent a web response. The methods of this class may be +// called on any thread. +/// +/*--cef(source=library,no_debugct_check)--*/ +class CefResponse : public virtual CefBase { + public: + typedef std::multimap HeaderMap; + + /// + // Create a new CefResponse object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is read-only. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Get the response status code. + /// + /*--cef()--*/ + virtual int GetStatus() =0; + + /// + // Set the response status code. + /// + /*--cef()--*/ + virtual void SetStatus(int status) = 0; + + /// + // Get the response status text. + /// + /*--cef()--*/ + virtual CefString GetStatusText() =0; + + /// + // Set the response status text. + /// + /*--cef()--*/ + virtual void SetStatusText(const CefString& statusText) = 0; + + /// + // Get the response mime type. + /// + /*--cef()--*/ + virtual CefString GetMimeType() = 0; + + /// + // Set the response mime type. + /// + /*--cef()--*/ + virtual void SetMimeType(const CefString& mimeType) = 0; + + /// + // Get the value for the specified response header field. + /// + /*--cef()--*/ + virtual CefString GetHeader(const CefString& name) =0; + + /// + // Get all response header fields. + /// + /*--cef()--*/ + virtual void GetHeaderMap(HeaderMap& headerMap) =0; + + /// + // Set all response header fields. + /// + /*--cef()--*/ + virtual void SetHeaderMap(const HeaderMap& headerMap) =0; +}; + +#endif // CEF_INCLUDE_CEF_RESPONSE_H_ diff --git a/include/cef_runnable.h b/include/cef_runnable.h new file mode 100644 index 000000000..29f13038b --- /dev/null +++ b/include/cef_runnable.h @@ -0,0 +1,349 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. Portions Copyright (c) +// 2006-2011 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// The contents of this file are a modified extract of base/task.h + +#ifndef CEF_INCLUDE_CEF_RUNNABLE_H_ +#define CEF_INCLUDE_CEF_RUNNABLE_H_ +#pragma once + +#if defined(BUILDING_CEF_SHARED) +// The implementation of cef_runnable.h depends on an obsolete version of +// base/tuple.h that is implemented by cef_tuple.h for client applications but +// is not compatible with the version used when building Chromium/CEF. +#error This header cannot be used when building Chromium/CEF. +#endif + +#include "include/base/cef_tuple.h" +#include "include/cef_base.h" +#include "include/cef_task.h" + +// CefRunnableMethodTraits ----------------------------------------------------- +// +// This traits-class is used by CefRunnableMethod to manage the lifetime of the +// callee object. By default, it is assumed that the callee supports AddRef +// and Release methods. A particular class can specialize this template to +// define other lifetime management. For example, if the callee is known to +// live longer than the CefRunnableMethod object, then a CefRunnableMethodTraits +// struct could be defined with empty RetainCallee and ReleaseCallee methods. +// +// The DISABLE_RUNNABLE_METHOD_REFCOUNT macro is provided as a convenient way +// for declaring a CefRunnableMethodTraits that disables refcounting. + +template +struct CefRunnableMethodTraits { + CefRunnableMethodTraits() { + } + + ~CefRunnableMethodTraits() { + } + + void RetainCallee(T* obj) { +#ifndef NDEBUG + // Catch NewCefRunnableMethod being called in an object's constructor. + // This isn't safe since the method can be invoked before the constructor + // completes, causing the object to be deleted. + obj->AddRef(); + obj->Release(); +#endif + obj->AddRef(); + } + + void ReleaseCallee(T* obj) { + obj->Release(); + } +}; + +// Convenience macro for declaring a CefRunnableMethodTraits that disables +// refcounting of a class. This is useful if you know that the callee +// will outlive the CefRunnableMethod object and thus do not need the ref +// counts. +// +// The invocation of DISABLE_RUNNABLE_METHOD_REFCOUNT should be done at the +// global namespace scope. Example: +// +// namespace foo { +// class Bar { +// ... +// }; +// } // namespace foo +// +// DISABLE_RUNNABLE_METHOD_REFCOUNT(foo::Bar); +// +// This is different from DISALLOW_COPY_AND_ASSIGN which is declared inside the +// class. +#define DISABLE_RUNNABLE_METHOD_REFCOUNT(TypeName) \ + template <> \ + struct CefRunnableMethodTraits { \ + void RetainCallee(TypeName* manager) {} \ + void ReleaseCallee(TypeName* manager) {} \ + } + +// CefRunnableMethod and CefRunnableFunction ---------------------------------- +// +// CefRunnable methods are a type of task that call a function on an object +// when they are run. We implement both an object and a set of +// NewCefRunnableMethod and NewCefRunnableFunction functions for convenience. +// These functions are overloaded and will infer the template types, +// simplifying calling code. +// +// The template definitions all use the following names: +// T - the class type of the object you're supplying +// this is not needed for the Static version of the call +// Method/Function - the signature of a pointer to the method or function you +// want to call +// Param - the parameter(s) to the method, possibly packed as a Tuple +// A - the first parameter (if any) to the method +// B - the second parameter (if any) to the method +// +// Put these all together and you get an object that can call a method whose +// signature is: +// R T::MyFunction([A[, B]]) +// +// Usage: +// CefPostTask(TID_UI, NewCefRunnableMethod(object, &Object::method[, a[, b]]) +// CefPostTask(TID_UI, NewCefRunnableFunction(&function[, a[, b]]) + +// CefRunnableMethod and NewCefRunnableMethod implementation ------------------ + +template +class CefRunnableMethod : public CefTask { + public: + CefRunnableMethod(T* obj, Method meth, const Params& params) + : obj_(obj), meth_(meth), params_(params) { + traits_.RetainCallee(obj_); + } + + ~CefRunnableMethod() { + T* obj = obj_; + obj_ = NULL; + if (obj) + traits_.ReleaseCallee(obj); + } + + virtual void Execute() { + if (obj_) + DispatchToMethod(obj_, meth_, params_); + } + + private: + T* obj_; + Method meth_; + Params params_; + CefRunnableMethodTraits traits_; + + IMPLEMENT_REFCOUNTING(CefRunnableMethod); +}; + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method) { + return new CefRunnableMethod(object, method, MakeTuple()); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a) { + return new CefRunnableMethod >(object, + method, + MakeTuple(a)); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a, const B& b) { + return new CefRunnableMethod >(object, method, + MakeTuple(a, b)); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a, const B& b, + const C& c) { + return new CefRunnableMethod >(object, method, + MakeTuple(a, b, + c)); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a, const B& b, + const C& c, const D& d) { + return new CefRunnableMethod >(object, method, + MakeTuple(a, b, + c, + d)); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a, const B& b, + const C& c, const D& d, + const E& e) { + return new CefRunnableMethod >(object, + method, + MakeTuple(a, b, c, d, + e)); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a, const B& b, + const C& c, const D& d, + const E& e, const F& f) { + return new CefRunnableMethod >(object, + method, + MakeTuple(a, b, c, d, + e, f)); +} + +template +inline CefRefPtr NewCefRunnableMethod(T* object, Method method, + const A& a, const B& b, + const C& c, const D& d, + const E& e, const F& f, + const G& g) { + return new CefRunnableMethod >(object, + method, + MakeTuple(a, b, c, + d, e, f, + g)); +} + +// CefRunnableFunction and NewCefRunnableFunction implementation -------------- + +template +class CefRunnableFunction : public CefTask { + public: + CefRunnableFunction(Function function, const Params& params) + : function_(function), params_(params) { + } + + ~CefRunnableFunction() { + } + + virtual void Execute() { + if (function_) + DispatchToFunction(function_, params_); + } + + private: + Function function_; + Params params_; + + IMPLEMENT_REFCOUNTING(CefRunnableFunction); +}; + +template +inline CefRefPtr NewCefRunnableFunction(Function function) { + return new CefRunnableFunction(function, MakeTuple()); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a) { + return new CefRunnableFunction >(function, MakeTuple(a)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b) { + return new CefRunnableFunction >(function, + MakeTuple(a, b)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b, + const C& c) { + return new CefRunnableFunction >(function, + MakeTuple(a, b, + c)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b, + const C& c, const D& d) { + return new CefRunnableFunction >(function, + MakeTuple(a, b, + c, + d)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b, + const C& c, const D& d, + const E& e) { + return new CefRunnableFunction >(function, + MakeTuple(a, b, c, d, e)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b, + const C& c, const D& d, + const E& e, const F& f) { + return new CefRunnableFunction >(function, + MakeTuple(a, b, c, d, e, f)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b, + const C& c, const D& d, + const E& e, const F& f, + const G& g) { + return new CefRunnableFunction >( + function, MakeTuple(a, b, c, d, e, f, g)); +} + +template +inline CefRefPtr NewCefRunnableFunction(Function function, + const A& a, const B& b, + const C& c, const D& d, + const E& e, const F& f, + const G& g, const H& h) { + return new CefRunnableFunction >( + function, MakeTuple(a, b, c, d, e, f, g, h)); +} + +#endif // CEF_INCLUDE_CEF_RUNNABLE_H_ diff --git a/include/cef_sandbox_win.h b/include/cef_sandbox_win.h new file mode 100644 index 000000000..9b6c48b09 --- /dev/null +++ b/include/cef_sandbox_win.h @@ -0,0 +1,92 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_CEF_SANDBOX_WIN_H_ +#define CEF_INCLUDE_CEF_SANDBOX_WIN_H_ +#pragma once + +#include "include/cef_base.h" + +#if defined(OS_WIN) + +#ifdef __cplusplus +extern "C" { +#endif + +// The sandbox is used to restrict sub-processes (renderer, plugin, GPU, etc) +// from directly accessing system resources. This helps to protect the user +// from untrusted and potentially malicious Web content. +// See http://www.chromium.org/developers/design-documents/sandbox for +// complete details. +// +// To enable the sandbox on Windows the following requirements must be met: +// 1. Use the same executable for the browser process and all sub-processes. +// 2. Link the executable with the cef_sandbox static library. +// 3. Call the cef_sandbox_info_create() function from within the executable +// (not from a separate DLL) and pass the resulting pointer into both the +// CefExecutProcess() and CefInitialize() functions via the +// |windows_sandbox_info| parameter. + +/// +// Create the sandbox information object for this process. It is safe to create +// multiple of this object and to destroy the object immediately after passing +// into the CefExecutProcess() and/or CefInitialize() functions. +/// +void* cef_sandbox_info_create(); + +/// +// Destroy the specified sandbox information object. +/// +void cef_sandbox_info_destroy(void* sandbox_info); + +#ifdef __cplusplus +} + +/// +// Manages the life span of a sandbox information object. +/// +class CefScopedSandboxInfo { + public: + CefScopedSandboxInfo() { + sandbox_info_ = cef_sandbox_info_create(); + } + ~CefScopedSandboxInfo() { + cef_sandbox_info_destroy(sandbox_info_); + } + + void* sandbox_info() const { return sandbox_info_; } + + private: + void* sandbox_info_; +}; +#endif // __cplusplus + +#endif // defined(OS_WIN) + +#endif // CEF_INCLUDE_CEF_SANDBOX_WIN_H_ diff --git a/include/cef_scheme.h b/include/cef_scheme.h new file mode 100644 index 000000000..cd8415c07 --- /dev/null +++ b/include/cef_scheme.h @@ -0,0 +1,161 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_SCHEME_H_ +#define CEF_INCLUDE_CEF_SCHEME_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_request.h" +#include "include/cef_response.h" +#include "include/cef_resource_handler.h" + +class CefSchemeHandlerFactory; + + +/// +// Register a scheme handler factory for the specified |scheme_name| and +// optional |domain_name|. An empty |domain_name| value for a standard scheme +// will cause the factory to match all domain names. The |domain_name| value +// will be ignored for non-standard schemes. If |scheme_name| is a built-in +// scheme and no handler is returned by |factory| then the built-in scheme +// handler factory will be called. If |scheme_name| is a custom scheme then +// also implement the CefApp::OnRegisterCustomSchemes() method in all processes. +// This function may be called multiple times to change or remove the factory +// that matches the specified |scheme_name| and optional |domain_name|. +// Returns false if an error occurs. This function may be called on any thread +// in the browser process. +/// +/*--cef(optional_param=domain_name,optional_param=factory)--*/ +bool CefRegisterSchemeHandlerFactory( + const CefString& scheme_name, + const CefString& domain_name, + CefRefPtr factory); + +/// +// Clear all registered scheme handler factories. Returns false on error. This +// function may be called on any thread in the browser process. +/// +/*--cef()--*/ +bool CefClearSchemeHandlerFactories(); + + +/// +// Class that manages custom scheme registrations. +/// +/*--cef(source=library)--*/ +class CefSchemeRegistrar : public virtual CefBase { + public: + /// + // Register a custom scheme. This method should not be called for the built-in + // HTTP, HTTPS, FILE, FTP, ABOUT and DATA schemes. + // + // If |is_standard| is true the scheme will be treated as a standard scheme. + // Standard schemes are subject to URL canonicalization and parsing rules as + // defined in the Common Internet Scheme Syntax RFC 1738 Section 3.1 available + // at http://www.ietf.org/rfc/rfc1738.txt + // + // In particular, the syntax for standard scheme URLs must be of the form: + //
+  //  [scheme]://[username]:[password]@[host]:[port]/[url-path]
+  // 
+ // Standard scheme URLs must have a host component that is a fully qualified + // domain name as defined in Section 3.5 of RFC 1034 [13] and Section 2.1 of + // RFC 1123. These URLs will be canonicalized to "scheme://host/path" in the + // simplest case and "scheme://username:password@host:port/path" in the most + // explicit case. For example, "scheme:host/path" and "scheme:///host/path" + // will both be canonicalized to "scheme://host/path". The origin of a + // standard scheme URL is the combination of scheme, host and port (i.e., + // "scheme://host:port" in the most explicit case). + // + // For non-standard scheme URLs only the "scheme:" component is parsed and + // canonicalized. The remainder of the URL will be passed to the handler + // as-is. For example, "scheme:///some%20text" will remain the same. + // Non-standard scheme URLs cannot be used as a target for form submission. + // + // If |is_local| is true the scheme will be treated as local (i.e., with the + // same security rules as those applied to "file" URLs). Normal pages cannot + // link to or access local URLs. Also, by default, local URLs can only perform + // XMLHttpRequest calls to the same URL (origin + path) that originated the + // request. To allow XMLHttpRequest calls from a local URL to other URLs with + // the same origin set the CefSettings.file_access_from_file_urls_allowed + // value to true. To allow XMLHttpRequest calls from a local URL to all + // origins set the CefSettings.universal_access_from_file_urls_allowed value + // to true. + // + // If |is_display_isolated| is true the scheme will be treated as display- + // isolated. This means that pages cannot display these URLs unless they are + // from the same scheme. For example, pages in another origin cannot create + // iframes or hyperlinks to URLs with this scheme. + // + // This function may be called on any thread. It should only be called once + // per unique |scheme_name| value. If |scheme_name| is already registered or + // if an error occurs this method will return false. + /// + /*--cef()--*/ + virtual bool AddCustomScheme(const CefString& scheme_name, + bool is_standard, + bool is_local, + bool is_display_isolated) =0; +}; + + +/// +// Class that creates CefResourceHandler instances for handling scheme requests. +// The methods of this class will always be called on the IO thread. +/// +/*--cef(source=client)--*/ +class CefSchemeHandlerFactory : public virtual CefBase { + public: + /// + // Return a new resource handler instance to handle the request or an empty + // reference to allow default handling of the request. |browser| and |frame| + // will be the browser window and frame respectively that originated the + // request or NULL if the request did not originate from a browser window + // (for example, if the request came from CefURLRequest). The |request| object + // passed to this method will not contain cookie data. + /// + /*--cef(optional_param=browser,optional_param=frame)--*/ + virtual CefRefPtr Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) =0; +}; + +#endif // CEF_INCLUDE_CEF_SCHEME_H_ diff --git a/include/cef_stream.h b/include/cef_stream.h new file mode 100644 index 000000000..3d0633c25 --- /dev/null +++ b/include/cef_stream.h @@ -0,0 +1,242 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_STREAM_H_ +#define CEF_INCLUDE_CEF_STREAM_H_ + +#include "include/cef_base.h" + +/// +// Interface the client can implement to provide a custom stream reader. The +// methods of this class may be called on any thread. +/// +/*--cef(source=client)--*/ +class CefReadHandler : public virtual CefBase { + public: + /// + // Read raw binary data. + /// + /*--cef()--*/ + virtual size_t Read(void* ptr, size_t size, size_t n) =0; + + /// + // Seek to the specified offset position. |whence| may be any one of + // SEEK_CUR, SEEK_END or SEEK_SET. Return zero on success and non-zero on + // failure. + /// + /*--cef()--*/ + virtual int Seek(int64 offset, int whence) =0; + + /// + // Return the current offset position. + /// + /*--cef()--*/ + virtual int64 Tell() =0; + + /// + // Return non-zero if at end of file. + /// + /*--cef()--*/ + virtual int Eof() =0; + + /// + // Return true if this handler performs work like accessing the file system + // which may block. Used as a hint for determining the thread to access the + // handler from. + /// + /*--cef()--*/ + virtual bool MayBlock() =0; +}; + + +/// +// Class used to read data from a stream. The methods of this class may be +// called on any thread. +/// +/*--cef(source=library)--*/ +class CefStreamReader : public virtual CefBase { + public: + /// + // Create a new CefStreamReader object from a file. + /// + /*--cef()--*/ + static CefRefPtr CreateForFile(const CefString& fileName); + /// + // Create a new CefStreamReader object from data. + /// + /*--cef()--*/ + static CefRefPtr CreateForData(void* data, size_t size); + /// + // Create a new CefStreamReader object from a custom handler. + /// + /*--cef()--*/ + static CefRefPtr CreateForHandler( + CefRefPtr handler); + + /// + // Read raw binary data. + /// + /*--cef()--*/ + virtual size_t Read(void* ptr, size_t size, size_t n) =0; + + /// + // Seek to the specified offset position. |whence| may be any one of + // SEEK_CUR, SEEK_END or SEEK_SET. Returns zero on success and non-zero on + // failure. + /// + /*--cef()--*/ + virtual int Seek(int64 offset, int whence) =0; + + /// + // Return the current offset position. + /// + /*--cef()--*/ + virtual int64 Tell() =0; + + /// + // Return non-zero if at end of file. + /// + /*--cef()--*/ + virtual int Eof() =0; + + /// + // Returns true if this reader performs work like accessing the file system + // which may block. Used as a hint for determining the thread to access the + // reader from. + /// + /*--cef()--*/ + virtual bool MayBlock() =0; +}; + + +/// +// Interface the client can implement to provide a custom stream writer. The +// methods of this class may be called on any thread. +/// +/*--cef(source=client)--*/ +class CefWriteHandler : public virtual CefBase { + public: + /// + // Write raw binary data. + /// + /*--cef()--*/ + virtual size_t Write(const void* ptr, size_t size, size_t n) =0; + + /// + // Seek to the specified offset position. |whence| may be any one of + // SEEK_CUR, SEEK_END or SEEK_SET. Return zero on success and non-zero on + // failure. + /// + /*--cef()--*/ + virtual int Seek(int64 offset, int whence) =0; + + /// + // Return the current offset position. + /// + /*--cef()--*/ + virtual int64 Tell() =0; + + /// + // Flush the stream. + /// + /*--cef()--*/ + virtual int Flush() =0; + + /// + // Return true if this handler performs work like accessing the file system + // which may block. Used as a hint for determining the thread to access the + // handler from. + /// + /*--cef()--*/ + virtual bool MayBlock() =0; +}; + + +/// +// Class used to write data to a stream. The methods of this class may be called +// on any thread. +/// +/*--cef(source=library)--*/ +class CefStreamWriter : public virtual CefBase { + public: + /// + // Create a new CefStreamWriter object for a file. + /// + /*--cef()--*/ + static CefRefPtr CreateForFile(const CefString& fileName); + /// + // Create a new CefStreamWriter object for a custom handler. + /// + /*--cef()--*/ + static CefRefPtr CreateForHandler( + CefRefPtr handler); + + /// + // Write raw binary data. + /// + /*--cef()--*/ + virtual size_t Write(const void* ptr, size_t size, size_t n) =0; + + /// + // Seek to the specified offset position. |whence| may be any one of + // SEEK_CUR, SEEK_END or SEEK_SET. Returns zero on success and non-zero on + // failure. + /// + /*--cef()--*/ + virtual int Seek(int64 offset, int whence) =0; + + /// + // Return the current offset position. + /// + /*--cef()--*/ + virtual int64 Tell() =0; + + /// + // Flush the stream. + /// + /*--cef()--*/ + virtual int Flush() =0; + + /// + // Returns true if this writer performs work like accessing the file system + // which may block. Used as a hint for determining the thread to access the + // writer from. + /// + /*--cef()--*/ + virtual bool MayBlock() =0; +}; + +#endif // CEF_INCLUDE_CEF_STREAM_H_ diff --git a/include/cef_string_visitor.h b/include/cef_string_visitor.h new file mode 100644 index 000000000..549371473 --- /dev/null +++ b/include/cef_string_visitor.h @@ -0,0 +1,55 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_STRING_VISITOR_H_ +#define CEF_INCLUDE_CEF_STRING_VISITOR_H_ + +#include "include/cef_base.h" + +/// +// Implement this interface to receive string values asynchronously. +/// +/*--cef(source=client)--*/ +class CefStringVisitor : public virtual CefBase { + public: + /// + // Method that will be executed. + /// + /*--cef(optional_param=string)--*/ + virtual void Visit(const CefString& string) =0; +}; + +#endif // CEF_INCLUDE_CEF_STRING_VISITOR_H_ diff --git a/include/cef_task.h b/include/cef_task.h new file mode 100644 index 000000000..0ecaa7526 --- /dev/null +++ b/include/cef_task.h @@ -0,0 +1,148 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_TASK_H_ +#define CEF_INCLUDE_CEF_TASK_H_ + +#include "include/cef_base.h" + +typedef cef_thread_id_t CefThreadId; + +/// +// Implement this interface for asynchronous task execution. If the task is +// posted successfully and if the associated message loop is still running then +// the Execute() method will be called on the target thread. If the task fails +// to post then the task object may be destroyed on the source thread instead of +// the target thread. For this reason be cautious when performing work in the +// task object destructor. +/// +/*--cef(source=client)--*/ +class CefTask : public virtual CefBase { + public: + /// + // Method that will be executed on the target thread. + /// + /*--cef()--*/ + virtual void Execute() =0; +}; + +/// +// Class that asynchronously executes tasks on the associated thread. It is safe +// to call the methods of this class on any thread. +// +// CEF maintains multiple internal threads that are used for handling different +// types of tasks in different processes. The cef_thread_id_t definitions in +// cef_types.h list the common CEF threads. Task runners are also available for +// other CEF threads as appropriate (for example, V8 WebWorker threads). +/// +/*--cef(source=library)--*/ +class CefTaskRunner : public virtual CefBase { + public: + /// + // Returns the task runner for the current thread. Only CEF threads will have + // task runners. An empty reference will be returned if this method is called + // on an invalid thread. + /// + /*--cef()--*/ + static CefRefPtr GetForCurrentThread(); + + /// + // Returns the task runner for the specified CEF thread. + /// + /*--cef()--*/ + static CefRefPtr GetForThread(CefThreadId threadId); + + /// + // Returns true if this object is pointing to the same task runner as |that| + // object. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr that) =0; + + /// + // Returns true if this task runner belongs to the current thread. + /// + /*--cef()--*/ + virtual bool BelongsToCurrentThread() =0; + + /// + // Returns true if this task runner is for the specified CEF thread. + /// + /*--cef()--*/ + virtual bool BelongsToThread(CefThreadId threadId) =0; + + /// + // Post a task for execution on the thread associated with this task runner. + // Execution will occur asynchronously. + /// + /*--cef()--*/ + virtual bool PostTask(CefRefPtr task) =0; + + /// + // Post a task for delayed execution on the thread associated with this task + // runner. Execution will occur asynchronously. Delayed tasks are not + // supported on V8 WebWorker threads and will be executed without the + // specified delay. + /// + /*--cef()--*/ + virtual bool PostDelayedTask(CefRefPtr task, int64 delay_ms) =0; +}; + + +/// +// Returns true if called on the specified thread. Equivalent to using +// CefTaskRunner::GetForThread(threadId)->BelongsToCurrentThread(). +/// +/*--cef()--*/ +bool CefCurrentlyOn(CefThreadId threadId); + +/// +// Post a task for execution on the specified thread. Equivalent to +// using CefTaskRunner::GetForThread(threadId)->PostTask(task). +/// +/*--cef()--*/ +bool CefPostTask(CefThreadId threadId, CefRefPtr task); + +/// +// Post a task for delayed execution on the specified thread. Equivalent to +// using CefTaskRunner::GetForThread(threadId)->PostDelayedTask(task, delay_ms). +/// +/*--cef()--*/ +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, + int64 delay_ms); + + +#endif // CEF_INCLUDE_CEF_TASK_H_ diff --git a/include/cef_trace.h b/include/cef_trace.h new file mode 100644 index 000000000..5b977c6e5 --- /dev/null +++ b/include/cef_trace.h @@ -0,0 +1,111 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. Portons copyright (c) 2012 +// Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +// See cef_trace_event.h for trace macros and additonal documentation. + +#ifndef CEF_INCLUDE_CEF_TRACE_H_ +#define CEF_INCLUDE_CEF_TRACE_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_callback.h" + +/// +// Implement this interface to receive notification when tracing has completed. +// The methods of this class will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefEndTracingCallback : public virtual CefBase { + public: + /// + // Called after all processes have sent their trace data. |tracing_file| is + // the path at which tracing data was written. The client is responsible for + // deleting |tracing_file|. + /// + /*--cef()--*/ + virtual void OnEndTracingComplete(const CefString& tracing_file) =0; +}; + + +/// +// Start tracing events on all processes. Tracing is initialized asynchronously +// and |callback| will be executed on the UI thread after initialization is +// complete. +// +// If CefBeginTracing was called previously, or if a CefEndTracingAsync call is +// pending, CefBeginTracing will fail and return false. +// +// |categories| is a comma-delimited list of category wildcards. A category can +// have an optional '-' prefix to make it an excluded category. Having both +// included and excluded categories in the same list is not supported. +// +// Example: "test_MyTest*" +// Example: "test_MyTest*,test_OtherStuff" +// Example: "-excluded_category1,-excluded_category2" +// +// This function must be called on the browser process UI thread. +/// +/*--cef(optional_param=categories,optional_param=callback)--*/ +bool CefBeginTracing(const CefString& categories, + CefRefPtr callback); + +/// +// Stop tracing events on all processes. +// +// This function will fail and return false if a previous call to +// CefEndTracingAsync is already pending or if CefBeginTracing was not called. +// +// |tracing_file| is the path at which tracing data will be written and +// |callback| is the callback that will be executed once all processes have +// sent their trace data. If |tracing_file| is empty a new temporary file path +// will be used. If |callback| is empty no trace data will be written. +// +// This function must be called on the browser process UI thread. +/// +/*--cef(optional_param=tracing_file,optional_param=callback)--*/ +bool CefEndTracing(const CefString& tracing_file, + CefRefPtr callback); + +/// +// Returns the current system trace time or, if none is defined, the current +// high-res time. Can be used by clients to synchronize with the time +// information in trace events. +/// +/*--cef()--*/ +int64 CefNowFromSystemTraceTime(); + +#endif // CEF_INCLUDE_CEF_TRACE_H_ diff --git a/include/cef_url.h b/include/cef_url.h new file mode 100644 index 000000000..d2def08e9 --- /dev/null +++ b/include/cef_url.h @@ -0,0 +1,77 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_URL_H_ +#define CEF_INCLUDE_CEF_URL_H_ +#pragma once + +#include + +#include "include/cef_base.h" + +/// +// Parse the specified |url| into its component parts. +// Returns false if the URL is empty or invalid. +/// +/*--cef()--*/ +bool CefParseURL(const CefString& url, + CefURLParts& parts); + +/// +// Creates a URL from the specified |parts|, which must contain a non-empty +// spec or a non-empty host and path (at a minimum), but not both. +// Returns false if |parts| isn't initialized as described. +/// +/*--cef()--*/ +bool CefCreateURL(const CefURLParts& parts, + CefString& url); + +/// +// Returns the mime type for the specified file extension or an empty string if +// unknown. +/// +/*--cef()--*/ +CefString CefGetMimeType(const CefString& extension); + +// Get the extensions associated with the given mime type. This should be passed +// in lower case. There could be multiple extensions for a given mime type, like +// "html,htm" for "text/html", or "txt,text,html,..." for "text/*". Any existing +// elements in the provided vector will not be erased. +/*--cef()--*/ +void CefGetExtensionsForMimeType(const CefString& mime_type, + std::vector& extensions); + +#endif // CEF_INCLUDE_CEF_URL_H_ diff --git a/include/cef_urlrequest.h b/include/cef_urlrequest.h new file mode 100644 index 000000000..1a4e839fe --- /dev/null +++ b/include/cef_urlrequest.h @@ -0,0 +1,183 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_URLREQUEST_H_ +#define CEF_INCLUDE_CEF_URLREQUEST_H_ +#pragma once + +#include "include/cef_auth_callback.h" +#include "include/cef_base.h" +#include "include/cef_request.h" +#include "include/cef_response.h" + +class CefURLRequestClient; + +/// +// Class used to make a URL request. URL requests are not associated with a +// browser instance so no CefClient callbacks will be executed. URL requests +// can be created on any valid CEF thread in either the browser or render +// process. Once created the methods of the URL request object must be accessed +// on the same thread that created it. +/// +/*--cef(source=library)--*/ +class CefURLRequest : public virtual CefBase { + public: + typedef cef_urlrequest_status_t Status; + typedef cef_errorcode_t ErrorCode; + + /// + // Create a new URL request. Only GET, POST, HEAD, DELETE and PUT request + // methods are supported. Multiple post data elements are not supported and + // elements of type PDE_TYPE_FILE are only supported for requests originating + // from the browser process. Requests originating from the render process will + // receive the same handling as requests originating from Web content -- if + // the response contains Content-Disposition or Mime-Type header values that + // would not normally be rendered then the response may receive special + // handling inside the browser (for example, via the file download code path + // instead of the URL request code path). The |request| object will be marked + // as read-only after calling this method. + /// + /*--cef()--*/ + static CefRefPtr Create( + CefRefPtr request, + CefRefPtr client); + + /// + // Returns the request object used to create this URL request. The returned + // object is read-only and should not be modified. + /// + /*--cef()--*/ + virtual CefRefPtr GetRequest() =0; + + /// + // Returns the client. + /// + /*--cef()--*/ + virtual CefRefPtr GetClient() =0; + + /// + // Returns the request status. + /// + /*--cef(default_retval=UR_UNKNOWN)--*/ + virtual Status GetRequestStatus() =0; + + /// + // Returns the request error if status is UR_CANCELED or UR_FAILED, or 0 + // otherwise. + /// + /*--cef(default_retval=ERR_NONE)--*/ + virtual ErrorCode GetRequestError() =0; + + /// + // Returns the response, or NULL if no response information is available. + // Response information will only be available after the upload has completed. + // The returned object is read-only and should not be modified. + /// + /*--cef()--*/ + virtual CefRefPtr GetResponse() =0; + + /// + // Cancel the request. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +/// +// Interface that should be implemented by the CefURLRequest client. The +// methods of this class will be called on the same thread that created the +// request unless otherwise documented. +/// +/*--cef(source=client)--*/ +class CefURLRequestClient : public virtual CefBase { + public: + /// + // Notifies the client that the request has completed. Use the + // CefURLRequest::GetRequestStatus method to determine if the request was + // successful or not. + /// + /*--cef()--*/ + virtual void OnRequestComplete(CefRefPtr request) =0; + + /// + // Notifies the client of upload progress. |current| denotes the number of + // bytes sent so far and |total| is the total size of uploading data (or -1 if + // chunked upload is enabled). This method will only be called if the + // UR_FLAG_REPORT_UPLOAD_PROGRESS flag is set on the request. + /// + /*--cef()--*/ + virtual void OnUploadProgress(CefRefPtr request, + int64 current, + int64 total) =0; + + /// + // Notifies the client of download progress. |current| denotes the number of + // bytes received up to the call and |total| is the expected total size of the + // response (or -1 if not determined). + /// + /*--cef()--*/ + virtual void OnDownloadProgress(CefRefPtr request, + int64 current, + int64 total) =0; + + /// + // Called when some part of the response is read. |data| contains the current + // bytes received since the last call. This method will not be called if the + // UR_FLAG_NO_DOWNLOAD_DATA flag is set on the request. + /// + /*--cef()--*/ + virtual void OnDownloadData(CefRefPtr request, + const void* data, + size_t data_length) =0; + + /// + // Called on the IO thread when the browser needs credentials from the user. + // |isProxy| indicates whether the host is a proxy server. |host| contains the + // hostname and |port| contains the port number. Return true to continue the + // request and call CefAuthCallback::Continue() when the authentication + // information is available. Return false to cancel the request. This method + // will only be called for requests initiated from the browser process. + /// + /*--cef(optional_param=realm)--*/ + virtual bool GetAuthCredentials(bool isProxy, + const CefString& host, + int port, + const CefString& realm, + const CefString& scheme, + CefRefPtr callback) =0; +}; + +#endif // CEF_INCLUDE_CEF_URLREQUEST_H_ diff --git a/include/cef_v8.h b/include/cef_v8.h new file mode 100644 index 000000000..3f05b802e --- /dev/null +++ b/include/cef_v8.h @@ -0,0 +1,879 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + + +#ifndef CEF_INCLUDE_CEF_V8_H_ +#define CEF_INCLUDE_CEF_V8_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_task.h" +#include + +class CefV8Exception; +class CefV8Handler; +class CefV8StackFrame; +class CefV8Value; + + +/// +// Register a new V8 extension with the specified JavaScript extension code and +// handler. Functions implemented by the handler are prototyped using the +// keyword 'native'. The calling of a native function is restricted to the scope +// in which the prototype of the native function is defined. This function may +// only be called on the render process main thread. +// +// Example JavaScript extension code: +//
+//   // create the 'example' global object if it doesn't already exist.
+//   if (!example)
+//     example = {};
+//   // create the 'example.test' global object if it doesn't already exist.
+//   if (!example.test)
+//     example.test = {};
+//   (function() {
+//     // Define the function 'example.test.myfunction'.
+//     example.test.myfunction = function() {
+//       // Call CefV8Handler::Execute() with the function name 'MyFunction'
+//       // and no arguments.
+//       native function MyFunction();
+//       return MyFunction();
+//     };
+//     // Define the getter function for parameter 'example.test.myparam'.
+//     example.test.__defineGetter__('myparam', function() {
+//       // Call CefV8Handler::Execute() with the function name 'GetMyParam'
+//       // and no arguments.
+//       native function GetMyParam();
+//       return GetMyParam();
+//     });
+//     // Define the setter function for parameter 'example.test.myparam'.
+//     example.test.__defineSetter__('myparam', function(b) {
+//       // Call CefV8Handler::Execute() with the function name 'SetMyParam'
+//       // and a single argument.
+//       native function SetMyParam();
+//       if(b) SetMyParam(b);
+//     });
+//
+//     // Extension definitions can also contain normal JavaScript variables
+//     // and functions.
+//     var myint = 0;
+//     example.test.increment = function() {
+//       myint += 1;
+//       return myint;
+//     };
+//   })();
+// 
+// Example usage in the page: +//
+//   // Call the function.
+//   example.test.myfunction();
+//   // Set the parameter.
+//   example.test.myparam = value;
+//   // Get the parameter.
+//   value = example.test.myparam;
+//   // Call another function.
+//   example.test.increment();
+// 
+/// +/*--cef(optional_param=handler)--*/ +bool CefRegisterExtension(const CefString& extension_name, + const CefString& javascript_code, + CefRefPtr handler); + + +/// +// Class representing a V8 context handle. V8 handles can only be accessed from +// the thread on which they are created. Valid threads for creating a V8 handle +// include the render process main thread (TID_RENDERER) and WebWorker threads. +// A task runner for posting tasks on the associated thread can be retrieved via +// the CefV8Context::GetTaskRunner() method. +/// +/*--cef(source=library)--*/ +class CefV8Context : public virtual CefBase { + public: + /// + // Returns the current (top) context object in the V8 context stack. + /// + /*--cef()--*/ + static CefRefPtr GetCurrentContext(); + + /// + // Returns the entered (bottom) context object in the V8 context stack. + /// + /*--cef()--*/ + static CefRefPtr GetEnteredContext(); + + /// + // Returns true if V8 is currently inside a context. + /// + /*--cef()--*/ + static bool InContext(); + + /// + // Returns the task runner associated with this context. V8 handles can only + // be accessed from the thread on which they are created. This method can be + // called on any render process thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetTaskRunner() =0; + + /// + // Returns true if the underlying handle is valid and it can be accessed on + // the current thread. Do not call any other methods if this method returns + // false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns the browser for this context. This method will return an empty + // reference for WebWorker contexts. + /// + /*--cef()--*/ + virtual CefRefPtr GetBrowser() =0; + + /// + // Returns the frame for this context. This method will return an empty + // reference for WebWorker contexts. + /// + /*--cef()--*/ + virtual CefRefPtr GetFrame() =0; + + /// + // Returns the global object for this context. The context must be entered + // before calling this method. + /// + /*--cef()--*/ + virtual CefRefPtr GetGlobal() =0; + + /// + // Enter this context. A context must be explicitly entered before creating a + // V8 Object, Array, Function or Date asynchronously. Exit() must be called + // the same number of times as Enter() before releasing this context. V8 + // objects belong to the context in which they are created. Returns true if + // the scope was entered successfully. + /// + /*--cef()--*/ + virtual bool Enter() =0; + + /// + // Exit this context. Call this method only after calling Enter(). Returns + // true if the scope was exited successfully. + /// + /*--cef()--*/ + virtual bool Exit() =0; + + /// + // Returns true if this object is pointing to the same handle as |that| + // object. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr that) =0; + + /// + // Evaluates the specified JavaScript code using this context's global object. + // On success |retval| will be set to the return value, if any, and the + // function will return true. On failure |exception| will be set to the + // exception, if any, and the function will return false. + /// + /*--cef()--*/ + virtual bool Eval(const CefString& code, + CefRefPtr& retval, + CefRefPtr& exception) =0; +}; + + +typedef std::vector > CefV8ValueList; + +/// +// Interface that should be implemented to handle V8 function calls. The methods +// of this class will be called on the thread associated with the V8 function. +/// +/*--cef(source=client)--*/ +class CefV8Handler : public virtual CefBase { + public: + /// + // Handle execution of the function identified by |name|. |object| is the + // receiver ('this' object) of the function. |arguments| is the list of + // arguments passed to the function. If execution succeeds set |retval| to the + // function return value. If execution fails set |exception| to the exception + // that will be thrown. Return true if execution was handled. + /// + /*--cef()--*/ + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) =0; +}; + +/// +// Interface that should be implemented to handle V8 accessor calls. Accessor +// identifiers are registered by calling CefV8Value::SetValue(). The methods +// of this class will be called on the thread associated with the V8 accessor. +/// +/*--cef(source=client)--*/ +class CefV8Accessor : public virtual CefBase { + public: + /// + // Handle retrieval the accessor value identified by |name|. |object| is the + // receiver ('this' object) of the accessor. If retrieval succeeds set + // |retval| to the return value. If retrieval fails set |exception| to the + // exception that will be thrown. Return true if accessor retrieval was + // handled. + /// + /*--cef()--*/ + virtual bool Get(const CefString& name, + const CefRefPtr object, + CefRefPtr& retval, + CefString& exception) =0; + + /// + // Handle assignment of the accessor value identified by |name|. |object| is + // the receiver ('this' object) of the accessor. |value| is the new value + // being assigned to the accessor. If assignment fails set |exception| to the + // exception that will be thrown. Return true if accessor assignment was + // handled. + /// + /*--cef()--*/ + virtual bool Set(const CefString& name, + const CefRefPtr object, + const CefRefPtr value, + CefString& exception) =0; +}; + +/// +// Class representing a V8 exception. The methods of this class may be called on +// any render process thread. +/// +/*--cef(source=library)--*/ +class CefV8Exception : public virtual CefBase { + public: + /// + // Returns the exception message. + /// + /*--cef()--*/ + virtual CefString GetMessage() =0; + + /// + // Returns the line of source code that the exception occurred within. + /// + /*--cef()--*/ + virtual CefString GetSourceLine() =0; + + /// + // Returns the resource name for the script from where the function causing + // the error originates. + /// + /*--cef()--*/ + virtual CefString GetScriptResourceName() =0; + + /// + // Returns the 1-based number of the line where the error occurred or 0 if the + // line number is unknown. + /// + /*--cef()--*/ + virtual int GetLineNumber() =0; + + /// + // Returns the index within the script of the first character where the error + // occurred. + /// + /*--cef()--*/ + virtual int GetStartPosition() =0; + + /// + // Returns the index within the script of the last character where the error + // occurred. + /// + /*--cef()--*/ + virtual int GetEndPosition() =0; + + /// + // Returns the index within the line of the first character where the error + // occurred. + /// + /*--cef()--*/ + virtual int GetStartColumn() =0; + + /// + // Returns the index within the line of the last character where the error + // occurred. + /// + /*--cef()--*/ + virtual int GetEndColumn() =0; +}; + +/// +// Class representing a V8 value handle. V8 handles can only be accessed from +// the thread on which they are created. Valid threads for creating a V8 handle +// include the render process main thread (TID_RENDERER) and WebWorker threads. +// A task runner for posting tasks on the associated thread can be retrieved via +// the CefV8Context::GetTaskRunner() method. +/// +/*--cef(source=library)--*/ +class CefV8Value : public virtual CefBase { + public: + typedef cef_v8_accesscontrol_t AccessControl; + typedef cef_v8_propertyattribute_t PropertyAttribute; + + /// + // Create a new CefV8Value object of type undefined. + /// + /*--cef()--*/ + static CefRefPtr CreateUndefined(); + + /// + // Create a new CefV8Value object of type null. + /// + /*--cef()--*/ + static CefRefPtr CreateNull(); + + /// + // Create a new CefV8Value object of type bool. + /// + /*--cef()--*/ + static CefRefPtr CreateBool(bool value); + + /// + // Create a new CefV8Value object of type int. + /// + /*--cef()--*/ + static CefRefPtr CreateInt(int32 value); + + /// + // Create a new CefV8Value object of type unsigned int. + /// + /*--cef()--*/ + static CefRefPtr CreateUInt(uint32 value); + + /// + // Create a new CefV8Value object of type double. + /// + /*--cef()--*/ + static CefRefPtr CreateDouble(double value); + + /// + // Create a new CefV8Value object of type Date. This method should only be + // called from within the scope of a CefV8ContextHandler, CefV8Handler or + // CefV8Accessor callback, or in combination with calling Enter() and Exit() + // on a stored CefV8Context reference. + /// + /*--cef()--*/ + static CefRefPtr CreateDate(const CefTime& date); + + /// + // Create a new CefV8Value object of type string. + /// + /*--cef(optional_param=value)--*/ + static CefRefPtr CreateString(const CefString& value); + + /// + // Create a new CefV8Value object of type object with optional accessor. This + // method should only be called from within the scope of a + // CefV8ContextHandler, CefV8Handler or CefV8Accessor callback, or in + // combination with calling Enter() and Exit() on a stored CefV8Context + // reference. + /// + /*--cef(optional_param=accessor)--*/ + static CefRefPtr CreateObject(CefRefPtr accessor); + + /// + // Create a new CefV8Value object of type array with the specified |length|. + // If |length| is negative the returned array will have length 0. This method + // should only be called from within the scope of a CefV8ContextHandler, + // CefV8Handler or CefV8Accessor callback, or in combination with calling + // Enter() and Exit() on a stored CefV8Context reference. + /// + /*--cef()--*/ + static CefRefPtr CreateArray(int length); + + /// + // Create a new CefV8Value object of type function. This method should only be + // called from within the scope of a CefV8ContextHandler, CefV8Handler or + // CefV8Accessor callback, or in combination with calling Enter() and Exit() + // on a stored CefV8Context reference. + /// + /*--cef()--*/ + static CefRefPtr CreateFunction(const CefString& name, + CefRefPtr handler); + + /// + // Returns true if the underlying handle is valid and it can be accessed on + // the current thread. Do not call any other methods if this method returns + // false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // True if the value type is undefined. + /// + /*--cef()--*/ + virtual bool IsUndefined() =0; + + /// + // True if the value type is null. + /// + /*--cef()--*/ + virtual bool IsNull() =0; + + /// + // True if the value type is bool. + /// + /*--cef()--*/ + virtual bool IsBool() =0; + + /// + // True if the value type is int. + /// + /*--cef()--*/ + virtual bool IsInt() =0; + + /// + // True if the value type is unsigned int. + /// + /*--cef()--*/ + virtual bool IsUInt() =0; + + /// + // True if the value type is double. + /// + /*--cef()--*/ + virtual bool IsDouble() =0; + + /// + // True if the value type is Date. + /// + /*--cef()--*/ + virtual bool IsDate() =0; + + /// + // True if the value type is string. + /// + /*--cef()--*/ + virtual bool IsString() =0; + + /// + // True if the value type is object. + /// + /*--cef()--*/ + virtual bool IsObject() =0; + + /// + // True if the value type is array. + /// + /*--cef()--*/ + virtual bool IsArray() =0; + + /// + // True if the value type is function. + /// + /*--cef()--*/ + virtual bool IsFunction() =0; + + /// + // Returns true if this object is pointing to the same handle as |that| + // object. + /// + /*--cef()--*/ + virtual bool IsSame(CefRefPtr that) =0; + + /// + // Return a bool value. The underlying data will be converted to if + // necessary. + /// + /*--cef()--*/ + virtual bool GetBoolValue() =0; + + /// + // Return an int value. The underlying data will be converted to if + // necessary. + /// + /*--cef()--*/ + virtual int32 GetIntValue() =0; + + /// + // Return an unisgned int value. The underlying data will be converted to if + // necessary. + /// + /*--cef()--*/ + virtual uint32 GetUIntValue() =0; + + /// + // Return a double value. The underlying data will be converted to if + // necessary. + /// + /*--cef()--*/ + virtual double GetDoubleValue() =0; + + /// + // Return a Date value. The underlying data will be converted to if + // necessary. + /// + /*--cef()--*/ + virtual CefTime GetDateValue() =0; + + /// + // Return a string value. The underlying data will be converted to if + // necessary. + /// + /*--cef()--*/ + virtual CefString GetStringValue() =0; + + + // OBJECT METHODS - These methods are only available on objects. Arrays and + // functions are also objects. String- and integer-based keys can be used + // interchangably with the framework converting between them as necessary. + + /// + // Returns true if this is a user created object. + /// + /*--cef()--*/ + virtual bool IsUserCreated() =0; + + /// + // Returns true if the last method call resulted in an exception. This + // attribute exists only in the scope of the current CEF value object. + /// + /*--cef()--*/ + virtual bool HasException() =0; + + /// + // Returns the exception resulting from the last method call. This attribute + // exists only in the scope of the current CEF value object. + /// + /*--cef()--*/ + virtual CefRefPtr GetException() =0; + + /// + // Clears the last exception and returns true on success. + /// + /*--cef()--*/ + virtual bool ClearException() =0; + + /// + // Returns true if this object will re-throw future exceptions. This attribute + // exists only in the scope of the current CEF value object. + /// + /*--cef()--*/ + virtual bool WillRethrowExceptions() =0; + + /// + // Set whether this object will re-throw future exceptions. By default + // exceptions are not re-thrown. If a exception is re-thrown the current + // context should not be accessed again until after the exception has been + // caught and not re-thrown. Returns true on success. This attribute exists + // only in the scope of the current CEF value object. + /// + /*--cef()--*/ + virtual bool SetRethrowExceptions(bool rethrow) =0; + + /// + // Returns true if the object has a value with the specified identifier. + /// + /*--cef(capi_name=has_value_bykey,optional_param=key)--*/ + virtual bool HasValue(const CefString& key) =0; + + /// + // Returns true if the object has a value with the specified identifier. + /// + /*--cef(capi_name=has_value_byindex,index_param=index)--*/ + virtual bool HasValue(int index) =0; + + /// + // Deletes the value with the specified identifier and returns true on + // success. Returns false if this method is called incorrectly or an exception + // is thrown. For read-only and don't-delete values this method will return + // true even though deletion failed. + /// + /*--cef(capi_name=delete_value_bykey,optional_param=key)--*/ + virtual bool DeleteValue(const CefString& key) =0; + + /// + // Deletes the value with the specified identifier and returns true on + // success. Returns false if this method is called incorrectly, deletion fails + // or an exception is thrown. For read-only and don't-delete values this + // method will return true even though deletion failed. + /// + /*--cef(capi_name=delete_value_byindex,index_param=index)--*/ + virtual bool DeleteValue(int index) =0; + + /// + // Returns the value with the specified identifier on success. Returns NULL + // if this method is called incorrectly or an exception is thrown. + /// + /*--cef(capi_name=get_value_bykey,optional_param=key)--*/ + virtual CefRefPtr GetValue(const CefString& key) =0; + + /// + // Returns the value with the specified identifier on success. Returns NULL + // if this method is called incorrectly or an exception is thrown. + /// + /*--cef(capi_name=get_value_byindex,index_param=index)--*/ + virtual CefRefPtr GetValue(int index) =0; + + /// + // Associates a value with the specified identifier and returns true on + // success. Returns false if this method is called incorrectly or an exception + // is thrown. For read-only values this method will return true even though + // assignment failed. + /// + /*--cef(capi_name=set_value_bykey,optional_param=key)--*/ + virtual bool SetValue(const CefString& key, CefRefPtr value, + PropertyAttribute attribute) =0; + + /// + // Associates a value with the specified identifier and returns true on + // success. Returns false if this method is called incorrectly or an exception + // is thrown. For read-only values this method will return true even though + // assignment failed. + /// + /*--cef(capi_name=set_value_byindex,index_param=index)--*/ + virtual bool SetValue(int index, CefRefPtr value) =0; + + /// + // Registers an identifier and returns true on success. Access to the + // identifier will be forwarded to the CefV8Accessor instance passed to + // CefV8Value::CreateObject(). Returns false if this method is called + // incorrectly or an exception is thrown. For read-only values this method + // will return true even though assignment failed. + /// + /*--cef(capi_name=set_value_byaccessor,optional_param=key)--*/ + virtual bool SetValue(const CefString& key, AccessControl settings, + PropertyAttribute attribute) =0; + + /// + // Read the keys for the object's values into the specified vector. Integer- + // based keys will also be returned as strings. + /// + /*--cef()--*/ + virtual bool GetKeys(std::vector& keys) =0; + + /// + // Sets the user data for this object and returns true on success. Returns + // false if this method is called incorrectly. This method can only be called + // on user created objects. + /// + /*--cef(optional_param=user_data)--*/ + virtual bool SetUserData(CefRefPtr user_data) =0; + + /// + // Returns the user data, if any, assigned to this object. + /// + /*--cef()--*/ + virtual CefRefPtr GetUserData() =0; + + /// + // Returns the amount of externally allocated memory registered for the + // object. + /// + /*--cef()--*/ + virtual int GetExternallyAllocatedMemory() =0; + + /// + // Adjusts the amount of registered external memory for the object. Used to + // give V8 an indication of the amount of externally allocated memory that is + // kept alive by JavaScript objects. V8 uses this information to decide when + // to perform global garbage collection. Each CefV8Value tracks the amount of + // external memory associated with it and automatically decreases the global + // total by the appropriate amount on its destruction. |change_in_bytes| + // specifies the number of bytes to adjust by. This method returns the number + // of bytes associated with the object after the adjustment. This method can + // only be called on user created objects. + /// + /*--cef()--*/ + virtual int AdjustExternallyAllocatedMemory(int change_in_bytes) =0; + + + // ARRAY METHODS - These methods are only available on arrays. + + /// + // Returns the number of elements in the array. + /// + /*--cef()--*/ + virtual int GetArrayLength() =0; + + + // FUNCTION METHODS - These methods are only available on functions. + + /// + // Returns the function name. + /// + /*--cef()--*/ + virtual CefString GetFunctionName() =0; + + /// + // Returns the function handler or NULL if not a CEF-created function. + /// + /*--cef()--*/ + virtual CefRefPtr GetFunctionHandler() =0; + + /// + // Execute the function using the current V8 context. This method should only + // be called from within the scope of a CefV8Handler or CefV8Accessor + // callback, or in combination with calling Enter() and Exit() on a stored + // CefV8Context reference. |object| is the receiver ('this' object) of the + // function. If |object| is empty the current context's global object will be + // used. |arguments| is the list of arguments that will be passed to the + // function. Returns the function return value on success. Returns NULL if + // this method is called incorrectly or an exception is thrown. + /// + /*--cef(optional_param=object)--*/ + virtual CefRefPtr ExecuteFunction( + CefRefPtr object, + const CefV8ValueList& arguments) =0; + + /// + // Execute the function using the specified V8 context. |object| is the + // receiver ('this' object) of the function. If |object| is empty the + // specified context's global object will be used. |arguments| is the list of + // arguments that will be passed to the function. Returns the function return + // value on success. Returns NULL if this method is called incorrectly or an + // exception is thrown. + /// + /*--cef(optional_param=object)--*/ + virtual CefRefPtr ExecuteFunctionWithContext( + CefRefPtr context, + CefRefPtr object, + const CefV8ValueList& arguments) =0; +}; + +/// +// Class representing a V8 stack trace handle. V8 handles can only be accessed +// from the thread on which they are created. Valid threads for creating a V8 +// handle include the render process main thread (TID_RENDERER) and WebWorker +// threads. A task runner for posting tasks on the associated thread can be +// retrieved via the CefV8Context::GetTaskRunner() method. +/// +/*--cef(source=library)--*/ +class CefV8StackTrace : public virtual CefBase { + public: + /// + // Returns the stack trace for the currently active context. |frame_limit| is + // the maximum number of frames that will be captured. + /// + /*--cef()--*/ + static CefRefPtr GetCurrent(int frame_limit); + + /// + // Returns true if the underlying handle is valid and it can be accessed on + // the current thread. Do not call any other methods if this method returns + // false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns the number of stack frames. + /// + /*--cef()--*/ + virtual int GetFrameCount() =0; + + /// + // Returns the stack frame at the specified 0-based index. + /// + /*--cef()--*/ + virtual CefRefPtr GetFrame(int index) =0; +}; + +/// +// Class representing a V8 stack frame handle. V8 handles can only be accessed +// from the thread on which they are created. Valid threads for creating a V8 +// handle include the render process main thread (TID_RENDERER) and WebWorker +// threads. A task runner for posting tasks on the associated thread can be +// retrieved via the CefV8Context::GetTaskRunner() method. +/// +/*--cef(source=library)--*/ +class CefV8StackFrame : public virtual CefBase { + public: + /// + // Returns true if the underlying handle is valid and it can be accessed on + // the current thread. Do not call any other methods if this method returns + // false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns the name of the resource script that contains the function. + /// + /*--cef()--*/ + virtual CefString GetScriptName() =0; + + /// + // Returns the name of the resource script that contains the function or the + // sourceURL value if the script name is undefined and its source ends with + // a "//@ sourceURL=..." string. + /// + /*--cef()--*/ + virtual CefString GetScriptNameOrSourceURL() =0; + + /// + // Returns the name of the function. + /// + /*--cef()--*/ + virtual CefString GetFunctionName() =0; + + /// + // Returns the 1-based line number for the function call or 0 if unknown. + /// + /*--cef()--*/ + virtual int GetLineNumber() =0; + + /// + // Returns the 1-based column offset on the line for the function call or 0 if + // unknown. + /// + /*--cef()--*/ + virtual int GetColumn() =0; + + /// + // Returns true if the function was compiled using eval(). + /// + /*--cef()--*/ + virtual bool IsEval() =0; + + /// + // Returns true if the function was called as a constructor via "new". + /// + /*--cef()--*/ + virtual bool IsConstructor() =0; +}; + +#endif // CEF_INCLUDE_CEF_V8_H_ diff --git a/include/cef_values.h b/include/cef_values.h new file mode 100644 index 000000000..9a640ab77 --- /dev/null +++ b/include/cef_values.h @@ -0,0 +1,471 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_VALUES_H_ +#define CEF_INCLUDE_CEF_VALUES_H_ +#pragma once + +#include +#include "include/cef_base.h" + +class CefDictionaryValue; +class CefListValue; + +typedef cef_value_type_t CefValueType; + +/// +// Class representing a binary value. Can be used on any process and thread. +/// +/*--cef(source=library)--*/ +class CefBinaryValue : public virtual CefBase { + public: + /// + // Creates a new object that is not owned by any other object. The specified + // |data| will be copied. + /// + /*--cef()--*/ + static CefRefPtr Create(const void* data, + size_t data_size); + + /// + // Returns true if this object is valid. Do not call any other methods if this + // method returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if this object is currently owned by another object. + /// + /*--cef()--*/ + virtual bool IsOwned() =0; + + /// + // Returns a copy of this object. The data in this object will also be copied. + /// + /*--cef()--*/ + virtual CefRefPtr Copy() =0; + + /// + // Returns the data size. + /// + /*--cef()--*/ + virtual size_t GetSize() =0; + + /// + // Read up to |buffer_size| number of bytes into |buffer|. Reading begins at + // the specified byte |data_offset|. Returns the number of bytes read. + /// + /*--cef()--*/ + virtual size_t GetData(void* buffer, + size_t buffer_size, + size_t data_offset) =0; +}; + + +/// +// Class representing a dictionary value. Can be used on any process and thread. +/// +/*--cef(source=library)--*/ +class CefDictionaryValue : public virtual CefBase { + public: + typedef std::vector KeyList; + + /// + // Creates a new object that is not owned by any other object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is valid. Do not call any other methods if this + // method returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if this object is currently owned by another object. + /// + /*--cef()--*/ + virtual bool IsOwned() =0; + + /// + // Returns true if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns a writable copy of this object. If |exclude_empty_children| is true + // any empty dictionaries or lists will be excluded from the copy. + /// + /*--cef()--*/ + virtual CefRefPtr Copy(bool exclude_empty_children) =0; + + /// + // Returns the number of values. + /// + /*--cef()--*/ + virtual size_t GetSize() =0; + + /// + // Removes all values. Returns true on success. + /// + /*--cef()--*/ + virtual bool Clear() =0; + + /// + // Returns true if the current dictionary has a value for the given key. + /// + /*--cef()--*/ + virtual bool HasKey(const CefString& key) =0; + + /// + // Reads all keys for this dictionary into the specified vector. + /// + /*--cef()--*/ + virtual bool GetKeys(KeyList& keys) =0; + + /// + // Removes the value at the specified key. Returns true is the value was + // removed successfully. + /// + /*--cef()--*/ + virtual bool Remove(const CefString& key) =0; + + /// + // Returns the value type for the specified key. + /// + /*--cef(default_retval=VTYPE_INVALID)--*/ + virtual CefValueType GetType(const CefString& key) =0; + + /// + // Returns the value at the specified key as type bool. + /// + /*--cef()--*/ + virtual bool GetBool(const CefString& key) =0; + + /// + // Returns the value at the specified key as type int. + /// + /*--cef()--*/ + virtual int GetInt(const CefString& key) =0; + + /// + // Returns the value at the specified key as type double. + /// + /*--cef()--*/ + virtual double GetDouble(const CefString& key) =0; + + /// + // Returns the value at the specified key as type string. + /// + /*--cef()--*/ + virtual CefString GetString(const CefString& key) =0; + + /// + // Returns the value at the specified key as type binary. + /// + /*--cef()--*/ + virtual CefRefPtr GetBinary(const CefString& key) =0; + + /// + // Returns the value at the specified key as type dictionary. + /// + /*--cef()--*/ + virtual CefRefPtr GetDictionary(const CefString& key) =0; + + /// + // Returns the value at the specified key as type list. + /// + /*--cef()--*/ + virtual CefRefPtr GetList(const CefString& key) =0; + + /// + // Sets the value at the specified key as type null. Returns true if the + // value was set successfully. + /// + /*--cef()--*/ + virtual bool SetNull(const CefString& key) =0; + + /// + // Sets the value at the specified key as type bool. Returns true if the + // value was set successfully. + /// + /*--cef()--*/ + virtual bool SetBool(const CefString& key, bool value) =0; + + /// + // Sets the value at the specified key as type int. Returns true if the + // value was set successfully. + /// + /*--cef()--*/ + virtual bool SetInt(const CefString& key, int value) =0; + + /// + // Sets the value at the specified key as type double. Returns true if the + // value was set successfully. + /// + /*--cef()--*/ + virtual bool SetDouble(const CefString& key, double value) =0; + + /// + // Sets the value at the specified key as type string. Returns true if the + // value was set successfully. + /// + /*--cef(optional_param=value)--*/ + virtual bool SetString(const CefString& key, const CefString& value) =0; + + /// + // Sets the value at the specified key as type binary. Returns true if the + // value was set successfully. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + /*--cef()--*/ + virtual bool SetBinary(const CefString& key, + CefRefPtr value) =0; + + /// + // Sets the value at the specified key as type dict. Returns true if the + // value was set successfully. After calling this method the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + /*--cef()--*/ + virtual bool SetDictionary(const CefString& key, + CefRefPtr value) =0; + + /// + // Sets the value at the specified key as type list. Returns true if the + // value was set successfully. After calling this method the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + /*--cef()--*/ + virtual bool SetList(const CefString& key, + CefRefPtr value) =0; +}; + + +/// +// Class representing a list value. Can be used on any process and thread. +/// +/*--cef(source=library)--*/ +class CefListValue : public virtual CefBase { + public: + /// + // Creates a new object that is not owned by any other object. + /// + /*--cef()--*/ + static CefRefPtr Create(); + + /// + // Returns true if this object is valid. Do not call any other methods if this + // method returns false. + /// + /*--cef()--*/ + virtual bool IsValid() =0; + + /// + // Returns true if this object is currently owned by another object. + /// + /*--cef()--*/ + virtual bool IsOwned() =0; + + /// + // Returns true if the values of this object are read-only. Some APIs may + // expose read-only objects. + /// + /*--cef()--*/ + virtual bool IsReadOnly() =0; + + /// + // Returns a writable copy of this object. + /// + /*--cef()--*/ + virtual CefRefPtr Copy() =0; + + /// + // Sets the number of values. If the number of values is expanded all + // new value slots will default to type null. Returns true on success. + /// + /*--cef()--*/ + virtual bool SetSize(size_t size) =0; + + /// + // Returns the number of values. + /// + /*--cef()--*/ + virtual size_t GetSize() =0; + + /// + // Removes all values. Returns true on success. + /// + /*--cef()--*/ + virtual bool Clear() =0; + + /// + // Removes the value at the specified index. + /// + /*--cef(index_param=index)--*/ + virtual bool Remove(int index) =0; + + /// + // Returns the value type at the specified index. + /// + /*--cef(default_retval=VTYPE_INVALID,index_param=index)--*/ + virtual CefValueType GetType(int index) =0; + + /// + // Returns the value at the specified index as type bool. + /// + /*--cef(index_param=index)--*/ + virtual bool GetBool(int index) =0; + + /// + // Returns the value at the specified index as type int. + /// + /*--cef(index_param=index)--*/ + virtual int GetInt(int index) =0; + + /// + // Returns the value at the specified index as type double. + /// + /*--cef(index_param=index)--*/ + virtual double GetDouble(int index) =0; + + /// + // Returns the value at the specified index as type string. + /// + /*--cef(index_param=index)--*/ + virtual CefString GetString(int index) =0; + + /// + // Returns the value at the specified index as type binary. + /// + /*--cef(index_param=index)--*/ + virtual CefRefPtr GetBinary(int index) =0; + + /// + // Returns the value at the specified index as type dictionary. + /// + /*--cef(index_param=index)--*/ + virtual CefRefPtr GetDictionary(int index) =0; + + /// + // Returns the value at the specified index as type list. + /// + /*--cef(index_param=index)--*/ + virtual CefRefPtr GetList(int index) =0; + + /// + // Sets the value at the specified index as type null. Returns true if the + // value was set successfully. + /// + /*--cef(index_param=index)--*/ + virtual bool SetNull(int index) =0; + + /// + // Sets the value at the specified index as type bool. Returns true if the + // value was set successfully. + /// + /*--cef(index_param=index)--*/ + virtual bool SetBool(int index, bool value) =0; + + /// + // Sets the value at the specified index as type int. Returns true if the + // value was set successfully. + /// + /*--cef(index_param=index)--*/ + virtual bool SetInt(int index, int value) =0; + + /// + // Sets the value at the specified index as type double. Returns true if the + // value was set successfully. + /// + /*--cef(index_param=index)--*/ + virtual bool SetDouble(int index, double value) =0; + + /// + // Sets the value at the specified index as type string. Returns true if the + // value was set successfully. + /// + /*--cef(optional_param=value,index_param=index)--*/ + virtual bool SetString(int index, const CefString& value) =0; + + /// + // Sets the value at the specified index as type binary. Returns true if the + // value was set successfully. After calling this method the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + /*--cef(index_param=index)--*/ + virtual bool SetBinary(int index, CefRefPtr value) =0; + + /// + // Sets the value at the specified index as type dict. Returns true if the + // value was set successfully. After calling this method the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + /*--cef(index_param=index)--*/ + virtual bool SetDictionary(int index, CefRefPtr value) =0; + + /// + // Sets the value at the specified index as type list. Returns true if the + // value was set successfully. After calling this method the |value| object + // will no longer be valid. If |value| is currently owned by another object + // then the value will be copied and the |value| reference will not change. + // Otherwise, ownership will be transferred to this object and the |value| + // reference will be invalidated. + /// + /*--cef(index_param=index)--*/ + virtual bool SetList(int index, CefRefPtr value) =0; +}; + +#endif // CEF_INCLUDE_CEF_VALUES_H_ diff --git a/include/cef_web_plugin.h b/include/cef_web_plugin.h new file mode 100644 index 000000000..0ff2b8ea1 --- /dev/null +++ b/include/cef_web_plugin.h @@ -0,0 +1,178 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_WEB_PLUGIN_H_ +#define CEF_INCLUDE_CEF_WEB_PLUGIN_H_ + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Information about a specific web plugin. +/// +/*--cef(source=library)--*/ +class CefWebPluginInfo : public virtual CefBase { + public: + /// + // Returns the plugin name (i.e. Flash). + /// + /*--cef()--*/ + virtual CefString GetName() =0; + + /// + // Returns the plugin file path (DLL/bundle/library). + /// + /*--cef()--*/ + virtual CefString GetPath() =0; + + /// + // Returns the version of the plugin (may be OS-specific). + /// + /*--cef()--*/ + virtual CefString GetVersion() =0; + + /// + // Returns a description of the plugin from the version information. + /// + /*--cef()--*/ + virtual CefString GetDescription() =0; +}; + +/// +// Interface to implement for visiting web plugin information. The methods of +// this class will be called on the browser process UI thread. +/// +/*--cef(source=client)--*/ +class CefWebPluginInfoVisitor : public virtual CefBase { + public: + /// + // Method that will be called once for each plugin. |count| is the 0-based + // index for the current plugin. |total| is the total number of plugins. + // Return false to stop visiting plugins. This method may never be called if + // no plugins are found. + /// + /*--cef()--*/ + virtual bool Visit(CefRefPtr info, int count, int total) =0; +}; + +/// +// Visit web plugin information. Can be called on any thread in the browser +// process. +/// +/*--cef()--*/ +void CefVisitWebPluginInfo(CefRefPtr visitor); + +/// +// Cause the plugin list to refresh the next time it is accessed regardless +// of whether it has already been loaded. Can be called on any thread in the +// browser process. +/// +/*--cef()--*/ +void CefRefreshWebPlugins(); + +/// +// Add a plugin path (directory + file). This change may not take affect until +// after CefRefreshWebPlugins() is called. Can be called on any thread in the +// browser process. +/// +/*--cef()--*/ +void CefAddWebPluginPath(const CefString& path); + +/// +// Add a plugin directory. This change may not take affect until after +// CefRefreshWebPlugins() is called. Can be called on any thread in the browser +// process. +/// +/*--cef()--*/ +void CefAddWebPluginDirectory(const CefString& dir); + +/// +// Remove a plugin path (directory + file). This change may not take affect +// until after CefRefreshWebPlugins() is called. Can be called on any thread in +// the browser process. +/// +/*--cef()--*/ +void CefRemoveWebPluginPath(const CefString& path); + +/// +// Unregister an internal plugin. This may be undone the next time +// CefRefreshWebPlugins() is called. Can be called on any thread in the browser +// process. +/// +/*--cef()--*/ +void CefUnregisterInternalWebPlugin(const CefString& path); + +/// +// Force a plugin to shutdown. Can be called on any thread in the browser +// process but will be executed on the IO thread. +/// +/*--cef()--*/ +void CefForceWebPluginShutdown(const CefString& path); + +/// +// Register a plugin crash. Can be called on any thread in the browser process +// but will be executed on the IO thread. +/// +/*--cef()--*/ +void CefRegisterWebPluginCrash(const CefString& path); + +/// +// Interface to implement for receiving unstable plugin information. The methods +// of this class will be called on the browser process IO thread. +/// +/*--cef(source=client)--*/ +class CefWebPluginUnstableCallback : public virtual CefBase { + public: + /// + // Method that will be called for the requested plugin. |unstable| will be + // true if the plugin has reached the crash count threshold of 3 times in 120 + // seconds. + /// + /*--cef()--*/ + virtual void IsUnstable(const CefString& path, + bool unstable) =0; +}; + +/// +// Query if a plugin is unstable. Can be called on any thread in the browser +// process. +/// +/*--cef()--*/ +void CefIsWebPluginUnstable(const CefString& path, + CefRefPtr callback); + + +#endif // CEF_INCLUDE_CEF_WEB_PLUGIN_H_ diff --git a/include/cef_xml_reader.h b/include/cef_xml_reader.h new file mode 100644 index 000000000..86be8bac7 --- /dev/null +++ b/include/cef_xml_reader.h @@ -0,0 +1,268 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_XML_READER_H_ +#define CEF_INCLUDE_CEF_XML_READER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_stream.h" + +/// +// Class that supports the reading of XML data via the libxml streaming API. +// The methods of this class should only be called on the thread that creates +// the object. +/// +/*--cef(source=library)--*/ +class CefXmlReader : public virtual CefBase { + public: + typedef cef_xml_encoding_type_t EncodingType; + typedef cef_xml_node_type_t NodeType; + + /// + // Create a new CefXmlReader object. The returned object's methods can only + // be called from the thread that created the object. + /// + /*--cef()--*/ + static CefRefPtr Create(CefRefPtr stream, + EncodingType encodingType, + const CefString& URI); + + /// + // Moves the cursor to the next node in the document. This method must be + // called at least once to set the current cursor position. Returns true if + // the cursor position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToNextNode() =0; + + /// + // Close the document. This should be called directly to ensure that cleanup + // occurs on the correct thread. + /// + /*--cef()--*/ + virtual bool Close() =0; + + /// + // Returns true if an error has been reported by the XML parser. + /// + /*--cef()--*/ + virtual bool HasError() =0; + + /// + // Returns the error string. + /// + /*--cef()--*/ + virtual CefString GetError() =0; + + + // The below methods retrieve data for the node at the current cursor + // position. + + /// + // Returns the node type. + /// + /*--cef(default_retval=XML_NODE_UNSUPPORTED)--*/ + virtual NodeType GetType() =0; + + /// + // Returns the node depth. Depth starts at 0 for the root node. + /// + /*--cef()--*/ + virtual int GetDepth() =0; + + /// + // Returns the local name. See + // http://www.w3.org/TR/REC-xml-names/#NT-LocalPart for additional details. + /// + /*--cef()--*/ + virtual CefString GetLocalName() =0; + + /// + // Returns the namespace prefix. See http://www.w3.org/TR/REC-xml-names/ for + // additional details. + /// + /*--cef()--*/ + virtual CefString GetPrefix() =0; + + /// + // Returns the qualified name, equal to (Prefix:)LocalName. See + // http://www.w3.org/TR/REC-xml-names/#ns-qualnames for additional details. + /// + /*--cef()--*/ + virtual CefString GetQualifiedName() =0; + + /// + // Returns the URI defining the namespace associated with the node. See + // http://www.w3.org/TR/REC-xml-names/ for additional details. + /// + /*--cef()--*/ + virtual CefString GetNamespaceURI() =0; + + /// + // Returns the base URI of the node. See http://www.w3.org/TR/xmlbase/ for + // additional details. + /// + /*--cef()--*/ + virtual CefString GetBaseURI() =0; + + /// + // Returns the xml:lang scope within which the node resides. See + // http://www.w3.org/TR/REC-xml/#sec-lang-tag for additional details. + /// + /*--cef()--*/ + virtual CefString GetXmlLang() =0; + + /// + // Returns true if the node represents an empty element. is considered + // empty but is not. + /// + /*--cef()--*/ + virtual bool IsEmptyElement() =0; + + /// + // Returns true if the node has a text value. + /// + /*--cef()--*/ + virtual bool HasValue() =0; + + /// + // Returns the text value. + /// + /*--cef()--*/ + virtual CefString GetValue() =0; + + /// + // Returns true if the node has attributes. + /// + /*--cef()--*/ + virtual bool HasAttributes() =0; + + /// + // Returns the number of attributes. + /// + /*--cef()--*/ + virtual size_t GetAttributeCount() =0; + + /// + // Returns the value of the attribute at the specified 0-based index. + /// + /*--cef(capi_name=get_attribute_byindex,index_param=index)--*/ + virtual CefString GetAttribute(int index) =0; + + /// + // Returns the value of the attribute with the specified qualified name. + /// + /*--cef(capi_name=get_attribute_byqname)--*/ + virtual CefString GetAttribute(const CefString& qualifiedName) =0; + + /// + // Returns the value of the attribute with the specified local name and + // namespace URI. + /// + /*--cef(capi_name=get_attribute_bylname)--*/ + virtual CefString GetAttribute(const CefString& localName, + const CefString& namespaceURI) =0; + + /// + // Returns an XML representation of the current node's children. + /// + /*--cef()--*/ + virtual CefString GetInnerXml() =0; + + /// + // Returns an XML representation of the current node including its children. + /// + /*--cef()--*/ + virtual CefString GetOuterXml() =0; + + /// + // Returns the line number for the current node. + /// + /*--cef()--*/ + virtual int GetLineNumber() =0; + + + // Attribute nodes are not traversed by default. The below methods can be + // used to move the cursor to an attribute node. MoveToCarryingElement() can + // be called afterwards to return the cursor to the carrying element. The + // depth of an attribute node will be 1 + the depth of the carrying element. + + /// + // Moves the cursor to the attribute at the specified 0-based index. Returns + // true if the cursor position was set successfully. + /// + /*--cef(capi_name=move_to_attribute_byindex,index_param=index)--*/ + virtual bool MoveToAttribute(int index) =0; + + /// + // Moves the cursor to the attribute with the specified qualified name. + // Returns true if the cursor position was set successfully. + /// + /*--cef(capi_name=move_to_attribute_byqname)--*/ + virtual bool MoveToAttribute(const CefString& qualifiedName) =0; + + /// + // Moves the cursor to the attribute with the specified local name and + // namespace URI. Returns true if the cursor position was set successfully. + /// + /*--cef(capi_name=move_to_attribute_bylname)--*/ + virtual bool MoveToAttribute(const CefString& localName, + const CefString& namespaceURI) =0; + + /// + // Moves the cursor to the first attribute in the current element. Returns + // true if the cursor position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToFirstAttribute() =0; + + /// + // Moves the cursor to the next attribute in the current element. Returns + // true if the cursor position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToNextAttribute() =0; + + /// + // Moves the cursor back to the carrying element. Returns true if the cursor + // position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToCarryingElement() =0; +}; + +#endif // CEF_INCLUDE_CEF_XML_READER_H_ diff --git a/include/cef_zip_reader.h b/include/cef_zip_reader.h new file mode 100644 index 000000000..1fe02b916 --- /dev/null +++ b/include/cef_zip_reader.h @@ -0,0 +1,141 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file must follow a specific format in order to +// support the CEF translator tool. See the translator.README.txt file in the +// tools directory for more information. +// + +#ifndef CEF_INCLUDE_CEF_ZIP_READER_H_ +#define CEF_INCLUDE_CEF_ZIP_READER_H_ + +#include "include/cef_base.h" +#include "include/cef_stream.h" + +/// +// Class that supports the reading of zip archives via the zlib unzip API. +// The methods of this class should only be called on the thread that creates +// the object. +/// +/*--cef(source=library)--*/ +class CefZipReader : public virtual CefBase { + public: + /// + // Create a new CefZipReader object. The returned object's methods can only + // be called from the thread that created the object. + /// + /*--cef()--*/ + static CefRefPtr Create(CefRefPtr stream); + + /// + // Moves the cursor to the first file in the archive. Returns true if the + // cursor position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToFirstFile() =0; + + /// + // Moves the cursor to the next file in the archive. Returns true if the + // cursor position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToNextFile() =0; + + /// + // Moves the cursor to the specified file in the archive. If |caseSensitive| + // is true then the search will be case sensitive. Returns true if the cursor + // position was set successfully. + /// + /*--cef()--*/ + virtual bool MoveToFile(const CefString& fileName, bool caseSensitive) =0; + + /// + // Closes the archive. This should be called directly to ensure that cleanup + // occurs on the correct thread. + /// + /*--cef()--*/ + virtual bool Close() =0; + + + // The below methods act on the file at the current cursor position. + + /// + // Returns the name of the file. + /// + /*--cef()--*/ + virtual CefString GetFileName() =0; + + /// + // Returns the uncompressed size of the file. + /// + /*--cef()--*/ + virtual int64 GetFileSize() =0; + + /// + // Returns the last modified timestamp for the file. + /// + /*--cef()--*/ + virtual time_t GetFileLastModified() =0; + + /// + // Opens the file for reading of uncompressed data. A read password may + // optionally be specified. + /// + /*--cef(optional_param=password)--*/ + virtual bool OpenFile(const CefString& password) =0; + + /// + // Closes the file. + /// + /*--cef()--*/ + virtual bool CloseFile() =0; + + /// + // Read uncompressed file contents into the specified buffer. Returns < 0 if + // an error occurred, 0 if at the end of file, or the number of bytes read. + /// + /*--cef()--*/ + virtual int ReadFile(void* buffer, size_t bufferSize) =0; + + /// + // Returns the current offset in the uncompressed file contents. + /// + /*--cef()--*/ + virtual int64 Tell() =0; + + /// + // Returns true if at end of the file contents. + /// + /*--cef()--*/ + virtual bool Eof() =0; +}; + +#endif // CEF_INCLUDE_CEF_ZIP_READER_H_ diff --git a/include/internal/cef_export.h b/include/internal/cef_export.h new file mode 100644 index 000000000..2813253b6 --- /dev/null +++ b/include/internal/cef_export.h @@ -0,0 +1,55 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_EXPORT_H_ +#define CEF_INCLUDE_INTERNAL_CEF_EXPORT_H_ +#pragma once + +#include "include/base/cef_build.h" + +#if defined(COMPILER_MSVC) + +#ifdef BUILDING_CEF_SHARED +#define CEF_EXPORT __declspec(dllexport) +#elif USING_CEF_SHARED +#define CEF_EXPORT __declspec(dllimport) +#else +#define CEF_EXPORT +#endif +#define CEF_CALLBACK __stdcall + +#elif defined(COMPILER_GCC) + +#define CEF_EXPORT __attribute__ ((visibility("default"))) +#define CEF_CALLBACK + +#endif // COMPILER_GCC + +#endif // CEF_INCLUDE_INTERNAL_CEF_EXPORT_H_ diff --git a/include/internal/cef_linux.h b/include/internal/cef_linux.h new file mode 100644 index 000000000..6238397a3 --- /dev/null +++ b/include/internal/cef_linux.h @@ -0,0 +1,130 @@ +// Copyright (c) 2010 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_LINUX_H_ +#define CEF_INCLUDE_INTERNAL_CEF_LINUX_H_ +#pragma once + +#include "include/internal/cef_types_linux.h" +#include "include/internal/cef_types_wrappers.h" + +// Handle types. +#define CefCursorHandle cef_cursor_handle_t +#define CefEventHandle cef_event_handle_t +#define CefWindowHandle cef_window_handle_t +#define CefTextInputContext cef_text_input_context_t + +struct CefMainArgsTraits { + typedef cef_main_args_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->argc = src->argc; + target->argv = src->argv; + } +}; + +// Class representing CefExecuteProcess arguments. +class CefMainArgs : public CefStructBase { + public: + typedef CefStructBase parent; + + CefMainArgs() : parent() {} + explicit CefMainArgs(const cef_main_args_t& r) : parent(r) {} + explicit CefMainArgs(const CefMainArgs& r) : parent(r) {} + CefMainArgs(int argc_arg, char** argv_arg) : parent() { + argc = argc_arg; + argv = argv_arg; + } +}; + +struct CefWindowInfoTraits { + typedef cef_window_info_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->x = src->x; + target->y = src->y; + target->width = src->width; + target->height = src->height; + target->parent_window = src->parent_window; + target->windowless_rendering_enabled = src->windowless_rendering_enabled; + target->transparent_painting_enabled = src->transparent_painting_enabled; + target->window = src->window; + } +}; + +// Class representing window information. +class CefWindowInfo : public CefStructBase { + public: + typedef CefStructBase parent; + + CefWindowInfo() : parent() {} + explicit CefWindowInfo(const cef_window_info_t& r) : parent(r) {} + explicit CefWindowInfo(const CefWindowInfo& r) : parent(r) {} + + /// + // Create the browser as a child window. + /// + void SetAsChild(CefWindowHandle parent, + const CefRect& windowRect) { + parent_window = parent; + x = windowRect.x; + y = windowRect.y; + width = windowRect.width; + height = windowRect.height; + } + + /// + // Create the browser using windowless (off-screen) rendering. No window + // will be created for the browser and all rendering will occur via the + // CefRenderHandler interface. The |parent| value will be used to identify + // monitor info and to act as the parent window for dialogs, context menus, + // etc. If |parent| is not provided then the main screen monitor will be used + // and some functionality that requires a parent window may not function + // correctly. If |transparent| is true a transparent background color will be + // used (RGBA=0x00000000). If |transparent| is false the background will be + // white and opaque. In order to create windowless browsers the + // CefSettings.windowless_rendering_enabled value must be set to true. + /// + void SetAsWindowless(CefWindowHandle parent, bool transparent) { + windowless_rendering_enabled = true; + parent_window = parent; + transparent_painting_enabled = transparent; + } +}; + +#endif // CEF_INCLUDE_INTERNAL_CEF_LINUX_H_ diff --git a/include/internal/cef_logging_internal.h b/include/internal/cef_logging_internal.h new file mode 100644 index 000000000..c376d0526 --- /dev/null +++ b/include/internal/cef_logging_internal.h @@ -0,0 +1,66 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_LOGGING_INTERNAL_H_ +#define CEF_INCLUDE_INTERNAL_CEF_LOGGING_INTERNAL_H_ +#pragma once + +#include "include/internal/cef_export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// See include/base/cef_logging.h for macros and intended usage. + +/// +// Gets the current log level. +/// +CEF_EXPORT int cef_get_min_log_level(); + +/// +// Gets the current vlog level for the given file (usually taken from +// __FILE__). Note that |N| is the size *with* the null terminator. +/// +CEF_EXPORT int cef_get_vlog_level(const char* file_start, size_t N); + +/// +// Add a log message. See the LogSeverity defines for supported |severity| +// values. +/// +CEF_EXPORT void cef_log(const char* file, + int line, + int severity, + const char* message); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // CEF_INCLUDE_INTERNAL_CEF_LOGGING_INTERNAL_H_ diff --git a/include/internal/cef_mac.h b/include/internal/cef_mac.h new file mode 100644 index 000000000..8defbfb09 --- /dev/null +++ b/include/internal/cef_mac.h @@ -0,0 +1,137 @@ +// Copyright (c) 2010 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_MAC_H_ +#define CEF_INCLUDE_INTERNAL_CEF_MAC_H_ +#pragma once + +#include "include/internal/cef_types_mac.h" +#include "include/internal/cef_types_wrappers.h" + +// Handle types. +#define CefCursorHandle cef_cursor_handle_t +#define CefEventHandle cef_event_handle_t +#define CefWindowHandle cef_window_handle_t +#define CefTextInputContext cef_text_input_context_t + +struct CefMainArgsTraits { + typedef cef_main_args_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->argc = src->argc; + target->argv = src->argv; + } +}; + +// Class representing CefExecuteProcess arguments. +class CefMainArgs : public CefStructBase { + public: + typedef CefStructBase parent; + + CefMainArgs() : parent() {} + explicit CefMainArgs(const cef_main_args_t& r) : parent(r) {} + explicit CefMainArgs(const CefMainArgs& r) : parent(r) {} + CefMainArgs(int argc, char** argv) : parent() { + this->argc = argc; + this->argv = argv; + } +}; + +struct CefWindowInfoTraits { + typedef cef_window_info_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->window_name); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + cef_string_set(src->window_name.str, src->window_name.length, + &target->window_name, copy); + target->x = src->x; + target->y = src->y; + target->width = src->width; + target->height = src->height; + target->hidden = src->hidden; + target->parent_view = src->parent_view; + target->windowless_rendering_enabled = src->windowless_rendering_enabled; + target->transparent_painting_enabled = src->transparent_painting_enabled; + target->view = src->view; + } +}; + +// Class representing window information. +class CefWindowInfo : public CefStructBase { + public: + typedef CefStructBase parent; + + CefWindowInfo() : parent() {} + explicit CefWindowInfo(const cef_window_info_t& r) : parent(r) {} + explicit CefWindowInfo(const CefWindowInfo& r) : parent(r) {} + + /// + // Create the browser as a child view. + /// + void SetAsChild(CefWindowHandle parent, int x, int y, int width, + int height) { + parent_view = parent; + this->x = x; + this->y = y; + this->width = width; + this->height = height; + hidden = false; + } + + /// + // Create the browser using windowless (off-screen) rendering. No view + // will be created for the browser and all rendering will occur via the + // CefRenderHandler interface. The |parent| value will be used to identify + // monitor info and to act as the parent view for dialogs, context menus, + // etc. If |parent| is not provided then the main screen monitor will be used + // and some functionality that requires a parent view may not function + // correctly. If |transparent| is true a transparent background color will be + // used (RGBA=0x00000000). If |transparent| is false the background will be + // white and opaque. In order to create windowless browsers the + // CefSettings.windowless_rendering_enabled value must be set to true. + /// + void SetAsWindowless(CefWindowHandle parent, bool transparent) { + windowless_rendering_enabled = true; + parent_view = parent; + transparent_painting_enabled = transparent; + } +}; + +#endif // CEF_INCLUDE_INTERNAL_CEF_MAC_H_ diff --git a/include/internal/cef_ptr.h b/include/internal/cef_ptr.h new file mode 100644 index 000000000..e38543911 --- /dev/null +++ b/include/internal/cef_ptr.h @@ -0,0 +1,161 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_PTR_H_ +#define CEF_INCLUDE_INTERNAL_CEF_PTR_H_ +#pragma once + +#include "include/base/cef_ref_counted.h" + +/// +// Smart pointer implementation that is an alias of scoped_refptr from +// include/base/cef_ref_counted.h. +//

+// A smart pointer class for reference counted objects. Use this class instead +// of calling AddRef and Release manually on a reference counted object to +// avoid common memory leaks caused by forgetting to Release an object +// reference. Sample usage: +//

+//   class MyFoo : public CefBase {
+//    ...
+//   };
+//
+//   void some_function() {
+//     // The MyFoo object that |foo| represents starts with a single
+//     // reference.
+//     CefRefPtr<MyFoo> foo = new MyFoo();
+//     foo->Method(param);
+//     // |foo| is released when this function returns
+//   }
+//
+//   void some_other_function() {
+//     CefRefPtr<MyFoo> foo = new MyFoo();
+//     ...
+//     foo = NULL;  // explicitly releases |foo|
+//     ...
+//     if (foo)
+//       foo->Method(param);
+//   }
+// 
+// The above examples show how CefRefPtr<T> acts like a pointer to T. +// Given two CefRefPtr<T> classes, it is also possible to exchange +// references between the two objects, like so: +//
+//   {
+//     CefRefPtr<MyFoo> a = new MyFoo();
+//     CefRefPtr<MyFoo> b;
+//
+//     b.swap(a);
+//     // now, |b| references the MyFoo object, and |a| references NULL.
+//   }
+// 
+// To make both |a| and |b| in the above example reference the same MyFoo +// object, simply use the assignment operator: +//
+//   {
+//     CefRefPtr<MyFoo> a = new MyFoo();
+//     CefRefPtr<MyFoo> b;
+//
+//     b = a;
+//     // now, |a| and |b| each own a reference to the same MyFoo object.
+//     // the reference count of the underlying MyFoo object will be 2.
+//   }
+// 
+// Reference counted objects can also be passed as function parameters and +// used as function return values: +//
+//   void some_func_with_param(CefRefPtr<MyFoo> param) {
+//     // A reference is added to the MyFoo object that |param| represents
+//     // during the scope of some_func_with_param() and released when
+//     // some_func_with_param() goes out of scope.
+//   }
+//
+//   CefRefPtr<MyFoo> some_func_with_retval() {
+//     // The MyFoo object that |foox| represents starts with a single
+//     // reference.
+//     CefRefPtr<MyFoo> foox = new MyFoo();
+//
+//     // Creating the return value adds an additional reference.
+//     return foox;
+//
+//     // When some_func_with_retval() goes out of scope the original |foox|
+//     // reference is released.
+//   }
+//
+//   void and_another_function() {
+//     CefRefPtr<MyFoo> foo = new MyFoo();
+//
+//     // pass |foo| as a parameter.
+//     some_function(foo);
+//
+//     CefRefPtr<MyFoo> foo2 = some_func_with_retval();
+//     // Now, since we kept a reference to the some_func_with_retval() return
+//     // value, |foo2| is the only class pointing to the MyFoo object created
+//     in some_func_with_retval(), and it has a reference count of 1.
+//
+//     some_func_with_retval();
+//     // Now, since we didn't keep a reference to the some_func_with_retval()
+//     // return value, the MyFoo object created in some_func_with_retval()
+//     // will automatically be released.
+//   }
+// 
+// And in standard containers: +//
+//   {
+//      // Create a vector that holds MyFoo objects.
+//      std::vector<CefRefPtr<MyFoo> > MyFooVec;
+//
+//     // The MyFoo object that |foo| represents starts with a single
+//     // reference.
+//     CefRefPtr<MyFoo> foo = new MyFoo();
+//
+//     // When the MyFoo object is added to |MyFooVec| the reference count
+//     // is increased to 2.
+//     MyFooVec.push_back(foo);
+//   }
+// 
+//

+/// +template +class CefRefPtr : public scoped_refptr { + public: + typedef scoped_refptr parent; + + CefRefPtr() : parent() {} + + CefRefPtr(T* p) : parent(p) {} + + CefRefPtr(const scoped_refptr& r) : parent(r) {} + + template + CefRefPtr(const scoped_refptr& r) : parent(r) {} +}; + +#endif // CEF_INCLUDE_INTERNAL_CEF_PTR_H_ diff --git a/include/internal/cef_string.h b/include/internal/cef_string.h new file mode 100644 index 000000000..a7876fe56 --- /dev/null +++ b/include/internal/cef_string.h @@ -0,0 +1,113 @@ +// Copyright (c) 2010 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_STRING_H_ +#define CEF_INCLUDE_INTERNAL_CEF_STRING_H_ +#pragma once + +// The CEF interface is built with one string type as the default. Comment out +// all but one of the CEF_STRING_TYPE_* defines below to specify the default. +// If you change the default you MUST recompile all of CEF. + +// Build with the UTF8 string type as default. +// #define CEF_STRING_TYPE_UTF8 1 + +// Build with the UTF16 string type as default. +#define CEF_STRING_TYPE_UTF16 1 + +// Build with the wide string type as default. +// #define CEF_STRING_TYPE_WIDE 1 + + +#include "include/internal/cef_string_types.h" + +#ifdef __cplusplus +#include "include/internal/cef_string_wrappers.h" +#if defined(CEF_STRING_TYPE_UTF16) +typedef CefStringUTF16 CefString; +#elif defined(CEF_STRING_TYPE_UTF8) +typedef CefStringUTF8 CefString; +#elif defined(CEF_STRING_TYPE_WIDE) +typedef CefStringWide CefString; +#endif +#endif // __cplusplus + +#if defined(CEF_STRING_TYPE_UTF8) +typedef char cef_char_t; +typedef cef_string_utf8_t cef_string_t; +typedef cef_string_userfree_utf8_t cef_string_userfree_t; +#define cef_string_set cef_string_utf8_set +#define cef_string_copy cef_string_utf8_copy +#define cef_string_clear cef_string_utf8_clear +#define cef_string_userfree_alloc cef_string_userfree_utf8_alloc +#define cef_string_userfree_free cef_string_userfree_utf8_free +#define cef_string_from_ascii cef_string_utf8_copy +#define cef_string_to_utf8 cef_string_utf8_copy +#define cef_string_from_utf8 cef_string_utf8_copy +#define cef_string_to_utf16 cef_string_utf8_to_utf16 +#define cef_string_from_utf16 cef_string_utf16_to_utf8 +#define cef_string_to_wide cef_string_utf8_to_wide +#define cef_string_from_wide cef_string_wide_to_utf8 +#elif defined(CEF_STRING_TYPE_UTF16) +typedef char16 cef_char_t; +typedef cef_string_userfree_utf16_t cef_string_userfree_t; +typedef cef_string_utf16_t cef_string_t; +#define cef_string_set cef_string_utf16_set +#define cef_string_copy cef_string_utf16_copy +#define cef_string_clear cef_string_utf16_clear +#define cef_string_userfree_alloc cef_string_userfree_utf16_alloc +#define cef_string_userfree_free cef_string_userfree_utf16_free +#define cef_string_from_ascii cef_string_ascii_to_utf16 +#define cef_string_to_utf8 cef_string_utf16_to_utf8 +#define cef_string_from_utf8 cef_string_utf8_to_utf16 +#define cef_string_to_utf16 cef_string_utf16_copy +#define cef_string_from_utf16 cef_string_utf16_copy +#define cef_string_to_wide cef_string_utf16_to_wide +#define cef_string_from_wide cef_string_wide_to_utf16 +#elif defined(CEF_STRING_TYPE_WIDE) +typedef wchar_t cef_char_t; +typedef cef_string_wide_t cef_string_t; +typedef cef_string_userfree_wide_t cef_string_userfree_t; +#define cef_string_set cef_string_wide_set +#define cef_string_copy cef_string_wide_copy +#define cef_string_clear cef_string_wide_clear +#define cef_string_userfree_alloc cef_string_userfree_wide_alloc +#define cef_string_userfree_free cef_string_userfree_wide_free +#define cef_string_from_ascii cef_string_ascii_to_wide +#define cef_string_to_utf8 cef_string_wide_to_utf8 +#define cef_string_from_utf8 cef_string_utf8_to_wide +#define cef_string_to_utf16 cef_string_wide_to_utf16 +#define cef_string_from_utf16 cef_string_utf16_to_wide +#define cef_string_to_wide cef_string_wide_copy +#define cef_string_from_wide cef_string_wide_copy +#else +#error Please choose a string type. +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_STRING_H_ diff --git a/include/internal/cef_string_list.h b/include/internal/cef_string_list.h new file mode 100644 index 000000000..52a0abf2f --- /dev/null +++ b/include/internal/cef_string_list.h @@ -0,0 +1,88 @@ +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_STRING_LIST_H_ +#define CEF_INCLUDE_INTERNAL_CEF_STRING_LIST_H_ +#pragma once + +#include "include/internal/cef_export.h" +#include "include/internal/cef_string.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// CEF string maps are a set of key/value string pairs. +/// +typedef void* cef_string_list_t; + +/// +// Allocate a new string map. +/// +CEF_EXPORT cef_string_list_t cef_string_list_alloc(); + +/// +// Return the number of elements in the string list. +/// +CEF_EXPORT int cef_string_list_size(cef_string_list_t list); + +/// +// Retrieve the value at the specified zero-based string list index. Returns +// true (1) if the value was successfully retrieved. +/// +CEF_EXPORT int cef_string_list_value(cef_string_list_t list, + int index, cef_string_t* value); + +/// +// Append a new value at the end of the string list. +/// +CEF_EXPORT void cef_string_list_append(cef_string_list_t list, + const cef_string_t* value); + +/// +// Clear the string list. +/// +CEF_EXPORT void cef_string_list_clear(cef_string_list_t list); + +/// +// Free the string list. +/// +CEF_EXPORT void cef_string_list_free(cef_string_list_t list); + +/// +// Creates a copy of an existing string list. +/// +CEF_EXPORT cef_string_list_t cef_string_list_copy(cef_string_list_t list); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_STRING_LIST_H_ diff --git a/include/internal/cef_string_map.h b/include/internal/cef_string_map.h new file mode 100644 index 000000000..93eea2a55 --- /dev/null +++ b/include/internal/cef_string_map.h @@ -0,0 +1,97 @@ +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_STRING_MAP_H_ +#define CEF_INCLUDE_INTERNAL_CEF_STRING_MAP_H_ +#pragma once + +#include "include/internal/cef_export.h" +#include "include/internal/cef_string.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// CEF string maps are a set of key/value string pairs. +/// +typedef void* cef_string_map_t; + +/// +// Allocate a new string map. +/// +CEF_EXPORT cef_string_map_t cef_string_map_alloc(); + +/// +// Return the number of elements in the string map. +/// +CEF_EXPORT int cef_string_map_size(cef_string_map_t map); + +/// +// Return the value assigned to the specified key. +/// +CEF_EXPORT int cef_string_map_find(cef_string_map_t map, + const cef_string_t* key, + cef_string_t* value); + +/// +// Return the key at the specified zero-based string map index. +/// +CEF_EXPORT int cef_string_map_key(cef_string_map_t map, int index, + cef_string_t* key); + +/// +// Return the value at the specified zero-based string map index. +/// +CEF_EXPORT int cef_string_map_value(cef_string_map_t map, int index, + cef_string_t* value); + +/// +// Append a new key/value pair at the end of the string map. +/// +CEF_EXPORT int cef_string_map_append(cef_string_map_t map, + const cef_string_t* key, + const cef_string_t* value); + +/// +// Clear the string map. +/// +CEF_EXPORT void cef_string_map_clear(cef_string_map_t map); + +/// +// Free the string map. +/// +CEF_EXPORT void cef_string_map_free(cef_string_map_t map); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_STRING_MAP_H_ diff --git a/include/internal/cef_string_multimap.h b/include/internal/cef_string_multimap.h new file mode 100644 index 000000000..cd3904244 --- /dev/null +++ b/include/internal/cef_string_multimap.h @@ -0,0 +1,105 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_STRING_MULTIMAP_H_ +#define CEF_INCLUDE_INTERNAL_CEF_STRING_MULTIMAP_H_ +#pragma once + +#include "include/internal/cef_export.h" +#include "include/internal/cef_string.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// CEF string multimaps are a set of key/value string pairs. +// More than one value can be assigned to a single key. +/// +typedef void* cef_string_multimap_t; + +/// +// Allocate a new string multimap. +/// +CEF_EXPORT cef_string_multimap_t cef_string_multimap_alloc(); + +/// +// Return the number of elements in the string multimap. +/// +CEF_EXPORT int cef_string_multimap_size(cef_string_multimap_t map); + +/// +// Return the number of values with the specified key. +/// +CEF_EXPORT int cef_string_multimap_find_count(cef_string_multimap_t map, + const cef_string_t* key); + +/// +// Return the value_index-th value with the specified key. +/// +CEF_EXPORT int cef_string_multimap_enumerate(cef_string_multimap_t map, + const cef_string_t* key, + int value_index, + cef_string_t* value); + +/// +// Return the key at the specified zero-based string multimap index. +/// +CEF_EXPORT int cef_string_multimap_key(cef_string_multimap_t map, int index, + cef_string_t* key); + +/// +// Return the value at the specified zero-based string multimap index. +/// +CEF_EXPORT int cef_string_multimap_value(cef_string_multimap_t map, int index, + cef_string_t* value); + +/// +// Append a new key/value pair at the end of the string multimap. +/// +CEF_EXPORT int cef_string_multimap_append(cef_string_multimap_t map, + const cef_string_t* key, + const cef_string_t* value); + +/// +// Clear the string multimap. +/// +CEF_EXPORT void cef_string_multimap_clear(cef_string_multimap_t map); + +/// +// Free the string multimap. +/// +CEF_EXPORT void cef_string_multimap_free(cef_string_multimap_t map); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_STRING_MULTIMAP_H_ diff --git a/include/internal/cef_string_types.h b/include/internal/cef_string_types.h new file mode 100644 index 000000000..493dc7e65 --- /dev/null +++ b/include/internal/cef_string_types.h @@ -0,0 +1,205 @@ +// Copyright (c) 2010 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_STRING_TYPES_H_ +#define CEF_INCLUDE_INTERNAL_CEF_STRING_TYPES_H_ +#pragma once + +// CEF provides functions for converting between UTF-8, -16 and -32 strings. +// CEF string types are safe for reading from multiple threads but not for +// modification. It is the user's responsibility to provide synchronization if +// modifying CEF strings from multiple threads. + +#include + +#include "include/base/cef_build.h" +#include "include/internal/cef_export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// CEF character type definitions. wchar_t is 2 bytes on Windows and 4 bytes on +// most other platforms. + +#if defined(OS_WIN) +typedef wchar_t char16; +#else // !OS_WIN +typedef unsigned short char16; // NOLINT (runtime/int) +#ifndef WCHAR_T_IS_UTF32 +#define WCHAR_T_IS_UTF32 +#endif // WCHAR_T_IS_UTF32 +#endif // !OS_WIN + + +// CEF string type definitions. Whomever allocates |str| is responsible for +// providing an appropriate |dtor| implementation that will free the string in +// the same memory space. When reusing an existing string structure make sure +// to call |dtor| for the old value before assigning new |str| and |dtor| +// values. Static strings will have a NULL |dtor| value. Using the below +// functions if you want this managed for you. + +typedef struct _cef_string_wide_t { + wchar_t* str; + size_t length; + void (*dtor)(wchar_t* str); +} cef_string_wide_t; + +typedef struct _cef_string_utf8_t { + char* str; + size_t length; + void (*dtor)(char* str); +} cef_string_utf8_t; + +typedef struct _cef_string_utf16_t { + char16* str; + size_t length; + void (*dtor)(char16* str); +} cef_string_utf16_t; + + +/// +// These functions set string values. If |copy| is true (1) the value will be +// copied instead of referenced. It is up to the user to properly manage +// the lifespan of references. +/// + +CEF_EXPORT int cef_string_wide_set(const wchar_t* src, size_t src_len, + cef_string_wide_t* output, int copy); +CEF_EXPORT int cef_string_utf8_set(const char* src, size_t src_len, + cef_string_utf8_t* output, int copy); +CEF_EXPORT int cef_string_utf16_set(const char16* src, size_t src_len, + cef_string_utf16_t* output, int copy); + + +/// +// Convenience macros for copying values. +/// + +#define cef_string_wide_copy(src, src_len, output) \ + cef_string_wide_set(src, src_len, output, true) +#define cef_string_utf8_copy(src, src_len, output) \ + cef_string_utf8_set(src, src_len, output, true) +#define cef_string_utf16_copy(src, src_len, output) \ + cef_string_utf16_set(src, src_len, output, true) + + +/// +// These functions clear string values. The structure itself is not freed. +/// + +CEF_EXPORT void cef_string_wide_clear(cef_string_wide_t* str); +CEF_EXPORT void cef_string_utf8_clear(cef_string_utf8_t* str); +CEF_EXPORT void cef_string_utf16_clear(cef_string_utf16_t* str); + + +/// +// These functions compare two string values with the same results as strcmp(). +/// + +CEF_EXPORT int cef_string_wide_cmp(const cef_string_wide_t* str1, + const cef_string_wide_t* str2); +CEF_EXPORT int cef_string_utf8_cmp(const cef_string_utf8_t* str1, + const cef_string_utf8_t* str2); +CEF_EXPORT int cef_string_utf16_cmp(const cef_string_utf16_t* str1, + const cef_string_utf16_t* str2); + + +/// +// These functions convert between UTF-8, -16, and -32 strings. They are +// potentially slow so unnecessary conversions should be avoided. The best +// possible result will always be written to |output| with the boolean return +// value indicating whether the conversion is 100% valid. +/// + +CEF_EXPORT int cef_string_wide_to_utf8(const wchar_t* src, size_t src_len, + cef_string_utf8_t* output); +CEF_EXPORT int cef_string_utf8_to_wide(const char* src, size_t src_len, + cef_string_wide_t* output); + +CEF_EXPORT int cef_string_wide_to_utf16(const wchar_t* src, size_t src_len, + cef_string_utf16_t* output); +CEF_EXPORT int cef_string_utf16_to_wide(const char16* src, size_t src_len, + cef_string_wide_t* output); + +CEF_EXPORT int cef_string_utf8_to_utf16(const char* src, size_t src_len, + cef_string_utf16_t* output); +CEF_EXPORT int cef_string_utf16_to_utf8(const char16* src, size_t src_len, + cef_string_utf8_t* output); + + +/// +// These functions convert an ASCII string, typically a hardcoded constant, to a +// Wide/UTF16 string. Use instead of the UTF8 conversion routines if you know +// the string is ASCII. +/// + +CEF_EXPORT int cef_string_ascii_to_wide(const char* src, size_t src_len, + cef_string_wide_t* output); +CEF_EXPORT int cef_string_ascii_to_utf16(const char* src, size_t src_len, + cef_string_utf16_t* output); + + + +/// +// It is sometimes necessary for the system to allocate string structures with +// the expectation that the user will free them. The userfree types act as a +// hint that the user is responsible for freeing the structure. +/// + +typedef cef_string_wide_t* cef_string_userfree_wide_t; +typedef cef_string_utf8_t* cef_string_userfree_utf8_t; +typedef cef_string_utf16_t* cef_string_userfree_utf16_t; + + +/// +// These functions allocate a new string structure. They must be freed by +// calling the associated free function. +/// + +CEF_EXPORT cef_string_userfree_wide_t cef_string_userfree_wide_alloc(); +CEF_EXPORT cef_string_userfree_utf8_t cef_string_userfree_utf8_alloc(); +CEF_EXPORT cef_string_userfree_utf16_t cef_string_userfree_utf16_alloc(); + + +/// +// These functions free the string structure allocated by the associated +// alloc function. Any string contents will first be cleared. +/// + +CEF_EXPORT void cef_string_userfree_wide_free(cef_string_userfree_wide_t str); +CEF_EXPORT void cef_string_userfree_utf8_free(cef_string_userfree_utf8_t str); +CEF_EXPORT void cef_string_userfree_utf16_free(cef_string_userfree_utf16_t str); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_STRING_TYPES_H_ diff --git a/include/internal/cef_string_wrappers.h b/include/internal/cef_string_wrappers.h new file mode 100644 index 000000000..060c3c89f --- /dev/null +++ b/include/internal/cef_string_wrappers.h @@ -0,0 +1,715 @@ +// Copyright (c) 2010 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_STRING_WRAPPERS_H_ +#define CEF_INCLUDE_INTERNAL_CEF_STRING_WRAPPERS_H_ +#pragma once + +#include +#include + +#include "include/base/cef_string16.h" +#include "include/internal/cef_string_types.h" + +/// +// Traits implementation for wide character strings. +/// +struct CefStringTraitsWide { + typedef wchar_t char_type; + typedef cef_string_wide_t struct_type; + typedef cef_string_userfree_wide_t userfree_struct_type; + + static inline void clear(struct_type *s) { cef_string_wide_clear(s); } + static inline int set(const char_type* src, size_t src_size, + struct_type* output, int copy) { + return cef_string_wide_set(src, src_size, output, copy); + } + static inline int compare(const struct_type* s1, const struct_type* s2) { + return cef_string_wide_cmp(s1, s2); + } + static inline userfree_struct_type userfree_alloc() { + return cef_string_userfree_wide_alloc(); + } + static inline void userfree_free(userfree_struct_type ufs) { + return cef_string_userfree_wide_free(ufs); + } + + // Conversion methods. + static inline bool from_ascii(const char* str, size_t len, struct_type *s) { + return cef_string_ascii_to_wide(str, len, s) ? true : false; + } + static inline std::string to_string(const struct_type *s) { + cef_string_utf8_t cstr; + memset(&cstr, 0, sizeof(cstr)); + cef_string_wide_to_utf8(s->str, s->length, &cstr); + std::string str; + if (cstr.length > 0) + str = std::string(cstr.str, cstr.length); + cef_string_utf8_clear(&cstr); + return str; + } + static inline bool from_string(const std::string& str, struct_type *s) { + return cef_string_utf8_to_wide(str.c_str(), str.length(), s) ? true : false; + } + static inline std::wstring to_wstring(const struct_type *s) { + return std::wstring(s->str, s->length); + } + static inline bool from_wstring(const std::wstring& str, struct_type *s) { + return cef_string_wide_set(str.c_str(), str.length(), s, true) ? + true : false; + } +#if defined(WCHAR_T_IS_UTF32) + static inline base::string16 to_string16(const struct_type *s) { + cef_string_utf16_t cstr; + memset(&cstr, 0, sizeof(cstr)); + cef_string_wide_to_utf16(s->str, s->length, &cstr); + base::string16 str; + if (cstr.length > 0) + str = base::string16(cstr.str, cstr.length); + cef_string_utf16_clear(&cstr); + return str; + } + static inline bool from_string16(const base::string16& str, + struct_type *s) { + return cef_string_utf16_to_wide(str.c_str(), str.length(), s) ? + true : false; + } +#else // WCHAR_T_IS_UTF32 + static inline base::string16 to_string16(const struct_type *s) { + return base::string16(s->str, s->length); + } + static inline bool from_string16(const base::string16& str, struct_type *s) { + return cef_string_wide_set(str.c_str(), str.length(), s, true) ? + true : false; + } +#endif // WCHAR_T_IS_UTF32 +}; + +/// +// Traits implementation for utf8 character strings. +/// +struct CefStringTraitsUTF8 { + typedef char char_type; + typedef cef_string_utf8_t struct_type; + typedef cef_string_userfree_utf8_t userfree_struct_type; + + static inline void clear(struct_type *s) { cef_string_utf8_clear(s); } + static inline int set(const char_type* src, size_t src_size, + struct_type* output, int copy) { + return cef_string_utf8_set(src, src_size, output, copy); + } + static inline int compare(const struct_type* s1, const struct_type* s2) { + return cef_string_utf8_cmp(s1, s2); + } + static inline userfree_struct_type userfree_alloc() { + return cef_string_userfree_utf8_alloc(); + } + static inline void userfree_free(userfree_struct_type ufs) { + return cef_string_userfree_utf8_free(ufs); + } + + // Conversion methods. + static inline bool from_ascii(const char* str, size_t len, struct_type* s) { + return cef_string_utf8_copy(str, len, s) ? true : false; + } + static inline std::string to_string(const struct_type* s) { + return std::string(s->str, s->length); + } + static inline bool from_string(const std::string& str, struct_type* s) { + return cef_string_utf8_copy(str.c_str(), str.length(), s) ? true : false; + } + static inline std::wstring to_wstring(const struct_type* s) { + cef_string_wide_t cstr; + memset(&cstr, 0, sizeof(cstr)); + cef_string_utf8_to_wide(s->str, s->length, &cstr); + std::wstring str; + if (cstr.length > 0) + str = std::wstring(cstr.str, cstr.length); + cef_string_wide_clear(&cstr); + return str; + } + static inline bool from_wstring(const std::wstring& str, struct_type* s) { + return cef_string_wide_to_utf8(str.c_str(), str.length(), s) ? true : false; + } + static inline base::string16 to_string16(const struct_type* s) { + cef_string_utf16_t cstr; + memset(&cstr, 0, sizeof(cstr)); + cef_string_utf8_to_utf16(s->str, s->length, &cstr); + base::string16 str; + if (cstr.length > 0) + str = base::string16(cstr.str, cstr.length); + cef_string_utf16_clear(&cstr); + return str; + } + static inline bool from_string16(const base::string16& str, struct_type* s) { + return cef_string_utf16_to_utf8(str.c_str(), str.length(), s) ? + true : false; + } +}; + +/// +// Traits implementation for utf16 character strings. +/// +struct CefStringTraitsUTF16 { + typedef char16 char_type; + typedef cef_string_utf16_t struct_type; + typedef cef_string_userfree_utf16_t userfree_struct_type; + + static inline void clear(struct_type *s) { cef_string_utf16_clear(s); } + static inline int set(const char_type* src, size_t src_size, + struct_type* output, int copy) { + return cef_string_utf16_set(src, src_size, output, copy); + } + static inline int compare(const struct_type* s1, const struct_type* s2) { + return cef_string_utf16_cmp(s1, s2); + } + static inline userfree_struct_type userfree_alloc() { + return cef_string_userfree_utf16_alloc(); + } + static inline void userfree_free(userfree_struct_type ufs) { + return cef_string_userfree_utf16_free(ufs); + } + + // Conversion methods. + static inline bool from_ascii(const char* str, size_t len, struct_type* s) { + return cef_string_ascii_to_utf16(str, len, s) ? true : false; + } + static inline std::string to_string(const struct_type* s) { + cef_string_utf8_t cstr; + memset(&cstr, 0, sizeof(cstr)); + cef_string_utf16_to_utf8(s->str, s->length, &cstr); + std::string str; + if (cstr.length > 0) + str = std::string(cstr.str, cstr.length); + cef_string_utf8_clear(&cstr); + return str; + } + static inline bool from_string(const std::string& str, struct_type* s) { + return cef_string_utf8_to_utf16(str.c_str(), str.length(), s) ? + true : false; + } +#if defined(WCHAR_T_IS_UTF32) + static inline std::wstring to_wstring(const struct_type* s) { + cef_string_wide_t cstr; + memset(&cstr, 0, sizeof(cstr)); + cef_string_utf16_to_wide(s->str, s->length, &cstr); + std::wstring str; + if (cstr.length > 0) + str = std::wstring(cstr.str, cstr.length); + cef_string_wide_clear(&cstr); + return str; + } + static inline bool from_wstring(const std::wstring& str, struct_type* s) { + return cef_string_wide_to_utf16(str.c_str(), str.length(), s) ? + true : false; + } +#else // WCHAR_T_IS_UTF32 + static inline std::wstring to_wstring(const struct_type* s) { + return std::wstring(s->str, s->length); + } + static inline bool from_wstring(const std::wstring& str, struct_type* s) { + return cef_string_utf16_set(str.c_str(), str.length(), s, true) ? + true : false; + } +#endif // WCHAR_T_IS_UTF32 + static inline base::string16 to_string16(const struct_type* s) { + return base::string16(s->str, s->length); + } + static inline bool from_string16(const base::string16& str, struct_type* s) { + return cef_string_utf16_set(str.c_str(), str.length(), s, true) ? + true : false; + } +}; + +/// +// CEF string classes can convert between all supported string types. For +// example, the CefStringWide class uses wchar_t as the underlying character +// type and provides two approaches for converting data to/from a UTF8 string +// (std::string). +//

+// 1. Implicit conversion using the assignment operator overload. +//

+//   CefStringWide aCefString;
+//   std::string aUTF8String;
+//   aCefString = aUTF8String; // Assign std::string to CefStringWide
+//   aUTF8String = aCefString; // Assign CefStringWide to std::string
+// 
+// 2. Explicit conversion using the FromString/ToString methods. +//
+//   CefStringWide aCefString;
+//   std::string aUTF8String;
+//   aCefString.FromString(aUTF8String); // Assign std::string to CefStringWide
+//   aUTF8String = aCefString.ToString(); // Assign CefStringWide to std::string
+// 
+// Conversion will only occur if the assigned value is a different string type. +// Assigning a std::string to a CefStringUTF8, for example, will copy the data +// without performing a conversion. +//

+// CEF string classes are safe for reading from multiple threads but not for +// modification. It is the user's responsibility to provide synchronization if +// modifying CEF strings from multiple threads. +/// +template +class CefStringBase { + public: + typedef typename traits::char_type char_type; + typedef typename traits::struct_type struct_type; + typedef typename traits::userfree_struct_type userfree_struct_type; + + /// + // Default constructor. + /// + CefStringBase() : string_(NULL), owner_(false) {} + + /// + // Create a new string from an existing string. Data will always be copied. + /// + CefStringBase(const CefStringBase& str) + : string_(NULL), owner_(false) { + FromString(str.c_str(), str.length(), true); + } + + /// + // Create a new string from an existing std::string. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + CefStringBase(const std::string& src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + FromString(src); + } + CefStringBase(const char* src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + if (src) + FromString(std::string(src)); + } + + /// + // Create a new string from an existing std::wstring. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + CefStringBase(const std::wstring& src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + FromWString(src); + } + CefStringBase(const wchar_t* src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + if (src) + FromWString(std::wstring(src)); + } + +#if defined(WCHAR_T_IS_UTF32) + /// + // Create a new string from an existing string16. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + CefStringBase(const base::string16& src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + FromString16(src); + } + CefStringBase(const char16* src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + if (src) + FromString16(base::string16(src)); + } +#endif // WCHAR_T_IS_UTF32 + + /// + // Create a new string from an existing character array. If |copy| is true + // this class will copy the data. Otherwise, this class will reference the + // existing data. Referenced data must exist for the lifetime of this class + // and will not be freed by this class. + /// + CefStringBase(const char_type* src, size_t src_len, bool copy) + : string_(NULL), owner_(false) { + if (src && src_len > 0) + FromString(src, src_len, copy); + } + + /// + // Create a new string referencing an existing string structure without taking + // ownership. Referenced structures must exist for the lifetime of this class + // and will not be freed by this class. + /// + CefStringBase(const struct_type* src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + if (!src) + return; + // Reference the existing structure without taking ownership. + Attach(const_cast(src), false); + } + + virtual ~CefStringBase() { ClearAndFree(); } + + + // The following methods are named for compatibility with the standard library + // string template types. + + /// + // Return a read-only pointer to the string data. + /// + const char_type* c_str() const { return (string_ ? string_->str : NULL); } + + /// + // Return the length of the string data. + /// + size_t length() const { return (string_ ? string_->length : 0); } + + /// + // Return the length of the string data. + /// + inline size_t size() const { return length(); } + + /// + // Returns true if the string is empty. + /// + bool empty() const { return (string_ == NULL || string_->length == 0); } + + /// + // Compare this string to the specified string. + /// + int compare(const CefStringBase& str) const { + if (empty() && str.empty()) + return 0; + if (empty()) + return -1; + if (str.empty()) + return 1; + return traits::compare(string_, str.GetStruct()); + } + + /// + // Clear the string data. + /// + void clear() { + if (string_) + traits::clear(string_); + } + + /// + // Swap this string's contents with the specified string. + /// + void swap(CefStringBase& str) { + struct_type* tmp_string = string_; + bool tmp_owner = owner_; + string_ = str.string_; + owner_ = str.owner_; + str.string_ = tmp_string; + str.owner_ = tmp_owner; + } + + + // The following methods are unique to CEF string template types. + + /// + // Returns true if this class owns the underlying string structure. + /// + bool IsOwner() const { return owner_; } + + /// + // Returns a read-only pointer to the underlying string structure. May return + // NULL if no structure is currently allocated. + /// + const struct_type* GetStruct() const { return string_; } + + /// + // Returns a writable pointer to the underlying string structure. Will never + // return NULL. + /// + struct_type* GetWritableStruct() { + AllocIfNeeded(); + return string_; + } + + /// + // Clear the state of this class. The underlying string structure and data + // will be freed if this class owns the structure. + /// + void ClearAndFree() { + if (!string_) + return; + if (owner_) { + clear(); + delete string_; + } + string_ = NULL; + owner_ = false; + } + + /// + // Attach to the specified string structure. If |owner| is true this class + // will take ownership of the structure. + /// + void Attach(struct_type* str, bool owner) { + // Free the previous structure and data, if any. + ClearAndFree(); + + string_ = str; + owner_ = owner; + } + + /// + // Take ownership of the specified userfree structure's string data. The + // userfree structure itself will be freed. Only use this method with userfree + // structures. + /// + void AttachToUserFree(userfree_struct_type str) { + // Free the previous structure and data, if any. + ClearAndFree(); + + if (!str) + return; + + AllocIfNeeded(); + owner_ = true; + memcpy(string_, str, sizeof(struct_type)); + + // Free the |str| structure but not the data. + memset(str, 0, sizeof(struct_type)); + traits::userfree_free(str); + } + + /// + // Detach from the underlying string structure. To avoid memory leaks only use + // this method if you already hold a pointer to the underlying string + // structure. + /// + void Detach() { + string_ = NULL; + owner_ = false; + } + + /// + // Create a userfree structure and give it ownership of this class' string + // data. This class will be disassociated from the data. May return NULL if + // this string class currently contains no data. + /// + userfree_struct_type DetachToUserFree() { + if (empty()) + return NULL; + + userfree_struct_type str = traits::userfree_alloc(); + memcpy(str, string_, sizeof(struct_type)); + + // Free this class' structure but not the data. + memset(string_, 0, sizeof(struct_type)); + ClearAndFree(); + + return str; + } + + /// + // Set this string's data to the specified character array. If |copy| is true + // this class will copy the data. Otherwise, this class will reference the + // existing data. Referenced data must exist for the lifetime of this class + // and will not be freed by this class. + /// + bool FromString(const char_type* src, size_t src_len, bool copy) { + if (src == NULL || src_len == 0) { + clear(); + return true; + } + AllocIfNeeded(); + return traits::set(src, src_len, string_, copy) ? true : false; + } + + /// + // Set this string's data from an existing ASCII string. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + bool FromASCII(const char* str) { + size_t len = str ? strlen(str) : 0; + if (len == 0) { + clear(); + return true; + } + AllocIfNeeded(); + return traits::from_ascii(str, len, string_); + } + + /// + // Return this string's data as a std::string. Translation will occur if + // necessary based on the underlying string type. + /// + std::string ToString() const { + if (empty()) + return std::string(); + return traits::to_string(string_); + } + + /// + // Set this string's data from an existing std::string. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + bool FromString(const std::string& str) { + if (str.empty()) { + clear(); + return true; + } + AllocIfNeeded(); + return traits::from_string(str, string_); + } + + /// + // Return this string's data as a std::wstring. Translation will occur if + // necessary based on the underlying string type. + /// + std::wstring ToWString() const { + if (empty()) + return std::wstring(); + return traits::to_wstring(string_); + } + + /// + // Set this string's data from an existing std::wstring. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + bool FromWString(const std::wstring& str) { + if (str.empty()) { + clear(); + return true; + } + AllocIfNeeded(); + return traits::from_wstring(str, string_); + } + + /// + // Return this string's data as a string16. Translation will occur if + // necessary based on the underlying string type. + /// + base::string16 ToString16() const { + if (empty()) + return base::string16(); + return traits::to_string16(string_); + } + + /// + // Set this string's data from an existing string16. Data will be always + // copied. Translation will occur if necessary based on the underlying string + // type. + /// + bool FromString16(const base::string16& str) { + if (str.empty()) { + clear(); + return true; + } + AllocIfNeeded(); + return traits::from_string16(str, string_); + } + + /// + // Comparison operator overloads. + /// + bool operator<(const CefStringBase& str) const { + return (compare(str) < 0); + } + bool operator<=(const CefStringBase& str) const { + return (compare(str) <= 0); + } + bool operator>(const CefStringBase& str) const { + return (compare(str) > 0); + } + bool operator>=(const CefStringBase& str) const { + return (compare(str) >= 0); + } + bool operator==(const CefStringBase& str) const { + return (compare(str) == 0); + } + bool operator!=(const CefStringBase& str) const { + return (compare(str) != 0); + } + + /// + // Assignment operator overloads. + /// + CefStringBase& operator=(const CefStringBase& str) { + FromString(str.c_str(), str.length(), true); + return *this; + } + operator std::string() const { + return ToString(); + } + CefStringBase& operator=(const std::string& str) { + FromString(str); + return *this; + } + CefStringBase& operator=(const char* str) { + FromString(std::string(str)); + return *this; + } + operator std::wstring() const { + return ToWString(); + } + CefStringBase& operator=(const std::wstring& str) { + FromWString(str); + return *this; + } + CefStringBase& operator=(const wchar_t* str) { + FromWString(std::wstring(str)); + return *this; + } +#if defined(WCHAR_T_IS_UTF32) + operator base::string16() const { + return ToString16(); + } + CefStringBase& operator=(const base::string16& str) { + FromString16(str); + return *this; + } + CefStringBase& operator=(const char16* str) { + FromString16(base::string16(str)); + return *this; + } +#endif // WCHAR_T_IS_UTF32 + + private: + // Allocate the string structure if it doesn't already exist. + void AllocIfNeeded() { + if (string_ == NULL) { + string_ = new struct_type; + memset(string_, 0, sizeof(struct_type)); + owner_ = true; + } + } + + struct_type* string_; + bool owner_; +}; + + +typedef CefStringBase CefStringWide; +typedef CefStringBase CefStringUTF8; +typedef CefStringBase CefStringUTF16; + +#endif // CEF_INCLUDE_INTERNAL_CEF_STRING_WRAPPERS_H_ diff --git a/include/internal/cef_thread_internal.h b/include/internal/cef_thread_internal.h new file mode 100644 index 000000000..eee2b2ae4 --- /dev/null +++ b/include/internal/cef_thread_internal.h @@ -0,0 +1,74 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_THREAD_INTERNAL_H_ +#define CEF_INCLUDE_INTERNAL_CEF_THREAD_INTERNAL_H_ +#pragma once + +#if defined(OS_WIN) +#include +#elif defined(OS_POSIX) +#include +#include +#endif + +#include "include/internal/cef_export.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(OS_WIN) +typedef DWORD cef_platform_thread_id_t; +#elif defined(OS_POSIX) +typedef pid_t cef_platform_thread_id_t; +#endif + +/// +// Returns the current platform thread ID. +/// +CEF_EXPORT cef_platform_thread_id_t cef_get_current_platform_thread_id(); + +#if defined(OS_WIN) +typedef DWORD cef_platform_thread_handle_t; +#elif defined(OS_POSIX) +typedef pthread_t cef_platform_thread_handle_t; +#endif + +/// +// Returns the current platform thread handle. +/// +CEF_EXPORT cef_platform_thread_handle_t + cef_get_current_platform_thread_handle(); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // CEF_INCLUDE_INTERNAL_CEF_THREAD_INTERNAL_H_ diff --git a/include/internal/cef_time.h b/include/internal/cef_time.h new file mode 100644 index 000000000..64e601fe0 --- /dev/null +++ b/include/internal/cef_time.h @@ -0,0 +1,88 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TIME_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TIME_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/internal/cef_export.h" +#include + +/// +// Time information. Values should always be in UTC. +/// +typedef struct _cef_time_t { + int year; // Four digit year "2007" + int month; // 1-based month (values 1 = January, etc.) + int day_of_week; // 0-based day of week (0 = Sunday, etc.) + int day_of_month; // 1-based day of month (1-31) + int hour; // Hour within the current day (0-23) + int minute; // Minute within the current hour (0-59) + int second; // Second within the current minute (0-59 plus leap + // seconds which may take it up to 60). + int millisecond; // Milliseconds within the current second (0-999) +} cef_time_t; + +/// +// Converts cef_time_t to/from time_t. Returns true (1) on success and false (0) +// on failure. +/// +CEF_EXPORT int cef_time_to_timet(const cef_time_t* cef_time, time_t* time); +CEF_EXPORT int cef_time_from_timet(time_t time, cef_time_t* cef_time); + +/// +// Converts cef_time_t to/from a double which is the number of seconds since +// epoch (Jan 1, 1970). Webkit uses this format to represent time. A value of 0 +// means "not initialized". Returns true (1) on success and false (0) on +// failure. +/// +CEF_EXPORT int cef_time_to_doublet(const cef_time_t* cef_time, double* time); +CEF_EXPORT int cef_time_from_doublet(double time, cef_time_t* cef_time); + +/// +// Retrieve the current system time. +// +CEF_EXPORT int cef_time_now(cef_time_t* cef_time); + +/// +// Retrieve the delta in milliseconds between two time values. +// +CEF_EXPORT int cef_time_delta(const cef_time_t* cef_time1, + const cef_time_t* cef_time2, + long long* delta); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_TIME_H_ diff --git a/include/internal/cef_trace_event_internal.h b/include/internal/cef_trace_event_internal.h new file mode 100644 index 000000000..6df870717 --- /dev/null +++ b/include/internal/cef_trace_event_internal.h @@ -0,0 +1,124 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TRACE_EVENT_INTERNAL_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TRACE_EVENT_INTERNAL_H_ +#pragma once + +#include "include/internal/cef_export.h" +#include "include/internal/cef_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// See include/base/cef_trace_event.h for macros and intended usage. + +// Functions for tracing counters and functions; called from macros. +// - |category| string must have application lifetime (static or literal). They +// may not include "(quotes) chars. +// - |argX_name|, |argX_val|, |valueX_name|, |valeX_val| are optional parameters +// and represent pairs of name and values of arguments +// - |copy| is used to avoid memory scoping issues with the |name| and +// |arg_name| parameters by copying them +// - |id| is used to disambiguate counters with the same name, or match async +// trace events + +CEF_EXPORT void cef_trace_event_instant(const char* category, + const char* name, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy); +CEF_EXPORT void cef_trace_event_begin(const char* category, + const char* name, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy); +CEF_EXPORT void cef_trace_event_end(const char* category, + const char* name, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy); +CEF_EXPORT void cef_trace_counter(const char* category, + const char* name, + const char* value1_name, + uint64 value1_val, + const char* value2_name, + uint64 value2_val, + int copy); +CEF_EXPORT void cef_trace_counter_id(const char* category, + const char* name, + uint64 id, + const char* value1_name, + uint64 value1_val, + const char* value2_name, + uint64 value2_val, + int copy); +CEF_EXPORT void cef_trace_event_async_begin(const char* category, + const char* name, + uint64 id, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy); +CEF_EXPORT void cef_trace_event_async_step_into(const char* category, + const char* name, + uint64 id, + uint64 step, + const char* arg1_name, + uint64 arg1_val, + int copy); +CEF_EXPORT void cef_trace_event_async_step_past(const char* category, + const char* name, + uint64 id, + uint64 step, + const char* arg1_name, + uint64 arg1_val, + int copy); +CEF_EXPORT void cef_trace_event_async_end(const char* category, + const char* name, + uint64 id, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif // CEF_INCLUDE_INTERNAL_CEF_TRACE_EVENT_INTERNAL_H_ diff --git a/include/internal/cef_types.h b/include/internal/cef_types.h new file mode 100644 index 000000000..376e38247 --- /dev/null +++ b/include/internal/cef_types.h @@ -0,0 +1,1934 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TYPES_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_H_ +#pragma once + +#include "include/base/cef_build.h" +#include "include/internal/cef_string.h" +#include "include/internal/cef_string_list.h" +#include "include/internal/cef_time.h" + +// Bring in platform-specific definitions. +#if defined(OS_WIN) +#include "include/internal/cef_types_win.h" +#elif defined(OS_MACOSX) +#include "include/internal/cef_types_mac.h" +#elif defined(OS_LINUX) +#include "include/internal/cef_types_linux.h" +#endif + +#include // For UINT_MAX +#include // For size_t + +// The NSPR system headers define 64-bit as |long| when possible, except on +// Mac OS X. In order to not have typedef mismatches, we do the same on LP64. +// +// On Mac OS X, |long long| is used for 64-bit types for compatibility with +// format macros even in the LP64 model. +#if defined(__LP64__) && !defined(OS_MACOSX) && !defined(OS_OPENBSD) +typedef long int64; // NOLINT(runtime/int) +typedef unsigned long uint64; // NOLINT(runtime/int) +#else +typedef long long int64; // NOLINT(runtime/int) +typedef unsigned long long uint64; // NOLINT(runtime/int) +#endif + +// TODO: Remove these type guards. These are to avoid conflicts with +// obsolete/protypes.h in the Gecko SDK. +#ifndef _INT32 +#define _INT32 +typedef int int32; +#endif + +// TODO: Remove these type guards. These are to avoid conflicts with +// obsolete/protypes.h in the Gecko SDK. +#ifndef _UINT32 +#define _UINT32 +typedef unsigned int uint32; +#endif + +// UTF-16 character type +#ifndef char16 +#if defined(WIN32) +typedef wchar_t char16; +#else +typedef unsigned short char16; +#endif +#endif + +// 32-bit ARGB color value, not premultiplied. The color components are always +// in a known order. Equivalent to the SkColor type. +typedef uint32 cef_color_t; + +// Return the alpha byte from a cef_color_t value. +#define CefColorGetA(color) (((color) >> 24) & 0xFF) +// Return the red byte from a cef_color_t value. +#define CefColorGetR(color) (((color) >> 16) & 0xFF) +// Return the green byte from a cef_color_t value. +#define CefColorGetG(color) (((color) >> 8) & 0xFF) +// Return the blue byte from a cef_color_t value. +#define CefColorGetB(color) (((color) >> 0) & 0xFF) + +// Return an cef_color_t value with the specified byte component values. +#define CefColorSetARGB(a, r, g, b) \ + static_cast( \ + (static_cast(a) << 24) | \ + (static_cast(r) << 16) | \ + (static_cast(g) << 8) | \ + (static_cast(b) << 0)) + +// Return an int64 value with the specified low and high int32 component values. +#define CefInt64Set(int32_low, int32_high) \ + static_cast((static_cast(int32_low)) | \ + (static_cast(static_cast(int32_high))) << 32) + +// Return the low int32 value from an int64 value. +#define CefInt64GetLow(int64_val) static_cast(int64_val) +// Return the high int32 value from an int64 value. +#define CefInt64GetHigh(int64_val) \ + static_cast((static_cast(int64_val) >> 32) & 0xFFFFFFFFL) + + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Log severity levels. +/// +typedef enum { + /// + // Default logging (currently INFO logging). + /// + LOGSEVERITY_DEFAULT, + + /// + // Verbose logging. + /// + LOGSEVERITY_VERBOSE, + + /// + // INFO logging. + /// + LOGSEVERITY_INFO, + + /// + // WARNING logging. + /// + LOGSEVERITY_WARNING, + + /// + // ERROR logging. + /// + LOGSEVERITY_ERROR, + + /// + // Completely disable logging. + /// + LOGSEVERITY_DISABLE = 99 +} cef_log_severity_t; + +/// +// Represents the state of a setting. +/// +typedef enum { + /// + // Use the default state for the setting. + /// + STATE_DEFAULT = 0, + + /// + // Enable or allow the setting. + /// + STATE_ENABLED, + + /// + // Disable or disallow the setting. + /// + STATE_DISABLED, +} cef_state_t; + +/// +// Initialization settings. Specify NULL or 0 to get the recommended default +// values. Many of these and other settings can also configured using command- +// line switches. +/// +typedef struct _cef_settings_t { + /// + // Size of this structure. + /// + size_t size; + + /// + // Set to true (1) to use a single process for the browser and renderer. This + // run mode is not officially supported by Chromium and is less stable than + // the multi-process default. Also configurable using the "single-process" + // command-line switch. + /// + int single_process; + + /// + // Set to true (1) to disable the sandbox for sub-processes. See + // cef_sandbox_win.h for requirements to enable the sandbox on Windows. Also + // configurable using the "no-sandbox" command-line switch. + /// + int no_sandbox; + + /// + // The path to a separate executable that will be launched for sub-processes. + // By default the browser process executable is used. See the comments on + // CefExecuteProcess() for details. Also configurable using the + // "browser-subprocess-path" command-line switch. + /// + cef_string_t browser_subprocess_path; + + /// + // Set to true (1) to have the browser process message loop run in a separate + // thread. If false (0) than the CefDoMessageLoopWork() function must be + // called from your application message loop. + /// + int multi_threaded_message_loop; + + /// + // Set to true (1) to enable windowless (off-screen) rendering support. Do not + // enable this value if the application does not use windowless rendering as + // it may reduce rendering performance on some systems. + /// + int windowless_rendering_enabled; + + /// + // Set to true (1) to disable configuration of browser process features using + // standard CEF and Chromium command-line arguments. Configuration can still + // be specified using CEF data structures or via the + // CefApp::OnBeforeCommandLineProcessing() method. + /// + int command_line_args_disabled; + + /// + // The location where cache data will be stored on disk. If empty an in-memory + // cache will be used for some features and a temporary disk cache for others. + // HTML5 databases such as localStorage will only persist across sessions if a + // cache path is specified. + /// + cef_string_t cache_path; + + /// + // To persist session cookies (cookies without an expiry date or validity + // interval) by default when using the global cookie manager set this value to + // true. Session cookies are generally intended to be transient and most Web + // browsers do not persist them. A |cache_path| value must also be specified to + // enable this feature. Also configurable using the "persist-session-cookies" + // command-line switch. + /// + int persist_session_cookies; + + /// + // Value that will be returned as the User-Agent HTTP header. If empty the + // default User-Agent string will be used. Also configurable using the + // "user-agent" command-line switch. + /// + cef_string_t user_agent; + + /// + // Value that will be inserted as the product portion of the default + // User-Agent string. If empty the Chromium product version will be used. If + // |userAgent| is specified this value will be ignored. Also configurable + // using the "product-version" command-line switch. + /// + cef_string_t product_version; + + /// + // The locale string that will be passed to WebKit. If empty the default + // locale of "en-US" will be used. This value is ignored on Linux where locale + // is determined using environment variable parsing with the precedence order: + // LANGUAGE, LC_ALL, LC_MESSAGES and LANG. Also configurable using the "lang" + // command-line switch. + /// + cef_string_t locale; + + /// + // The directory and file name to use for the debug log. If empty, the + // default name of "debug.log" will be used and the file will be written + // to the application directory. Also configurable using the "log-file" + // command-line switch. + /// + cef_string_t log_file; + + /// + // The log severity. Only messages of this severity level or higher will be + // logged. Also configurable using the "log-severity" command-line switch with + // a value of "verbose", "info", "warning", "error", "error-report" or + // "disable". + /// + cef_log_severity_t log_severity; + + /// + // Custom flags that will be used when initializing the V8 JavaScript engine. + // The consequences of using custom flags may not be well tested. Also + // configurable using the "js-flags" command-line switch. + /// + cef_string_t javascript_flags; + + /// + // The fully qualified path for the resources directory. If this value is + // empty the cef.pak and/or devtools_resources.pak files must be located in + // the module directory on Windows/Linux or the app bundle Resources directory + // on Mac OS X. Also configurable using the "resources-dir-path" command-line + // switch. + /// + cef_string_t resources_dir_path; + + /// + // The fully qualified path for the locales directory. If this value is empty + // the locales directory must be located in the module directory. This value + // is ignored on Mac OS X where pack files are always loaded from the app + // bundle Resources directory. Also configurable using the "locales-dir-path" + // command-line switch. + /// + cef_string_t locales_dir_path; + + /// + // Set to true (1) to disable loading of pack files for resources and locales. + // A resource bundle handler must be provided for the browser and render + // processes via CefApp::GetResourceBundleHandler() if loading of pack files + // is disabled. Also configurable using the "disable-pack-loading" command- + // line switch. + /// + int pack_loading_disabled; + + /// + // Set to a value between 1024 and 65535 to enable remote debugging on the + // specified port. For example, if 8080 is specified the remote debugging URL + // will be http://localhost:8080. CEF can be remotely debugged from any CEF or + // Chrome browser window. Also configurable using the "remote-debugging-port" + // command-line switch. + /// + int remote_debugging_port; + + /// + // The number of stack trace frames to capture for uncaught exceptions. + // Specify a positive value to enable the CefV8ContextHandler:: + // OnUncaughtException() callback. Specify 0 (default value) and + // OnUncaughtException() will not be called. Also configurable using the + // "uncaught-exception-stack-size" command-line switch. + /// + int uncaught_exception_stack_size; + + /// + // By default CEF V8 references will be invalidated (the IsValid() method will + // return false) after the owning context has been released. This reduces the + // need for external record keeping and avoids crashes due to the use of V8 + // references after the associated context has been released. + // + // CEF currently offers two context safety implementations with different + // performance characteristics. The default implementation (value of 0) uses a + // map of hash values and should provide better performance in situations with + // a small number contexts. The alternate implementation (value of 1) uses a + // hidden value attached to each context and should provide better performance + // in situations with a large number of contexts. + // + // If you need better performance in the creation of V8 references and you + // plan to manually track context lifespan you can disable context safety by + // specifying a value of -1. + // + // Also configurable using the "context-safety-implementation" command-line + // switch. + /// + int context_safety_implementation; + + /// + // Set to true (1) to ignore errors related to invalid SSL certificates. + // Enabling this setting can lead to potential security vulnerabilities like + // "man in the middle" attacks. Applications that load content from the + // internet should not enable this setting. Also configurable using the + // "ignore-certificate-errors" command-line switch. + /// + int ignore_certificate_errors; + + /// + // Opaque background color used for accelerated content. By default the + // background color will be white. Only the RGB compontents of the specified + // value will be used. The alpha component must greater than 0 to enable use + // of the background color but will be otherwise ignored. + /// + cef_color_t background_color; +} cef_settings_t; + +/// +// Browser initialization settings. Specify NULL or 0 to get the recommended +// default values. The consequences of using custom values may not be well +// tested. Many of these and other settings can also configured using command- +// line switches. +/// +typedef struct _cef_browser_settings_t { + /// + // Size of this structure. + /// + size_t size; + + /// + // The maximum rate in frames per second (fps) that CefRenderHandler::OnPaint + // will be called for a windowless browser. The actual fps may be lower if + // the browser cannot generate frames at the requested rate. The minimum + // value is 1 and the maximum value is 60 (default 30). + /// + int windowless_frame_rate; + + // The below values map to WebPreferences settings. + + /// + // Font settings. + /// + cef_string_t standard_font_family; + cef_string_t fixed_font_family; + cef_string_t serif_font_family; + cef_string_t sans_serif_font_family; + cef_string_t cursive_font_family; + cef_string_t fantasy_font_family; + int default_font_size; + int default_fixed_font_size; + int minimum_font_size; + int minimum_logical_font_size; + + /// + // Default encoding for Web content. If empty "ISO-8859-1" will be used. Also + // configurable using the "default-encoding" command-line switch. + /// + cef_string_t default_encoding; + + /// + // Controls the loading of fonts from remote sources. Also configurable using + // the "disable-remote-fonts" command-line switch. + /// + cef_state_t remote_fonts; + + /// + // Controls whether JavaScript can be executed. Also configurable using the + // "disable-javascript" command-line switch. + /// + cef_state_t javascript; + + /// + // Controls whether JavaScript can be used for opening windows. Also + // configurable using the "disable-javascript-open-windows" command-line + // switch. + /// + cef_state_t javascript_open_windows; + + /// + // Controls whether JavaScript can be used to close windows that were not + // opened via JavaScript. JavaScript can still be used to close windows that + // were opened via JavaScript. Also configurable using the + // "disable-javascript-close-windows" command-line switch. + /// + cef_state_t javascript_close_windows; + + /// + // Controls whether JavaScript can access the clipboard. Also configurable + // using the "disable-javascript-access-clipboard" command-line switch. + /// + cef_state_t javascript_access_clipboard; + + /// + // Controls whether DOM pasting is supported in the editor via + // execCommand("paste"). The |javascript_access_clipboard| setting must also + // be enabled. Also configurable using the "disable-javascript-dom-paste" + // command-line switch. + /// + cef_state_t javascript_dom_paste; + + /// + // Controls whether the caret position will be drawn. Also configurable using + // the "enable-caret-browsing" command-line switch. + /// + cef_state_t caret_browsing; + + /// + // Controls whether the Java plugin will be loaded. Also configurable using + // the "disable-java" command-line switch. + /// + cef_state_t java; + + /// + // Controls whether any plugins will be loaded. Also configurable using the + // "disable-plugins" command-line switch. + /// + cef_state_t plugins; + + /// + // Controls whether file URLs will have access to all URLs. Also configurable + // using the "allow-universal-access-from-files" command-line switch. + /// + cef_state_t universal_access_from_file_urls; + + /// + // Controls whether file URLs will have access to other file URLs. Also + // configurable using the "allow-access-from-files" command-line switch. + /// + cef_state_t file_access_from_file_urls; + + /// + // Controls whether web security restrictions (same-origin policy) will be + // enforced. Disabling this setting is not recommend as it will allow risky + // security behavior such as cross-site scripting (XSS). Also configurable + // using the "disable-web-security" command-line switch. + /// + cef_state_t web_security; + + /// + // Controls whether image URLs will be loaded from the network. A cached image + // will still be rendered if requested. Also configurable using the + // "disable-image-loading" command-line switch. + /// + cef_state_t image_loading; + + /// + // Controls whether standalone images will be shrunk to fit the page. Also + // configurable using the "image-shrink-standalone-to-fit" command-line + // switch. + /// + cef_state_t image_shrink_standalone_to_fit; + + /// + // Controls whether text areas can be resized. Also configurable using the + // "disable-text-area-resize" command-line switch. + /// + cef_state_t text_area_resize; + + /// + // Controls whether the tab key can advance focus to links. Also configurable + // using the "disable-tab-to-links" command-line switch. + /// + cef_state_t tab_to_links; + + /// + // Controls whether local storage can be used. Also configurable using the + // "disable-local-storage" command-line switch. + /// + cef_state_t local_storage; + + /// + // Controls whether databases can be used. Also configurable using the + // "disable-databases" command-line switch. + /// + cef_state_t databases; + + /// + // Controls whether the application cache can be used. Also configurable using + // the "disable-application-cache" command-line switch. + /// + cef_state_t application_cache; + + /// + // Controls whether WebGL can be used. Note that WebGL requires hardware + // support and may not work on all systems even when enabled. Also + // configurable using the "disable-webgl" command-line switch. + /// + cef_state_t webgl; + + /// + // Opaque background color used for the browser before a document is loaded + // and when no document color is specified. By default the background color + // will be the same as CefSettings.background_color. Only the RGB compontents + // of the specified value will be used. The alpha component must greater than + // 0 to enable use of the background color but will be otherwise ignored. + /// + cef_color_t background_color; +} cef_browser_settings_t; + +/// +// URL component parts. +/// +typedef struct _cef_urlparts_t { + /// + // The complete URL specification. + /// + cef_string_t spec; + + /// + // Scheme component not including the colon (e.g., "http"). + /// + cef_string_t scheme; + + /// + // User name component. + /// + cef_string_t username; + + /// + // Password component. + /// + cef_string_t password; + + /// + // Host component. This may be a hostname, an IPv4 address or an IPv6 literal + // surrounded by square brackets (e.g., "[2001:db8::1]"). + /// + cef_string_t host; + + /// + // Port number component. + /// + cef_string_t port; + + /// + // Origin contains just the scheme, host, and port from a URL. Equivalent to + // clearing any username and password, replacing the path with a slash, and + // clearing everything after that. This value will be empty for non-standard + // URLs. + /// + cef_string_t origin; + + /// + // Path component including the first slash following the host. + /// + cef_string_t path; + + /// + // Query string component (i.e., everything following the '?'). + /// + cef_string_t query; +} cef_urlparts_t; + +/// +// Cookie information. +/// +typedef struct _cef_cookie_t { + /// + // The cookie name. + /// + cef_string_t name; + + /// + // The cookie value. + /// + cef_string_t value; + + /// + // If |domain| is empty a host cookie will be created instead of a domain + // cookie. Domain cookies are stored with a leading "." and are visible to + // sub-domains whereas host cookies are not. + /// + cef_string_t domain; + + /// + // If |path| is non-empty only URLs at or below the path will get the cookie + // value. + /// + cef_string_t path; + + /// + // If |secure| is true the cookie will only be sent for HTTPS requests. + /// + int secure; + + /// + // If |httponly| is true the cookie will only be sent for HTTP requests. + /// + int httponly; + + /// + // The cookie creation date. This is automatically populated by the system on + // cookie creation. + /// + cef_time_t creation; + + /// + // The cookie last access date. This is automatically populated by the system + // on access. + /// + cef_time_t last_access; + + /// + // The cookie expiration date is only valid if |has_expires| is true. + /// + int has_expires; + cef_time_t expires; +} cef_cookie_t; + +/// +// Process termination status values. +/// +typedef enum { + /// + // Non-zero exit status. + /// + TS_ABNORMAL_TERMINATION, + + /// + // SIGKILL or task manager kill. + /// + TS_PROCESS_WAS_KILLED, + + /// + // Segmentation fault. + /// + TS_PROCESS_CRASHED, +} cef_termination_status_t; + +/// +// Path key values. +/// +typedef enum { + /// + // Current directory. + /// + PK_DIR_CURRENT, + + /// + // Directory containing PK_FILE_EXE. + /// + PK_DIR_EXE, + + /// + // Directory containing PK_FILE_MODULE. + /// + PK_DIR_MODULE, + + /// + // Temporary directory. + /// + PK_DIR_TEMP, + + /// + // Path and filename of the current executable. + /// + PK_FILE_EXE, + + /// + // Path and filename of the module containing the CEF code (usually the libcef + // module). + /// + PK_FILE_MODULE, +} cef_path_key_t; + +/// +// Storage types. +/// +typedef enum { + ST_LOCALSTORAGE = 0, + ST_SESSIONSTORAGE, +} cef_storage_type_t; + +/// +// Supported error code values. See net\base\net_error_list.h for complete +// descriptions of the error codes. +/// +typedef enum { + ERR_NONE = 0, + ERR_FAILED = -2, + ERR_ABORTED = -3, + ERR_INVALID_ARGUMENT = -4, + ERR_INVALID_HANDLE = -5, + ERR_FILE_NOT_FOUND = -6, + ERR_TIMED_OUT = -7, + ERR_FILE_TOO_BIG = -8, + ERR_UNEXPECTED = -9, + ERR_ACCESS_DENIED = -10, + ERR_NOT_IMPLEMENTED = -11, + ERR_CONNECTION_CLOSED = -100, + ERR_CONNECTION_RESET = -101, + ERR_CONNECTION_REFUSED = -102, + ERR_CONNECTION_ABORTED = -103, + ERR_CONNECTION_FAILED = -104, + ERR_NAME_NOT_RESOLVED = -105, + ERR_INTERNET_DISCONNECTED = -106, + ERR_SSL_PROTOCOL_ERROR = -107, + ERR_ADDRESS_INVALID = -108, + ERR_ADDRESS_UNREACHABLE = -109, + ERR_SSL_CLIENT_AUTH_CERT_NEEDED = -110, + ERR_TUNNEL_CONNECTION_FAILED = -111, + ERR_NO_SSL_VERSIONS_ENABLED = -112, + ERR_SSL_VERSION_OR_CIPHER_MISMATCH = -113, + ERR_SSL_RENEGOTIATION_REQUESTED = -114, + ERR_CERT_COMMON_NAME_INVALID = -200, + ERR_CERT_DATE_INVALID = -201, + ERR_CERT_AUTHORITY_INVALID = -202, + ERR_CERT_CONTAINS_ERRORS = -203, + ERR_CERT_NO_REVOCATION_MECHANISM = -204, + ERR_CERT_UNABLE_TO_CHECK_REVOCATION = -205, + ERR_CERT_REVOKED = -206, + ERR_CERT_INVALID = -207, + ERR_CERT_END = -208, + ERR_INVALID_URL = -300, + ERR_DISALLOWED_URL_SCHEME = -301, + ERR_UNKNOWN_URL_SCHEME = -302, + ERR_TOO_MANY_REDIRECTS = -310, + ERR_UNSAFE_REDIRECT = -311, + ERR_UNSAFE_PORT = -312, + ERR_INVALID_RESPONSE = -320, + ERR_INVALID_CHUNKED_ENCODING = -321, + ERR_METHOD_NOT_SUPPORTED = -322, + ERR_UNEXPECTED_PROXY_AUTH = -323, + ERR_EMPTY_RESPONSE = -324, + ERR_RESPONSE_HEADERS_TOO_BIG = -325, + ERR_CACHE_MISS = -400, + ERR_INSECURE_RESPONSE = -501, +} cef_errorcode_t; + +/// +// "Verb" of a drag-and-drop operation as negotiated between the source and +// destination. These constants match their equivalents in WebCore's +// DragActions.h and should not be renumbered. +/// +typedef enum { + DRAG_OPERATION_NONE = 0, + DRAG_OPERATION_COPY = 1, + DRAG_OPERATION_LINK = 2, + DRAG_OPERATION_GENERIC = 4, + DRAG_OPERATION_PRIVATE = 8, + DRAG_OPERATION_MOVE = 16, + DRAG_OPERATION_DELETE = 32, + DRAG_OPERATION_EVERY = UINT_MAX +} cef_drag_operations_mask_t; + +/// +// V8 access control values. +/// +typedef enum { + V8_ACCESS_CONTROL_DEFAULT = 0, + V8_ACCESS_CONTROL_ALL_CAN_READ = 1, + V8_ACCESS_CONTROL_ALL_CAN_WRITE = 1 << 1, + V8_ACCESS_CONTROL_PROHIBITS_OVERWRITING = 1 << 2 +} cef_v8_accesscontrol_t; + +/// +// V8 property attribute values. +/// +typedef enum { + V8_PROPERTY_ATTRIBUTE_NONE = 0, // Writeable, Enumerable, + // Configurable + V8_PROPERTY_ATTRIBUTE_READONLY = 1 << 0, // Not writeable + V8_PROPERTY_ATTRIBUTE_DONTENUM = 1 << 1, // Not enumerable + V8_PROPERTY_ATTRIBUTE_DONTDELETE = 1 << 2 // Not configurable +} cef_v8_propertyattribute_t; + +/// +// Post data elements may represent either bytes or files. +/// +typedef enum { + PDE_TYPE_EMPTY = 0, + PDE_TYPE_BYTES, + PDE_TYPE_FILE, +} cef_postdataelement_type_t; + +/// +// Resource type for a request. +/// +typedef enum { + /// + // Top level page. + /// + RT_MAIN_FRAME = 0, + + /// + // Frame or iframe. + /// + RT_SUB_FRAME, + + /// + // CSS stylesheet. + /// + RT_STYLESHEET, + + /// + // External script. + /// + RT_SCRIPT, + + /// + // Image (jpg/gif/png/etc). + /// + RT_IMAGE, + + /// + // Font. + /// + RT_FONT_RESOURCE, + + /// + // Some other subresource. This is the default type if the actual type is + // unknown. + /// + RT_SUB_RESOURCE, + + /// + // Object (or embed) tag for a plugin, or a resource that a plugin requested. + /// + RT_OBJECT, + + /// + // Media resource. + /// + RT_MEDIA, + + /// + // Main resource of a dedicated worker. + /// + RT_WORKER, + + /// + // Main resource of a shared worker. + /// + RT_SHARED_WORKER, + + /// + // Explicitly requested prefetch. + /// + RT_PREFETCH, + + /// + // Favicon. + /// + RT_FAVICON, + + /// + // XMLHttpRequest. + /// + RT_XHR, + + /// + // A request for a + /// + RT_PING, + + /// + // Main resource of a service worker. + /// + RT_SERVICE_WORKER, +} cef_resource_type_t; + +/// +// Transition type for a request. Made up of one source value and 0 or more +// qualifiers. +/// +typedef enum { + /// + // Source is a link click or the JavaScript window.open function. This is + // also the default value for requests like sub-resource loads that are not + // navigations. + /// + TT_LINK = 0, + + /// + // Source is some other "explicit" navigation action such as creating a new + // browser or using the LoadURL function. This is also the default value + // for navigations where the actual type is unknown. + /// + TT_EXPLICIT = 1, + + /// + // Source is a subframe navigation. This is any content that is automatically + // loaded in a non-toplevel frame. For example, if a page consists of several + // frames containing ads, those ad URLs will have this transition type. + // The user may not even realize the content in these pages is a separate + // frame, so may not care about the URL. + /// + TT_AUTO_SUBFRAME = 3, + + /// + // Source is a subframe navigation explicitly requested by the user that will + // generate new navigation entries in the back/forward list. These are + // probably more important than frames that were automatically loaded in + // the background because the user probably cares about the fact that this + // link was loaded. + /// + TT_MANUAL_SUBFRAME = 4, + + /// + // Source is a form submission by the user. NOTE: In some situations + // submitting a form does not result in this transition type. This can happen + // if the form uses a script to submit the contents. + /// + TT_FORM_SUBMIT = 7, + + /// + // Source is a "reload" of the page via the Reload function or by re-visiting + // the same URL. NOTE: This is distinct from the concept of whether a + // particular load uses "reload semantics" (i.e. bypasses cached data). + /// + TT_RELOAD = 8, + + /// + // General mask defining the bits used for the source values. + /// + TT_SOURCE_MASK = 0xFF, + + // Qualifiers. + // Any of the core values above can be augmented by one or more qualifiers. + // These qualifiers further define the transition. + + /// + // Attempted to visit a URL but was blocked. + /// + TT_BLOCKED_FLAG = 0x00800000, + + /// + // Used the Forward or Back function to navigate among browsing history. + /// + TT_FORWARD_BACK_FLAG = 0x01000000, + + /// + // The beginning of a navigation chain. + /// + TT_CHAIN_START_FLAG = 0x10000000, + + /// + // The last transition in a redirect chain. + /// + TT_CHAIN_END_FLAG = 0x20000000, + + /// + // Redirects caused by JavaScript or a meta refresh tag on the page. + /// + TT_CLIENT_REDIRECT_FLAG = 0x40000000, + + /// + // Redirects sent from the server by HTTP headers. + /// + TT_SERVER_REDIRECT_FLAG = 0x80000000, + + /// + // Used to test whether a transition involves a redirect. + /// + TT_IS_REDIRECT_MASK = 0xC0000000, + + /// + // General mask defining the bits used for the qualifiers. + /// + TT_QUALIFIER_MASK = 0xFFFFFF00, +} cef_transition_type_t; + +/// +// Flags used to customize the behavior of CefURLRequest. +/// +typedef enum { + /// + // Default behavior. + /// + UR_FLAG_NONE = 0, + + /// + // If set the cache will be skipped when handling the request. + /// + UR_FLAG_SKIP_CACHE = 1 << 0, + + /// + // If set user name, password, and cookies may be sent with the request, and + // cookies may be saved from the response. + /// + UR_FLAG_ALLOW_CACHED_CREDENTIALS = 1 << 1, + + /// + // If set upload progress events will be generated when a request has a body. + /// + UR_FLAG_REPORT_UPLOAD_PROGRESS = 1 << 3, + + /// + // If set the headers sent and received for the request will be recorded. + /// + UR_FLAG_REPORT_RAW_HEADERS = 1 << 5, + + /// + // If set the CefURLRequestClient::OnDownloadData method will not be called. + /// + UR_FLAG_NO_DOWNLOAD_DATA = 1 << 6, + + /// + // If set 5XX redirect errors will be propagated to the observer instead of + // automatically re-tried. This currently only applies for requests + // originated in the browser process. + /// + UR_FLAG_NO_RETRY_ON_5XX = 1 << 7, +} cef_urlrequest_flags_t; + +/// +// Flags that represent CefURLRequest status. +/// +typedef enum { + /// + // Unknown status. + /// + UR_UNKNOWN = 0, + + /// + // Request succeeded. + /// + UR_SUCCESS, + + /// + // An IO request is pending, and the caller will be informed when it is + // completed. + /// + UR_IO_PENDING, + + /// + // Request was canceled programatically. + /// + UR_CANCELED, + + /// + // Request failed for some reason. + /// + UR_FAILED, +} cef_urlrequest_status_t; + +/// +// Structure representing a point. +/// +typedef struct _cef_point_t { + int x; + int y; +} cef_point_t; + +/// +// Structure representing a rectangle. +/// +typedef struct _cef_rect_t { + int x; + int y; + int width; + int height; +} cef_rect_t; + +/// +// Structure representing a size. +/// +typedef struct _cef_size_t { + int width; + int height; +} cef_size_t; + +/// +// Existing process IDs. +/// +typedef enum { + /// + // Browser process. + /// + PID_BROWSER, + /// + // Renderer process. + /// + PID_RENDERER, +} cef_process_id_t; + +/// +// Existing thread IDs. +/// +typedef enum { +// BROWSER PROCESS THREADS -- Only available in the browser process. + + /// + // The main thread in the browser. This will be the same as the main + // application thread if CefInitialize() is called with a + // CefSettings.multi_threaded_message_loop value of false. + /// + TID_UI, + + /// + // Used to interact with the database. + /// + TID_DB, + + /// + // Used to interact with the file system. + /// + TID_FILE, + + /// + // Used for file system operations that block user interactions. + // Responsiveness of this thread affects users. + /// + TID_FILE_USER_BLOCKING, + + /// + // Used to launch and terminate browser processes. + /// + TID_PROCESS_LAUNCHER, + + /// + // Used to handle slow HTTP cache operations. + /// + TID_CACHE, + + /// + // Used to process IPC and network messages. + /// + TID_IO, + +// RENDER PROCESS THREADS -- Only available in the render process. + + /// + // The main thread in the renderer. Used for all WebKit and V8 interaction. + /// + TID_RENDERER, +} cef_thread_id_t; + +/// +// Supported value types. +/// +typedef enum { + VTYPE_INVALID = 0, + VTYPE_NULL, + VTYPE_BOOL, + VTYPE_INT, + VTYPE_DOUBLE, + VTYPE_STRING, + VTYPE_BINARY, + VTYPE_DICTIONARY, + VTYPE_LIST, +} cef_value_type_t; + +/// +// Supported JavaScript dialog types. +/// +typedef enum { + JSDIALOGTYPE_ALERT = 0, + JSDIALOGTYPE_CONFIRM, + JSDIALOGTYPE_PROMPT, +} cef_jsdialog_type_t; + +/// +// Screen information used when window rendering is disabled. This structure is +// passed as a parameter to CefRenderHandler::GetScreenInfo and should be filled +// in by the client. +/// +typedef struct _cef_screen_info_t { + /// + // Device scale factor. Specifies the ratio between physical and logical + // pixels. + /// + float device_scale_factor; + + /// + // The screen depth in bits per pixel. + /// + int depth; + + /// + // The bits per color component. This assumes that the colors are balanced + // equally. + /// + int depth_per_component; + + /// + // This can be true for black and white printers. + /// + int is_monochrome; + + /// + // This is set from the rcMonitor member of MONITORINFOEX, to whit: + // "A RECT structure that specifies the display monitor rectangle, + // expressed in virtual-screen coordinates. Note that if the monitor + // is not the primary display monitor, some of the rectangle's + // coordinates may be negative values." + // + // The |rect| and |available_rect| properties are used to determine the + // available surface for rendering popup views. + /// + cef_rect_t rect; + + /// + // This is set from the rcWork member of MONITORINFOEX, to whit: + // "A RECT structure that specifies the work area rectangle of the + // display monitor that can be used by applications, expressed in + // virtual-screen coordinates. Windows uses this rectangle to + // maximize an application on the monitor. The rest of the area in + // rcMonitor contains system windows such as the task bar and side + // bars. Note that if the monitor is not the primary display monitor, + // some of the rectangle's coordinates may be negative values". + // + // The |rect| and |available_rect| properties are used to determine the + // available surface for rendering popup views. + /// + cef_rect_t available_rect; +} cef_screen_info_t; + +/// +// Supported menu IDs. Non-English translations can be provided for the +// IDS_MENU_* strings in CefResourceBundleHandler::GetLocalizedString(). +/// +typedef enum { + // Navigation. + MENU_ID_BACK = 100, + MENU_ID_FORWARD = 101, + MENU_ID_RELOAD = 102, + MENU_ID_RELOAD_NOCACHE = 103, + MENU_ID_STOPLOAD = 104, + + // Editing. + MENU_ID_UNDO = 110, + MENU_ID_REDO = 111, + MENU_ID_CUT = 112, + MENU_ID_COPY = 113, + MENU_ID_PASTE = 114, + MENU_ID_DELETE = 115, + MENU_ID_SELECT_ALL = 116, + + // Miscellaneous. + MENU_ID_FIND = 130, + MENU_ID_PRINT = 131, + MENU_ID_VIEW_SOURCE = 132, + + // Spell checking word correction suggestions. + MENU_ID_SPELLCHECK_SUGGESTION_0 = 200, + MENU_ID_SPELLCHECK_SUGGESTION_1 = 201, + MENU_ID_SPELLCHECK_SUGGESTION_2 = 202, + MENU_ID_SPELLCHECK_SUGGESTION_3 = 203, + MENU_ID_SPELLCHECK_SUGGESTION_4 = 204, + MENU_ID_SPELLCHECK_SUGGESTION_LAST = 204, + MENU_ID_NO_SPELLING_SUGGESTIONS = 205, + MENU_ID_ADD_TO_DICTIONARY = 206, + + // All user-defined menu IDs should come between MENU_ID_USER_FIRST and + // MENU_ID_USER_LAST to avoid overlapping the Chromium and CEF ID ranges + // defined in the tools/gritsettings/resource_ids file. + MENU_ID_USER_FIRST = 26500, + MENU_ID_USER_LAST = 28500, +} cef_menu_id_t; + +/// +// Mouse button types. +/// +typedef enum { + MBT_LEFT = 0, + MBT_MIDDLE, + MBT_RIGHT, +} cef_mouse_button_type_t; + +/// +// Structure representing mouse event information. +/// +typedef struct _cef_mouse_event_t { + /// + // X coordinate relative to the left side of the view. + /// + int x; + + /// + // Y coordinate relative to the top side of the view. + /// + int y; + + /// + // Bit flags describing any pressed modifier keys. See + // cef_event_flags_t for values. + /// + uint32 modifiers; +} cef_mouse_event_t; + +/// +// Paint element types. +/// +typedef enum { + PET_VIEW = 0, + PET_POPUP, +} cef_paint_element_type_t; + +/// +// Supported event bit flags. +/// +typedef enum { + EVENTFLAG_NONE = 0, + EVENTFLAG_CAPS_LOCK_ON = 1 << 0, + EVENTFLAG_SHIFT_DOWN = 1 << 1, + EVENTFLAG_CONTROL_DOWN = 1 << 2, + EVENTFLAG_ALT_DOWN = 1 << 3, + EVENTFLAG_LEFT_MOUSE_BUTTON = 1 << 4, + EVENTFLAG_MIDDLE_MOUSE_BUTTON = 1 << 5, + EVENTFLAG_RIGHT_MOUSE_BUTTON = 1 << 6, + // Mac OS-X command key. + EVENTFLAG_COMMAND_DOWN = 1 << 7, + EVENTFLAG_NUM_LOCK_ON = 1 << 8, + EVENTFLAG_IS_KEY_PAD = 1 << 9, + EVENTFLAG_IS_LEFT = 1 << 10, + EVENTFLAG_IS_RIGHT = 1 << 11, +} cef_event_flags_t; + +/// +// Supported menu item types. +/// +typedef enum { + MENUITEMTYPE_NONE, + MENUITEMTYPE_COMMAND, + MENUITEMTYPE_CHECK, + MENUITEMTYPE_RADIO, + MENUITEMTYPE_SEPARATOR, + MENUITEMTYPE_SUBMENU, +} cef_menu_item_type_t; + +/// +// Supported context menu type flags. +/// +typedef enum { + /// + // No node is selected. + /// + CM_TYPEFLAG_NONE = 0, + /// + // The top page is selected. + /// + CM_TYPEFLAG_PAGE = 1 << 0, + /// + // A subframe page is selected. + /// + CM_TYPEFLAG_FRAME = 1 << 1, + /// + // A link is selected. + /// + CM_TYPEFLAG_LINK = 1 << 2, + /// + // A media node is selected. + /// + CM_TYPEFLAG_MEDIA = 1 << 3, + /// + // There is a textual or mixed selection that is selected. + /// + CM_TYPEFLAG_SELECTION = 1 << 4, + /// + // An editable element is selected. + /// + CM_TYPEFLAG_EDITABLE = 1 << 5, +} cef_context_menu_type_flags_t; + +/// +// Supported context menu media types. +/// +typedef enum { + /// + // No special node is in context. + /// + CM_MEDIATYPE_NONE, + /// + // An image node is selected. + /// + CM_MEDIATYPE_IMAGE, + /// + // A video node is selected. + /// + CM_MEDIATYPE_VIDEO, + /// + // An audio node is selected. + /// + CM_MEDIATYPE_AUDIO, + /// + // A file node is selected. + /// + CM_MEDIATYPE_FILE, + /// + // A plugin node is selected. + /// + CM_MEDIATYPE_PLUGIN, +} cef_context_menu_media_type_t; + +/// +// Supported context menu media state bit flags. +/// +typedef enum { + CM_MEDIAFLAG_NONE = 0, + CM_MEDIAFLAG_ERROR = 1 << 0, + CM_MEDIAFLAG_PAUSED = 1 << 1, + CM_MEDIAFLAG_MUTED = 1 << 2, + CM_MEDIAFLAG_LOOP = 1 << 3, + CM_MEDIAFLAG_CAN_SAVE = 1 << 4, + CM_MEDIAFLAG_HAS_AUDIO = 1 << 5, + CM_MEDIAFLAG_HAS_VIDEO = 1 << 6, + CM_MEDIAFLAG_CONTROL_ROOT_ELEMENT = 1 << 7, + CM_MEDIAFLAG_CAN_PRINT = 1 << 8, + CM_MEDIAFLAG_CAN_ROTATE = 1 << 9, +} cef_context_menu_media_state_flags_t; + +/// +// Supported context menu edit state bit flags. +/// +typedef enum { + CM_EDITFLAG_NONE = 0, + CM_EDITFLAG_CAN_UNDO = 1 << 0, + CM_EDITFLAG_CAN_REDO = 1 << 1, + CM_EDITFLAG_CAN_CUT = 1 << 2, + CM_EDITFLAG_CAN_COPY = 1 << 3, + CM_EDITFLAG_CAN_PASTE = 1 << 4, + CM_EDITFLAG_CAN_DELETE = 1 << 5, + CM_EDITFLAG_CAN_SELECT_ALL = 1 << 6, + CM_EDITFLAG_CAN_TRANSLATE = 1 << 7, +} cef_context_menu_edit_state_flags_t; + +/// +// Key event types. +/// +typedef enum { + /// + // Notification that a key transitioned from "up" to "down". + /// + KEYEVENT_RAWKEYDOWN = 0, + + /// + // Notification that a key was pressed. This does not necessarily correspond + // to a character depending on the key and language. Use KEYEVENT_CHAR for + // character input. + /// + KEYEVENT_KEYDOWN, + + /// + // Notification that a key was released. + /// + KEYEVENT_KEYUP, + + /// + // Notification that a character was typed. Use this for text input. Key + // down events may generate 0, 1, or more than one character event depending + // on the key, locale, and operating system. + /// + KEYEVENT_CHAR +} cef_key_event_type_t; + +/// +// Structure representing keyboard event information. +/// +typedef struct _cef_key_event_t { + /// + // The type of keyboard event. + /// + cef_key_event_type_t type; + + /// + // Bit flags describing any pressed modifier keys. See + // cef_event_flags_t for values. + /// + uint32 modifiers; + + /// + // The Windows key code for the key event. This value is used by the DOM + // specification. Sometimes it comes directly from the event (i.e. on + // Windows) and sometimes it's determined using a mapping function. See + // WebCore/platform/chromium/KeyboardCodes.h for the list of values. + /// + int windows_key_code; + + /// + // The actual key code genenerated by the platform. + /// + int native_key_code; + + /// + // Indicates whether the event is considered a "system key" event (see + // http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx for details). + // This value will always be false on non-Windows platforms. + /// + int is_system_key; + + /// + // The character generated by the keystroke. + /// + char16 character; + + /// + // Same as |character| but unmodified by any concurrently-held modifiers + // (except shift). This is useful for working out shortcut keys. + /// + char16 unmodified_character; + + /// + // True if the focus is currently on an editable field on the page. This is + // useful for determining if standard key events should be intercepted. + /// + int focus_on_editable_field; +} cef_key_event_t; + +/// +// Focus sources. +/// +typedef enum { + /// + // The source is explicit navigation via the API (LoadURL(), etc). + /// + FOCUS_SOURCE_NAVIGATION = 0, + /// + // The source is a system-generated focus event. + /// + FOCUS_SOURCE_SYSTEM, +} cef_focus_source_t; + +/// +// Navigation types. +/// +typedef enum { + NAVIGATION_LINK_CLICKED = 0, + NAVIGATION_FORM_SUBMITTED, + NAVIGATION_BACK_FORWARD, + NAVIGATION_RELOAD, + NAVIGATION_FORM_RESUBMITTED, + NAVIGATION_OTHER, +} cef_navigation_type_t; + +/// +// Supported XML encoding types. The parser supports ASCII, ISO-8859-1, and +// UTF16 (LE and BE) by default. All other types must be translated to UTF8 +// before being passed to the parser. If a BOM is detected and the correct +// decoder is available then that decoder will be used automatically. +/// +typedef enum { + XML_ENCODING_NONE = 0, + XML_ENCODING_UTF8, + XML_ENCODING_UTF16LE, + XML_ENCODING_UTF16BE, + XML_ENCODING_ASCII, +} cef_xml_encoding_type_t; + +/// +// XML node types. +/// +typedef enum { + XML_NODE_UNSUPPORTED = 0, + XML_NODE_PROCESSING_INSTRUCTION, + XML_NODE_DOCUMENT_TYPE, + XML_NODE_ELEMENT_START, + XML_NODE_ELEMENT_END, + XML_NODE_ATTRIBUTE, + XML_NODE_TEXT, + XML_NODE_CDATA, + XML_NODE_ENTITY_REFERENCE, + XML_NODE_WHITESPACE, + XML_NODE_COMMENT, +} cef_xml_node_type_t; + +/// +// Popup window features. +/// +typedef struct _cef_popup_features_t { + int x; + int xSet; + int y; + int ySet; + int width; + int widthSet; + int height; + int heightSet; + + int menuBarVisible; + int statusBarVisible; + int toolBarVisible; + int locationBarVisible; + int scrollbarsVisible; + int resizable; + + int fullscreen; + int dialog; + cef_string_list_t additionalFeatures; +} cef_popup_features_t; + +/// +// DOM document types. +/// +typedef enum { + DOM_DOCUMENT_TYPE_UNKNOWN = 0, + DOM_DOCUMENT_TYPE_HTML, + DOM_DOCUMENT_TYPE_XHTML, + DOM_DOCUMENT_TYPE_PLUGIN, +} cef_dom_document_type_t; + +/// +// DOM event category flags. +/// +typedef enum { + DOM_EVENT_CATEGORY_UNKNOWN = 0x0, + DOM_EVENT_CATEGORY_UI = 0x1, + DOM_EVENT_CATEGORY_MOUSE = 0x2, + DOM_EVENT_CATEGORY_MUTATION = 0x4, + DOM_EVENT_CATEGORY_KEYBOARD = 0x8, + DOM_EVENT_CATEGORY_TEXT = 0x10, + DOM_EVENT_CATEGORY_COMPOSITION = 0x20, + DOM_EVENT_CATEGORY_DRAG = 0x40, + DOM_EVENT_CATEGORY_CLIPBOARD = 0x80, + DOM_EVENT_CATEGORY_MESSAGE = 0x100, + DOM_EVENT_CATEGORY_WHEEL = 0x200, + DOM_EVENT_CATEGORY_BEFORE_TEXT_INSERTED = 0x400, + DOM_EVENT_CATEGORY_OVERFLOW = 0x800, + DOM_EVENT_CATEGORY_PAGE_TRANSITION = 0x1000, + DOM_EVENT_CATEGORY_POPSTATE = 0x2000, + DOM_EVENT_CATEGORY_PROGRESS = 0x4000, + DOM_EVENT_CATEGORY_XMLHTTPREQUEST_PROGRESS = 0x8000, +} cef_dom_event_category_t; + +/// +// DOM event processing phases. +/// +typedef enum { + DOM_EVENT_PHASE_UNKNOWN = 0, + DOM_EVENT_PHASE_CAPTURING, + DOM_EVENT_PHASE_AT_TARGET, + DOM_EVENT_PHASE_BUBBLING, +} cef_dom_event_phase_t; + +/// +// DOM node types. +/// +typedef enum { + DOM_NODE_TYPE_UNSUPPORTED = 0, + DOM_NODE_TYPE_ELEMENT, + DOM_NODE_TYPE_ATTRIBUTE, + DOM_NODE_TYPE_TEXT, + DOM_NODE_TYPE_CDATA_SECTION, + DOM_NODE_TYPE_PROCESSING_INSTRUCTIONS, + DOM_NODE_TYPE_COMMENT, + DOM_NODE_TYPE_DOCUMENT, + DOM_NODE_TYPE_DOCUMENT_TYPE, + DOM_NODE_TYPE_DOCUMENT_FRAGMENT, +} cef_dom_node_type_t; + +/// +// Supported file dialog modes. +/// +typedef enum { + /// + // Requires that the file exists before allowing the user to pick it. + /// + FILE_DIALOG_OPEN = 0, + + /// + // Like Open, but allows picking multiple files to open. + /// + FILE_DIALOG_OPEN_MULTIPLE, + + /// + // Like Open, but selects a folder to open. + /// + FILE_DIALOG_OPEN_FOLDER, + + /// + // Allows picking a nonexistent file, and prompts to overwrite if the file + // already exists. + /// + FILE_DIALOG_SAVE, + + /// + // General mask defining the bits used for the type values. + /// + FILE_DIALOG_TYPE_MASK = 0xFF, + + // Qualifiers. + // Any of the type values above can be augmented by one or more qualifiers. + // These qualifiers further define the dialog behavior. + + /// + // Prompt to overwrite if the user selects an existing file with the Save + // dialog. + /// + FILE_DIALOG_OVERWRITEPROMPT_FLAG = 0x01000000, + + /// + // Do not display read-only files. + /// + FILE_DIALOG_HIDEREADONLY_FLAG = 0x02000000, +} cef_file_dialog_mode_t; + +/// +// Geoposition error codes. +/// +typedef enum { + GEOPOSITON_ERROR_NONE = 0, + GEOPOSITON_ERROR_PERMISSION_DENIED, + GEOPOSITON_ERROR_POSITION_UNAVAILABLE, + GEOPOSITON_ERROR_TIMEOUT, +} cef_geoposition_error_code_t; + +/// +// Structure representing geoposition information. The properties of this +// structure correspond to those of the JavaScript Position object although +// their types may differ. +/// +typedef struct _cef_geoposition_t { + /// + // Latitude in decimal degrees north (WGS84 coordinate frame). + /// + double latitude; + + /// + // Longitude in decimal degrees west (WGS84 coordinate frame). + /// + double longitude; + + /// + // Altitude in meters (above WGS84 datum). + /// + double altitude; + + /// + // Accuracy of horizontal position in meters. + /// + double accuracy; + + /// + // Accuracy of altitude in meters. + /// + double altitude_accuracy; + + /// + // Heading in decimal degrees clockwise from true north. + /// + double heading; + + /// + // Horizontal component of device velocity in meters per second. + /// + double speed; + + /// + // Time of position measurement in milliseconds since Epoch in UTC time. This + // is taken from the host computer's system clock. + /// + cef_time_t timestamp; + + /// + // Error code, see enum above. + /// + cef_geoposition_error_code_t error_code; + + /// + // Human-readable error message. + /// + cef_string_t error_message; +} cef_geoposition_t; + +/// +// Print job color mode values. +/// +typedef enum { + COLOR_MODEL_UNKNOWN, + COLOR_MODEL_GRAY, + COLOR_MODEL_COLOR, + COLOR_MODEL_CMYK, + COLOR_MODEL_CMY, + COLOR_MODEL_KCMY, + COLOR_MODEL_CMY_K, // CMY_K represents CMY+K. + COLOR_MODEL_BLACK, + COLOR_MODEL_GRAYSCALE, + COLOR_MODEL_RGB, + COLOR_MODEL_RGB16, + COLOR_MODEL_RGBA, + COLOR_MODEL_COLORMODE_COLOR, // Used in samsung printer ppds. + COLOR_MODEL_COLORMODE_MONOCHROME, // Used in samsung printer ppds. + COLOR_MODEL_HP_COLOR_COLOR, // Used in HP color printer ppds. + COLOR_MODEL_HP_COLOR_BLACK, // Used in HP color printer ppds. + COLOR_MODEL_PRINTOUTMODE_NORMAL, // Used in foomatic ppds. + COLOR_MODEL_PRINTOUTMODE_NORMAL_GRAY, // Used in foomatic ppds. + COLOR_MODEL_PROCESSCOLORMODEL_CMYK, // Used in canon printer ppds. + COLOR_MODEL_PROCESSCOLORMODEL_GREYSCALE, // Used in canon printer ppds. + COLOR_MODEL_PROCESSCOLORMODEL_RGB, // Used in canon printer ppds +} cef_color_model_t; + +/// +// Print job duplex mode values. +/// +typedef enum { + DUPLEX_MODE_UNKNOWN = -1, + DUPLEX_MODE_SIMPLEX, + DUPLEX_MODE_LONG_EDGE, + DUPLEX_MODE_SHORT_EDGE, +} cef_duplex_mode_t; + +/// +// Structure representing a print job page range. +/// +typedef struct _cef_page_range_t { + int from; + int to; +} cef_page_range_t; + +/// +// Cursor type values. +/// +typedef enum { + CT_POINTER = 0, + CT_CROSS, + CT_HAND, + CT_IBEAM, + CT_WAIT, + CT_HELP, + CT_EASTRESIZE, + CT_NORTHRESIZE, + CT_NORTHEASTRESIZE, + CT_NORTHWESTRESIZE, + CT_SOUTHRESIZE, + CT_SOUTHEASTRESIZE, + CT_SOUTHWESTRESIZE, + CT_WESTRESIZE, + CT_NORTHSOUTHRESIZE, + CT_EASTWESTRESIZE, + CT_NORTHEASTSOUTHWESTRESIZE, + CT_NORTHWESTSOUTHEASTRESIZE, + CT_COLUMNRESIZE, + CT_ROWRESIZE, + CT_MIDDLEPANNING, + CT_EASTPANNING, + CT_NORTHPANNING, + CT_NORTHEASTPANNING, + CT_NORTHWESTPANNING, + CT_SOUTHPANNING, + CT_SOUTHEASTPANNING, + CT_SOUTHWESTPANNING, + CT_WESTPANNING, + CT_MOVE, + CT_VERTICALTEXT, + CT_CELL, + CT_CONTEXTMENU, + CT_ALIAS, + CT_PROGRESS, + CT_NODROP, + CT_COPY, + CT_NONE, + CT_NOTALLOWED, + CT_ZOOMIN, + CT_ZOOMOUT, + CT_GRAB, + CT_GRABBING, + CT_CUSTOM, +} cef_cursor_type_t; + +/// +// Structure representing cursor information. |buffer| will be +// |size.width|*|size.height|*4 bytes in size and represents a BGRA image with +// an upper-left origin. +/// +typedef struct _cef_cursor_info_t { + cef_point_t hotspot; + float image_scale_factor; + void* buffer; + cef_size_t size; +} cef_cursor_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_H_ diff --git a/include/internal/cef_types_linux.h b/include/internal/cef_types_linux.h new file mode 100644 index 000000000..3fb896dd0 --- /dev/null +++ b/include/internal/cef_types_linux.h @@ -0,0 +1,119 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TYPES_LINUX_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_LINUX_H_ +#pragma once + +#include "include/base/cef_build.h" + +#if defined(OS_LINUX) + +typedef union _XEvent XEvent; +typedef struct _XDisplay XDisplay; + +#include "include/internal/cef_export.h" +#include "include/internal/cef_string.h" + +// Handle types. +#define cef_cursor_handle_t unsigned long +#define cef_event_handle_t XEvent* +#define cef_window_handle_t unsigned long + +#define kNullCursorHandle 0 +#define kNullEventHandle NULL +#define kNullWindowHandle 0 + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Return the singleton X11 display shared with Chromium. The display is not +// thread-safe and must only be accessed on the browser process UI thread. +/// +CEF_EXPORT XDisplay* cef_get_xdisplay(); +#define cef_text_input_context_t void* + +/// +// Structure representing CefExecuteProcess arguments. +/// +typedef struct _cef_main_args_t { + int argc; + char** argv; +} cef_main_args_t; + +/// +// Class representing window information. +/// +typedef struct _cef_window_info_t { + unsigned int x; + unsigned int y; + unsigned int width; + unsigned int height; + + /// + // Pointer for the parent window. + /// + cef_window_handle_t parent_window; + + /// + // Set to true (1) to create the browser using windowless (off-screen) + // rendering. No window will be created for the browser and all rendering will + // occur via the CefRenderHandler interface. The |parent_window| value will be + // used to identify monitor info and to act as the parent window for dialogs, + // context menus, etc. If |parent_window| is not provided then the main screen + // monitor will be used and some functionality that requires a parent window + // may not function correctly. In order to create windowless browsers the + // CefSettings.windowless_rendering_enabled value must be set to true. + /// + int windowless_rendering_enabled; + + /// + // Set to true (1) to enable transparent painting in combination with + // windowless rendering. When this value is true a transparent background + // color will be used (RGBA=0x00000000). When this value is false the + // background will be white and opaque. + /// + int transparent_painting_enabled; + + /// + // Pointer for the new browser window. Only used with windowed rendering. + /// + cef_window_handle_t window; +} cef_window_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // OS_LINUX + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_LINUX_H_ diff --git a/include/internal/cef_types_mac.h b/include/internal/cef_types_mac.h new file mode 100644 index 000000000..9603fc60a --- /dev/null +++ b/include/internal/cef_types_mac.h @@ -0,0 +1,132 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_ +#pragma once + +#include "include/base/cef_build.h" + +#if defined(OS_MACOSX) +#include "include/internal/cef_string.h" + +// Handle types. +#ifdef __cplusplus +#ifdef __OBJC__ +@class NSCursor; +@class NSEvent; +@class NSView; +@class NSTextInputContext; +#else +class NSCursor; +class NSEvent; +struct NSView; +class NSTextInputContext; +#endif +#define cef_cursor_handle_t NSCursor* +#define cef_event_handle_t NSEvent* +#define cef_window_handle_t NSView* +#define cef_text_input_context_t NSTextInputContext* +#else +#define cef_cursor_handle_t void* +#define cef_event_handle_t void* +#define cef_window_handle_t void* +#define cef_text_input_context_t void* +#endif + +#define kNullCursorHandle NULL +#define kNullEventHandle NULL +#define kNullWindowHandle NULL + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Structure representing CefExecuteProcess arguments. +/// +typedef struct _cef_main_args_t { + int argc; + char** argv; +} cef_main_args_t; + +/// +// Class representing window information. +/// +typedef struct _cef_window_info_t { + cef_string_t window_name; + int x; + int y; + int width; + int height; + + /// + // Set to true (1) to create the view initially hidden. + /// + int hidden; + + /// + // NSView pointer for the parent view. + /// + cef_window_handle_t parent_view; + + /// + // Set to true (1) to create the browser using windowless (off-screen) + // rendering. No view will be created for the browser and all rendering will + // occur via the CefRenderHandler interface. The |parent_view| value will be + // used to identify monitor info and to act as the parent view for dialogs, + // context menus, etc. If |parent_view| is not provided then the main screen + // monitor will be used and some functionality that requires a parent view + // may not function correctly. In order to create windowless browsers the + // CefSettings.windowless_rendering_enabled value must be set to true. + /// + int windowless_rendering_enabled; + + /// + // Set to true (1) to enable transparent painting in combination with + // windowless rendering. When this value is true a transparent background + // color will be used (RGBA=0x00000000). When this value is false the + // background will be white and opaque. + /// + int transparent_painting_enabled; + + /// + // NSView pointer for the new browser view. Only used with windowed rendering. + /// + cef_window_handle_t view; +} cef_window_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // OS_MACOSX + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_ diff --git a/include/internal/cef_types_win.h b/include/internal/cef_types_win.h new file mode 100644 index 000000000..27bf6053b --- /dev/null +++ b/include/internal/cef_types_win.h @@ -0,0 +1,109 @@ +// Copyright (c) 2009 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TYPES_WIN_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_WIN_H_ +#pragma once + +#include "include/base/cef_build.h" + +#if defined(OS_WIN) +#include +#include "include/internal/cef_string.h" + +// Handle types. +#define cef_cursor_handle_t HCURSOR +#define cef_event_handle_t MSG* +#define cef_window_handle_t HWND +#define cef_text_input_context_t void* + +#define kNullCursorHandle NULL +#define kNullEventHandle NULL +#define kNullWindowHandle NULL + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Structure representing CefExecuteProcess arguments. +/// +typedef struct _cef_main_args_t { + HINSTANCE instance; +} cef_main_args_t; + +/// +// Structure representing window information. +/// +typedef struct _cef_window_info_t { + // Standard parameters required by CreateWindowEx() + DWORD ex_style; + cef_string_t window_name; + DWORD style; + int x; + int y; + int width; + int height; + cef_window_handle_t parent_window; + HMENU menu; + + /// + // Set to true (1) to create the browser using windowless (off-screen) + // rendering. No window will be created for the browser and all rendering will + // occur via the CefRenderHandler interface. The |parent_window| value will be + // used to identify monitor info and to act as the parent window for dialogs, + // context menus, etc. If |parent_window| is not provided then the main screen + // monitor will be used and some functionality that requires a parent window + // may not function correctly. In order to create windowless browsers the + // CefSettings.windowless_rendering_enabled value must be set to true. + /// + int windowless_rendering_enabled; + + /// + // Set to true (1) to enable transparent painting in combination with + // windowless rendering. When this value is true a transparent background + // color will be used (RGBA=0x00000000). When this value is false the + // background will be white and opaque. + /// + int transparent_painting_enabled; + + /// + // Handle for the new browser window. Only used with windowed rendering. + /// + cef_window_handle_t window; +} cef_window_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // OS_WIN + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_WIN_H_ diff --git a/include/internal/cef_types_wrappers.h b/include/internal/cef_types_wrappers.h new file mode 100644 index 000000000..9a4036d9c --- /dev/null +++ b/include/internal/cef_types_wrappers.h @@ -0,0 +1,780 @@ +// Copyright (c) 2013 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_TYPES_WRAPPERS_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_WRAPPERS_H_ +#pragma once + +#include "include/internal/cef_string.h" +#include "include/internal/cef_string_list.h" +#include "include/internal/cef_types.h" + +/// +// Template class that provides common functionality for CEF structure wrapping. +/// +template +class CefStructBase : public traits::struct_type { + public: + typedef typename traits::struct_type struct_type; + + CefStructBase() : attached_to_(NULL) { + Init(); + } + virtual ~CefStructBase() { + // Only clear this object's data if it isn't currently attached to a + // structure. + if (!attached_to_) + Clear(this); + } + + CefStructBase(const CefStructBase& r) { + Init(); + *this = r; + } + CefStructBase(const struct_type& r) { // NOLINT(runtime/explicit) + Init(); + *this = r; + } + + /// + // Clear this object's values. + /// + void Reset() { + Clear(this); + Init(); + } + + /// + // Attach to the source structure's existing values. DetachTo() can be called + // to insert the values back into the existing structure. + /// + void AttachTo(struct_type& source) { + // Only clear this object's data if it isn't currently attached to a + // structure. + if (!attached_to_) + Clear(this); + + // This object is now attached to the new structure. + attached_to_ = &source; + + // Transfer ownership of the values from the source structure. + memcpy(static_cast(this), &source, sizeof(struct_type)); + } + + /// + // Relinquish ownership of values to the target structure. + /// + void DetachTo(struct_type& target) { + if (attached_to_ != &target) { + // Clear the target structure's values only if we are not currently + // attached to that structure. + Clear(&target); + } + + // Transfer ownership of the values to the target structure. + memcpy(&target, static_cast(this), sizeof(struct_type)); + + // Remove the references from this object. + Init(); + } + + /// + // Set this object's values. If |copy| is true the source structure's values + // will be copied instead of referenced. + /// + void Set(const struct_type& source, bool copy) { + traits::set(&source, this, copy); + } + + CefStructBase& operator=(const CefStructBase& s) { + return operator=(static_cast(s)); + } + + CefStructBase& operator=(const struct_type& s) { + Set(s, true); + return *this; + } + + protected: + void Init() { + memset(static_cast(this), 0, sizeof(struct_type)); + attached_to_ = NULL; + traits::init(this); + } + + static void Clear(struct_type* s) { traits::clear(s); } + + struct_type* attached_to_; +}; + + +struct CefPointTraits { + typedef cef_point_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + *target = *src; + } +}; + +/// +// Class representing a point. +/// +class CefPoint : public CefStructBase { + public: + typedef CefStructBase parent; + + CefPoint() : parent() {} + CefPoint(const cef_point_t& r) : parent(r) {} // NOLINT(runtime/explicit) + CefPoint(const CefPoint& r) : parent(r) {} // NOLINT(runtime/explicit) + CefPoint(int x, int y) : parent() { + Set(x, y); + } + + bool IsEmpty() const { return x <= 0 && y <= 0; } + void Set(int x, int y) { + this->x = x, this->y = y; + } +}; + +inline bool operator==(const CefPoint& a, const CefPoint& b) { + return a.x == b.x && a.y == b.y; +} + +inline bool operator!=(const CefPoint& a, const CefPoint& b) { + return !(a == b); +} + + +struct CefRectTraits { + typedef cef_rect_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + *target = *src; + } +}; + +/// +// Class representing a rectangle. +/// +class CefRect : public CefStructBase { + public: + typedef CefStructBase parent; + + CefRect() : parent() {} + CefRect(const cef_rect_t& r) : parent(r) {} // NOLINT(runtime/explicit) + CefRect(const CefRect& r) : parent(r) {} // NOLINT(runtime/explicit) + CefRect(int x, int y, int width, int height) : parent() { + Set(x, y, width, height); + } + + bool IsEmpty() const { return width <= 0 || height <= 0; } + void Set(int x, int y, int width, int height) { + this->x = x, this->y = y, this->width = width, this->height = height; + } +}; + +inline bool operator==(const CefRect& a, const CefRect& b) { + return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; +} + +inline bool operator!=(const CefRect& a, const CefRect& b) { + return !(a == b); +} + + +struct CefSizeTraits { + typedef cef_size_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + *target = *src; + } +}; + +/// +// Class representing a size. +/// +class CefSize : public CefStructBase { + public: + typedef CefStructBase parent; + + CefSize() : parent() {} + CefSize(const cef_size_t& r) : parent(r) {} // NOLINT(runtime/explicit) + CefSize(const CefSize& r) : parent(r) {} // NOLINT(runtime/explicit) + CefSize(int width, int height) : parent() { + Set(width, height); + } + + bool IsEmpty() const { return width <= 0 || height <= 0; } + void Set(int width, int height) { + this->width = width, this->height = height; + } +}; + +inline bool operator==(const CefSize& a, const CefSize& b) { + return a.width == b.width && a.height == b.height; +} + +inline bool operator!=(const CefSize& a, const CefSize& b) { + return !(a == b); +} + + +struct CefScreenInfoTraits { + typedef cef_screen_info_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->device_scale_factor = src->device_scale_factor; + target->depth = src->depth; + target->depth_per_component = src->depth_per_component; + target->is_monochrome = src->is_monochrome; + target->rect = src->rect; + target->available_rect = src->available_rect; + } +}; + +/// +// Class representing the virtual screen information for use when window rendering +// is disabled. +/// +class CefScreenInfo : public CefStructBase { + public: + typedef CefStructBase parent; + + CefScreenInfo() : parent() {} + CefScreenInfo(const cef_screen_info_t& r) : parent(r) {} // NOLINT(runtime/explicit) + CefScreenInfo(const CefScreenInfo& r) : parent(r) {} // NOLINT(runtime/explicit) + CefScreenInfo(float device_scale_factor, + int depth, + int depth_per_component, + bool is_monochrome, + const CefRect& rect, + const CefRect& available_rect) : parent() { + Set(device_scale_factor, depth, depth_per_component, + is_monochrome, rect, available_rect); + } + + void Set(float device_scale_factor, + int depth, + int depth_per_component, + bool is_monochrome, + const CefRect& rect, + const CefRect& available_rect) { + this->device_scale_factor = device_scale_factor; + this->depth = depth; + this->depth_per_component = depth_per_component; + this->is_monochrome = is_monochrome; + this->rect = rect; + this->available_rect = available_rect; + } +}; + + +struct CefKeyEventTraits { + typedef cef_key_event_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->type = src->type; + target->modifiers = src->modifiers; + target->windows_key_code = src->windows_key_code; + target->native_key_code = src->native_key_code; + target->is_system_key = src->is_system_key; + target->character = src->character; + target->unmodified_character = src->unmodified_character; + target->focus_on_editable_field = src->focus_on_editable_field; + } +}; + +/// +// Class representing a a keyboard event. +/// +typedef CefStructBase CefKeyEvent; + + +struct CefMouseEventTraits { + typedef cef_mouse_event_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->x = src->x; + target->y = src->y; + target->modifiers = src->modifiers; + } +}; + +/// +// Class representing a mouse event. +/// +typedef CefStructBase CefMouseEvent; + + +struct CefPopupFeaturesTraits { + typedef cef_popup_features_t struct_type; + + static inline void init(struct_type* s) { + s->menuBarVisible = true; + s->statusBarVisible = true; + s->toolBarVisible = true; + s->locationBarVisible = true; + s->scrollbarsVisible = true; + s->resizable = true; + } + + static inline void clear(struct_type* s) { + if (s->additionalFeatures) + cef_string_list_free(s->additionalFeatures); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + if (target->additionalFeatures) + cef_string_list_free(target->additionalFeatures); + target->additionalFeatures = src->additionalFeatures ? + cef_string_list_copy(src->additionalFeatures) : NULL; + + target->x = src->x; + target->xSet = src->xSet; + target->y = src->y; + target->ySet = src->ySet; + target->width = src->width; + target->widthSet = src->widthSet; + target->height = src->height; + target->heightSet = src->heightSet; + target->menuBarVisible = src->menuBarVisible; + target->statusBarVisible = src->statusBarVisible; + target->toolBarVisible = src->toolBarVisible; + target->locationBarVisible = src->locationBarVisible; + target->scrollbarsVisible = src->scrollbarsVisible; + target->resizable = src->resizable; + target->fullscreen = src->fullscreen; + target->dialog = src->dialog; + } +}; + +/// +// Class representing popup window features. +/// +typedef CefStructBase CefPopupFeatures; + + +struct CefSettingsTraits { + typedef cef_settings_t struct_type; + + static inline void init(struct_type* s) { + s->size = sizeof(struct_type); + } + + static inline void clear(struct_type* s) { + cef_string_clear(&s->browser_subprocess_path); + cef_string_clear(&s->cache_path); + cef_string_clear(&s->user_agent); + cef_string_clear(&s->product_version); + cef_string_clear(&s->locale); + cef_string_clear(&s->log_file); + cef_string_clear(&s->javascript_flags); + cef_string_clear(&s->resources_dir_path); + cef_string_clear(&s->locales_dir_path); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->single_process = src->single_process; + target->no_sandbox = src->no_sandbox; + cef_string_set(src->browser_subprocess_path.str, + src->browser_subprocess_path.length, + &target->browser_subprocess_path, copy); + target->multi_threaded_message_loop = src->multi_threaded_message_loop; + target->windowless_rendering_enabled = src->windowless_rendering_enabled; + target->command_line_args_disabled = src->command_line_args_disabled; + + cef_string_set(src->cache_path.str, src->cache_path.length, + &target->cache_path, copy); + target->persist_session_cookies = src->persist_session_cookies; + + cef_string_set(src->user_agent.str, src->user_agent.length, + &target->user_agent, copy); + cef_string_set(src->product_version.str, src->product_version.length, + &target->product_version, copy); + cef_string_set(src->locale.str, src->locale.length, &target->locale, copy); + + cef_string_set(src->log_file.str, src->log_file.length, &target->log_file, + copy); + target->log_severity = src->log_severity; + cef_string_set(src->javascript_flags.str, src->javascript_flags.length, + &target->javascript_flags, copy); + + cef_string_set(src->resources_dir_path.str, src->resources_dir_path.length, + &target->resources_dir_path, copy); + cef_string_set(src->locales_dir_path.str, src->locales_dir_path.length, + &target->locales_dir_path, copy); + target->pack_loading_disabled = src->pack_loading_disabled; + target->remote_debugging_port = src->remote_debugging_port; + target->uncaught_exception_stack_size = src->uncaught_exception_stack_size; + target->context_safety_implementation = src->context_safety_implementation; + target->ignore_certificate_errors = src->ignore_certificate_errors; + target->background_color = src->background_color; + } +}; + +/// +// Class representing initialization settings. +/// +typedef CefStructBase CefSettings; + + +struct CefBrowserSettingsTraits { + typedef cef_browser_settings_t struct_type; + + static inline void init(struct_type* s) { + s->size = sizeof(struct_type); + } + + static inline void clear(struct_type* s) { + cef_string_clear(&s->standard_font_family); + cef_string_clear(&s->fixed_font_family); + cef_string_clear(&s->serif_font_family); + cef_string_clear(&s->sans_serif_font_family); + cef_string_clear(&s->cursive_font_family); + cef_string_clear(&s->fantasy_font_family); + cef_string_clear(&s->default_encoding); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->windowless_frame_rate = src->windowless_frame_rate; + + cef_string_set(src->standard_font_family.str, + src->standard_font_family.length, &target->standard_font_family, copy); + cef_string_set(src->fixed_font_family.str, src->fixed_font_family.length, + &target->fixed_font_family, copy); + cef_string_set(src->serif_font_family.str, src->serif_font_family.length, + &target->serif_font_family, copy); + cef_string_set(src->sans_serif_font_family.str, + src->sans_serif_font_family.length, &target->sans_serif_font_family, + copy); + cef_string_set(src->cursive_font_family.str, + src->cursive_font_family.length, &target->cursive_font_family, copy); + cef_string_set(src->fantasy_font_family.str, + src->fantasy_font_family.length, &target->fantasy_font_family, copy); + + target->default_font_size = src->default_font_size; + target->default_fixed_font_size = src->default_fixed_font_size; + target->minimum_font_size = src->minimum_font_size; + target->minimum_logical_font_size = src->minimum_logical_font_size; + + cef_string_set(src->default_encoding.str, src->default_encoding.length, + &target->default_encoding, copy); + + target->remote_fonts = src->remote_fonts; + target->javascript = src->javascript; + target->javascript_open_windows = src->javascript_open_windows; + target->javascript_close_windows = src->javascript_close_windows; + target->javascript_access_clipboard = src->javascript_access_clipboard; + target->javascript_dom_paste = src->javascript_dom_paste; + target->caret_browsing = src->caret_browsing; + target->java = src->java; + target->plugins = src->plugins; + target->universal_access_from_file_urls = + src->universal_access_from_file_urls; + target->file_access_from_file_urls = src->file_access_from_file_urls; + target->web_security = src->web_security; + target->image_loading = src->image_loading; + target->image_shrink_standalone_to_fit = + src->image_shrink_standalone_to_fit; + target->text_area_resize = src->text_area_resize; + target->tab_to_links = src->tab_to_links; + target->local_storage = src->local_storage; + target->databases= src->databases; + target->application_cache = src->application_cache; + target->webgl = src->webgl; + + target->background_color = src->background_color; + } +}; + +/// +// Class representing browser initialization settings. +/// +typedef CefStructBase CefBrowserSettings; + + +struct CefURLPartsTraits { + typedef cef_urlparts_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->spec); + cef_string_clear(&s->scheme); + cef_string_clear(&s->username); + cef_string_clear(&s->password); + cef_string_clear(&s->host); + cef_string_clear(&s->port); + cef_string_clear(&s->origin); + cef_string_clear(&s->path); + cef_string_clear(&s->query); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + cef_string_set(src->spec.str, src->spec.length, &target->spec, copy); + cef_string_set(src->scheme.str, src->scheme.length, &target->scheme, copy); + cef_string_set(src->username.str, src->username.length, &target->username, + copy); + cef_string_set(src->password.str, src->password.length, &target->password, + copy); + cef_string_set(src->host.str, src->host.length, &target->host, copy); + cef_string_set(src->port.str, src->port.length, &target->port, copy); + cef_string_set(src->origin.str, src->origin.length, &target->origin, copy); + cef_string_set(src->path.str, src->path.length, &target->path, copy); + cef_string_set(src->query.str, src->query.length, &target->query, copy); + } +}; + +/// +// Class representing a URL's component parts. +/// +typedef CefStructBase CefURLParts; + + +struct CefTimeTraits { + typedef cef_time_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + *target = *src; + } +}; + +/// +// Class representing a time. +/// +class CefTime : public CefStructBase { + public: + typedef CefStructBase parent; + + CefTime() : parent() {} + CefTime(const cef_time_t& r) : parent(r) {} // NOLINT(runtime/explicit) + CefTime(const CefTime& r) : parent(r) {} // NOLINT(runtime/explicit) + explicit CefTime(time_t r) : parent() { SetTimeT(r); } + explicit CefTime(double r) : parent() { SetDoubleT(r); } + + // Converts to/from time_t. + void SetTimeT(time_t r) { + cef_time_from_timet(r, this); + } + time_t GetTimeT() const { + time_t time = 0; + cef_time_to_timet(this, &time); + return time; + } + + // Converts to/from a double which is the number of seconds since epoch + // (Jan 1, 1970). Webkit uses this format to represent time. A value of 0 + // means "not initialized". + void SetDoubleT(double r) { + cef_time_from_doublet(r, this); + } + double GetDoubleT() const { + double time = 0; + cef_time_to_doublet(this, &time); + return time; + } + + // Set this object to now. + void Now() { + cef_time_now(this); + } + + // Return the delta between this object and |other| in milliseconds. + long long Delta(const CefTime& other) { + long long delta = 0; + cef_time_delta(this, &other, &delta); + return delta; + } +}; + + +struct CefCookieTraits { + typedef cef_cookie_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->name); + cef_string_clear(&s->value); + cef_string_clear(&s->domain); + cef_string_clear(&s->path); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + cef_string_set(src->name.str, src->name.length, &target->name, copy); + cef_string_set(src->value.str, src->value.length, &target->value, copy); + cef_string_set(src->domain.str, src->domain.length, &target->domain, copy); + cef_string_set(src->path.str, src->path.length, &target->path, copy); + target->secure = src->secure; + target->httponly = src->httponly; + target->creation = src->creation; + target->last_access = src->last_access; + target->has_expires = src->has_expires; + target->expires = src->expires; + } +}; + +/// +// Class representing a cookie. +/// +typedef CefStructBase CefCookie; + + +struct CefGeopositionTraits { + typedef cef_geoposition_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->error_message); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->latitude = src->latitude; + target->longitude = src->longitude; + target->altitude = src->altitude; + target->accuracy = src->accuracy; + target->altitude_accuracy = src->altitude_accuracy; + target->heading = src->heading; + target->speed = src->speed; + target->timestamp = src->timestamp; + target->error_code = src->error_code; + cef_string_set(src->error_message.str, src->error_message.length, + &target->error_message, copy); + } +}; + +/// +// Class representing a geoposition. +/// +typedef CefStructBase CefGeoposition; + + +struct CefPageRangeTraits { + typedef cef_page_range_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + *target = *src; + } +}; + +/// +// Class representing a print job page range. +/// +class CefPageRange : public CefStructBase { + public: + typedef CefStructBase parent; + + CefPageRange() : parent() {} + CefPageRange(const cef_page_range_t& r) // NOLINT(runtime/explicit) + : parent(r) {} + CefPageRange(const CefPageRange& r) // NOLINT(runtime/explicit) + : parent(r) {} + CefPageRange(int from, int to) : parent() { + Set(from, to); + } + + void Set(int from, int to) { + this->from = from, this->to = to; + } +}; + +inline bool operator==(const CefPageRange& a, const CefPageRange& b) { + return a.from == b.from && a.to == b.to; +} + +inline bool operator!=(const CefPageRange& a, const CefPageRange& b) { + return !(a == b); +} + + +struct CefCursorInfoTraits { + typedef cef_cursor_info_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->hotspot = src->hotspot; + target->image_scale_factor = src->image_scale_factor; + target->buffer = src->buffer; + target->size = src->size; + } +}; + +/// +// Class representing cursor information. +/// +typedef CefStructBase CefCursorInfo; + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_WRAPPERS_H_ diff --git a/include/internal/cef_win.h b/include/internal/cef_win.h new file mode 100644 index 000000000..7361a3ce4 --- /dev/null +++ b/include/internal/cef_win.h @@ -0,0 +1,156 @@ +// Copyright (c) 2008 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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 CEF_INCLUDE_INTERNAL_CEF_WIN_H_ +#define CEF_INCLUDE_INTERNAL_CEF_WIN_H_ +#pragma once + +#include "include/internal/cef_types_win.h" +#include "include/internal/cef_types_wrappers.h" + +/// +// Handle types. +/// +#define CefCursorHandle cef_cursor_handle_t +#define CefEventHandle cef_event_handle_t +#define CefWindowHandle cef_window_handle_t +#define CefTextInputContext cef_text_input_context_t + +struct CefMainArgsTraits { + typedef cef_main_args_t struct_type; + + static inline void init(struct_type* s) {} + static inline void clear(struct_type* s) {} + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->instance = src->instance; + } +}; + +// Class representing CefExecuteProcess arguments. +class CefMainArgs : public CefStructBase { + public: + typedef CefStructBase parent; + + CefMainArgs() : parent() {} + explicit CefMainArgs(const cef_main_args_t& r) : parent(r) {} + explicit CefMainArgs(const CefMainArgs& r) : parent(r) {} + explicit CefMainArgs(HINSTANCE hInstance) : parent() { + instance = hInstance; + } +}; + +struct CefWindowInfoTraits { + typedef cef_window_info_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->window_name); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->ex_style = src->ex_style; + cef_string_set(src->window_name.str, src->window_name.length, + &target->window_name, copy); + target->style = src->style; + target->x = src->x; + target->y = src->y; + target->width = src->width; + target->height = src->height; + target->parent_window = src->parent_window; + target->menu = src->menu; + target->transparent_painting_enabled = src->transparent_painting_enabled; + target->windowless_rendering_enabled = src->windowless_rendering_enabled; + target->window = src->window; + } +}; + +/// +// Class representing window information. +/// +class CefWindowInfo : public CefStructBase { + public: + typedef CefStructBase parent; + + CefWindowInfo() : parent() {} + explicit CefWindowInfo(const cef_window_info_t& r) : parent(r) {} + explicit CefWindowInfo(const CefWindowInfo& r) : parent(r) {} + + /// + // Create the browser as a child window. + /// + void SetAsChild(CefWindowHandle parent, RECT windowRect) { + style = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_TABSTOP | + WS_VISIBLE; + parent_window = parent; + x = windowRect.left; + y = windowRect.top; + width = windowRect.right - windowRect.left; + height = windowRect.bottom - windowRect.top; + } + + /// + // Create the browser as a popup window. + /// + void SetAsPopup(CefWindowHandle parent, const CefString& windowName) { + style = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | + WS_VISIBLE; + parent_window = parent; + x = CW_USEDEFAULT; + y = CW_USEDEFAULT; + width = CW_USEDEFAULT; + height = CW_USEDEFAULT; + + cef_string_copy(windowName.c_str(), windowName.length(), &window_name); + } + + /// + // Create the browser using windowless (off-screen) rendering. No window + // will be created for the browser and all rendering will occur via the + // CefRenderHandler interface. The |parent| value will be used to identify + // monitor info and to act as the parent window for dialogs, context menus, + // etc. If |parent| is not provided then the main screen monitor will be used + // and some functionality that requires a parent window may not function + // correctly. If |transparent| is true a transparent background color will be + // used (RGBA=0x00000000). If |transparent| is false the background will be + // white and opaque. In order to create windowless browsers the + // CefSettings.windowless_rendering_enabled value must be set to true. + /// + void SetAsWindowless(CefWindowHandle parent, bool transparent) { + windowless_rendering_enabled = TRUE; + parent_window = parent; + transparent_painting_enabled = transparent; + } +}; + +#endif // CEF_INCLUDE_INTERNAL_CEF_WIN_H_ diff --git a/include/wrapper/cef_byte_read_handler.h b/include/wrapper/cef_byte_read_handler.h new file mode 100644 index 000000000..559cdd818 --- /dev/null +++ b/include/wrapper/cef_byte_read_handler.h @@ -0,0 +1,79 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_BYTE_READ_HANDLER_H_ +#define CEF_INCLUDE_WRAPPER_CEF_BYTE_READ_HANDLER_H_ +#pragma once + +#include "include/base/cef_lock.h" +#include "include/base/cef_macros.h" +#include "include/cef_base.h" +#include "include/cef_stream.h" + +/// +// Thread safe implementation of the CefReadHandler class for reading an +// in-memory array of bytes. +/// +class CefByteReadHandler : public CefReadHandler { + public: + /// + // Create a new object for reading an array of bytes. An optional |source| + // reference can be kept to keep the underlying data source from being + // released while the reader exists. + /// + CefByteReadHandler(const unsigned char* bytes, + size_t size, + CefRefPtr source); + + // CefReadHandler methods. + virtual size_t Read(void* ptr, size_t size, size_t n) OVERRIDE; + virtual int Seek(int64 offset, int whence) OVERRIDE; + virtual int64 Tell() OVERRIDE; + virtual int Eof() OVERRIDE; + virtual bool MayBlock() OVERRIDE { return false; } + + private: + const unsigned char* bytes_; + int64 size_; + int64 offset_; + CefRefPtr source_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefByteReadHandler); + DISALLOW_COPY_AND_ASSIGN(CefByteReadHandler); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_BYTE_READ_HANDLER_H_ diff --git a/include/wrapper/cef_closure_task.h b/include/wrapper/cef_closure_task.h new file mode 100644 index 000000000..8828c6566 --- /dev/null +++ b/include/wrapper/cef_closure_task.h @@ -0,0 +1,101 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_CLOSURE_TASK_H_ +#define CEF_INCLUDE_WRAPPER_CEF_CLOSURE_TASK_H_ +#pragma once + +#include "include/base/cef_callback_forward.h" +#include "include/base/cef_macros.h" +#include "include/cef_task.h" + +/// +// Helpers for asynchronously executing a base::Closure (bound function or +// method) on a CEF thread. Creation of base::Closures can be facilitated using +// base::Bind. See include/base/cef_callback.h for complete usage instructions. +// +// TO use these helpers you should include this header and the header that +// defines base::Bind. +// +// #include "include/base/cef_bind.h" +// #include "include/wrapper/cef_closure_task.h" +// +// Example of executing a bound function: +// +// // Define a function. +// void MyFunc(int arg) { /* do something with |arg| on the UI thread */ } +// +// // Post a task that will execute MyFunc on the UI thread and pass an |arg| +// // value of 5. +// CefPostTask(TID_UI, base::Bind(&MyFunc, 5)); +// +// Example of executing a bound method: +// +// // Define a class. +// class MyClass : public CefBase { +// public: +// MyClass() {} +// void MyMethod(int arg) { /* do something with |arg| on the UI thread */ } +// private: +// IMPLEMENT_REFCOUNTING(MyClass); +// }; +// +// // Create an instance of MyClass. +// CefRefPtr instance = new MyClass(); +// +// // Post a task that will execute MyClass::MyMethod on the UI thread and pass +// // an |arg| value of 5. |instance| will be kept alive until after the task +// // completes. +// CefPostTask(TID_UI, base::Bind(&MyClass::MyMethod, instance, 5)); +/// + +/// +// Create a CefTask that wraps a base::Closure. Can be used in combination with +// CefTaskRunner. +/// +CefRefPtr CefCreateClosureTask(const base::Closure& closure); + +/// +// Post a Closure for execution on the specified thread. +/// +bool CefPostTask(CefThreadId threadId, const base::Closure& closure); + +/// +// Post a Closure for delayed execution on the specified thread. +/// +bool CefPostDelayedTask(CefThreadId threadId, const base::Closure& closure, + int64 delay_ms); + +#endif // CEF_INCLUDE_WRAPPER_CEF_CLOSURE_TASK_H_ diff --git a/include/wrapper/cef_helpers.h b/include/wrapper/cef_helpers.h new file mode 100644 index 000000000..3624c74db --- /dev/null +++ b/include/wrapper/cef_helpers.h @@ -0,0 +1,81 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_HELPERS_H_ +#define CEF_INCLUDE_WRAPPER_CEF_HELPERS_H_ +#pragma once + +#include +#include +#include + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_task.h" + +#define CEF_REQUIRE_UI_THREAD() DCHECK(CefCurrentlyOn(TID_UI)); +#define CEF_REQUIRE_IO_THREAD() DCHECK(CefCurrentlyOn(TID_IO)); +#define CEF_REQUIRE_FILE_THREAD() DCHECK(CefCurrentlyOn(TID_FILE)); +#define CEF_REQUIRE_RENDERER_THREAD() DCHECK(CefCurrentlyOn(TID_RENDERER)); + +/// +// Helper class to manage a scoped copy of |argv|. +/// +class CefScopedArgArray { + public: + CefScopedArgArray(int argc, char* argv[]) { + array_ = new char*[argc]; + for (int i = 0; i < argc; ++i) { + values_.push_back(argv[i]); + array_[i] = const_cast(values_[i].c_str()); + } + } + ~CefScopedArgArray() { + delete [] array_; + } + + char** array() const { return array_; } + + private: + char** array_; + + // Keep values in a vector separate from |array_| because various users may + // modify |array_| and we still want to clean up memory properly. + std::vector values_; + + DISALLOW_COPY_AND_ASSIGN(CefScopedArgArray); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_HELPERS_H_ diff --git a/include/wrapper/cef_message_router.h b/include/wrapper/cef_message_router.h new file mode 100644 index 000000000..2a6fcfe6f --- /dev/null +++ b/include/wrapper/cef_message_router.h @@ -0,0 +1,428 @@ +// Copyright (c) 2014 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_MESSAGE_ROUTER_H_ +#define CEF_INCLUDE_WRAPPER_CEF_MESSAGE_ROUTER_H_ +#pragma once + +#include "include/base/cef_ref_counted.h" +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_process_message.h" +#include "include/cef_v8.h" + +// The below classes implement support for routing aynchronous messages between +// JavaScript running in the renderer process and C++ running in the browser +// process. An application interacts with the router by passing it data from +// standard CEF C++ callbacks (OnBeforeBrowse, OnProcessMessageRecieved, +// OnContextCreated, etc). The renderer-side router supports generic JavaScript +// callback registration and execution while the browser-side router supports +// application-specific logic via one or more application-provided Handler +// instances. +// +// The renderer-side router implementation exposes a query function and a cancel +// function via the JavaScript 'window' object: +// +// // Create and send a new query. +// var request_id = window.cefQuery({ +// request: 'my_request', +// persistent: false, +// onSuccess: function(response) {}, +// onFailure: function(error_code, error_message) {} +// }); +// +// // Optionally cancel the query. +// window.cefQueryCancel(request_id); +// +// When |window.cefQuery| is executed the request is sent asynchronously to one +// or more C++ Handler objects registered in the browser process. Each C++ +// Handler can choose to either handle or ignore the query in the +// Handler::OnQuery callback. If a Handler chooses to handle the query then it +// should execute Callback::Success when a response is available or +// Callback::Failure if an error occurs. This will result in asynchronous +// execution of the associated JavaScript callback in the renderer process. Any +// queries unhandled by C++ code in the browser process will be automatically +// canceled and the associated JavaScript onFailure callback will be executed +// with an error code of -1. +// +// Queries can be either persistent or non-persistent. If the query is +// persistent than the callbacks will remain registered until one of the +// following conditions are met: +// +// A. The query is canceled in JavaScript using the |window.cefQueryCancel| +// function. +// B. The query is canceled in C++ code using the Callback::Failure function. +// C. The context associated with the query is released due to browser +// destruction, navigation or renderer process termination. +// +// If the query is non-persistent then the registration will be removed after +// the JavaScript callback is executed a single time. If a query is canceled for +// a reason other than Callback::Failure being executed then the associated +// Handler's OnQueryCanceled method will be called. +// +// Some possible usage patterns include: +// +// One-time Request. Use a non-persistent query to send a JavaScript request. +// The Handler evaluates the request and returns the response. The query is +// then discarded. +// +// Broadcast. Use a persistent query to register as a JavaScript broadcast +// receiver. The Handler keeps track of all registered Callbacks and executes +// them sequentially to deliver the broadcast message. +// +// Subscription. Use a persistent query to register as a JavaScript subscription +// receiver. The Handler initiates the subscription feed on the first request +// and delivers responses to all registered subscribers as they become +// available. The Handler cancels the subscription feed when there are no +// longer any registered JavaScript receivers. +// +// Message routing occurs on a per-browser and per-context basis. Consequently, +// additional application logic can be applied by restricting which browser or +// context instances are passed into the router. If you choose to use this +// approach do so cautiously. In order for the router to function correctly any +// browser or context instance passed into a single router callback must then +// be passed into all router callbacks. +// +// There is generally no need to have multiple renderer-side routers unless you +// wish to have multiple bindings with different JavaScript function names. It +// can be useful to have multiple browser-side routers with different client- +// provided Handler instances when implementing different behaviors on a per- +// browser basis. +// +// This implementation places no formatting restrictions on payload content. +// An application may choose to exchange anything from simple formatted +// strings to serialized XML or JSON data. +// +// +// EXAMPLE USAGE +// +// 1. Define the router configuration. You can optionally specify settings +// like the JavaScript function names. The configuration must be the same in +// both the browser and renderer processes. If using multiple routers in the +// same application make sure to specify unique function names for each +// router configuration. +// +// // Example config object showing the default values. +// CefMessageRouterConfig config; +// config.js_query_function = "cefQuery"; +// config.js_cancel_function = "cefQueryCancel"; +// +// 2. Create an instance of CefMessageRouterBrowserSide in the browser process. +// You might choose to make it a member of your CefClient implementation, +// for example. +// +// browser_side_router_ = CefMessageRouterBrowserSide::Create(config); +// +// 3. Register one or more Handlers. The Handler instances must either outlive +// the router or be removed from the router before they're deleted. +// +// browser_side_router_->AddHandler(my_handler); +// +// 4. Call all required CefMessageRouterBrowserSide methods from other callbacks +// in your CefClient implementation (OnBeforeClose, etc). See the +// CefMessageRouterBrowserSide class documentation for the complete list of +// methods. +// +// 5. Create an instance of CefMessageRouterRendererSide in the renderer process. +// You might choose to make it a member of your CefApp implementation, for +// example. +// +// renderer_side_router_ = CefMessageRouterRendererSide::Create(config); +// +// 6. Call all required CefMessageRouterRendererSide methods from other +// callbacks in your CefRenderProcessHandler implementation +// (OnContextCreated, etc). See the CefMessageRouterRendererSide class +// documentation for the complete list of methods. +// +// 7. Execute the query function from JavaScript code. +// +// window.cefQuery({request: 'my_request', +// persistent: false, +// onSuccess: function(response) { print(response); }, +// onFailure: function(error_code, error_message) {} }); +// +// 8. Handle the query in your Handler::OnQuery implementation and execute the +// appropriate callback either immediately or asynchronously. +// +// void MyHandler::OnQuery(int64 query_id, +// CefRefPtr browser, +// CefRefPtr frame, +// const CefString& request, +// bool persistent, +// CefRefPtr callback) { +// if (request == "my_request") { +// callback->Continue("my_response"); +// return true; +// } +// return false; // Not handled. +// } +// +// 9. Notice that the onSuccess callback is executed in JavaScript. + +/// +// Used to configure the query router. The same values must be passed to both +// CefMessageRouterBrowserSide and CefMessageRouterRendererSide. If using multiple +// router pairs make sure to choose values that do not conflict. +/// +struct CefMessageRouterConfig { + CefMessageRouterConfig(); + + // Name of the JavaScript function that will be added to the 'window' object + // for sending a query. The default value is "cefQuery". + CefString js_query_function; + + // Name of the JavaScript function that will be added to the 'window' object + // for canceling a pending query. The default value is "cefQueryCancel". + CefString js_cancel_function; +}; + +/// +// Implements the browser side of query routing. The methods of this class may +// be called on any browser process thread unless otherwise indicated. +/// +class CefMessageRouterBrowserSide : + public base::RefCountedThreadSafe { + public: + /// + // Callback associated with a single pending asynchronous query. Execute the + // Success or Failure method to send an asynchronous response to the + // associated JavaScript handler. It is a runtime error to destroy a Callback + // object associated with an uncanceled query without first executing one of + // the callback methods. The methods of this class may be called on any + // browser process thread. + /// + class Callback : public CefBase { + public: + /// + // Notify the associated JavaScript onSuccess callback that the query has + // completed successfully with the specified |response|. + /// + virtual void Success(const CefString& response) =0; + + /// + // Notify the associated JavaScript onFailure callback that the query has + // failed with the specified |error_code| and |error_message|. + /// + virtual void Failure(int error_code, const CefString& error_message) =0; + }; + + /// + // Implement this interface to handle queries. All methods will be executed on + // the browser process UI thread. + /// + class Handler { + public: + typedef CefMessageRouterBrowserSide::Callback Callback; + + /// + // Executed when a new query is received. |query_id| uniquely identifies the + // query for the life span of the router. Return true to handle the query + // or false to propagate the query to other registered handlers, if any. If + // no handlers return true from this method then the query will be + // automatically canceled with an error code of -1 delivered to the + // JavaScript onFailure callback. If this method returns true then a + // Callback method must be executed either in this method or asynchronously + // to complete the query. + /// + virtual bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) { + return false; + } + + /// + // Executed when a query has been canceled either explicitly using the + // JavaScript cancel function or implicitly due to browser destruction, + // navigation or renderer process termination. It will only be called for + // the single handler that returned true from OnQuery for the same + // |query_id|. No references to the associated Callback object should be + // kept after this method is called, nor should any Callback methods be + // executed. + /// + virtual void OnQueryCanceled(CefRefPtr browser, + CefRefPtr frame, + int64 query_id) {} + + virtual ~Handler() {} + }; + + /// + // Create a new router with the specified configuration. + /// + static CefRefPtr Create( + const CefMessageRouterConfig& config); + + /// + // Add a new query handler. If |first| is true it will be added as the first + // handler, otherwise it will be added as the last handler. Returns true if + // the handler is added successfully or false if the handler has already been + // added. Must be called on the browser process UI thread. The Handler object + // must either outlive the router or be removed before deletion. + /// + virtual bool AddHandler(Handler* handler, bool first) =0; + + /// + // Remove an existing query handler. Any pending queries associated with the + // handler will be canceled. Handler::OnQueryCanceled will be called and the + // associated JavaScript onFailure callback will be executed with an error + // code of -1. Returns true if the handler is removed successfully or false + // if the handler is not found. Must be called on the browser process UI + // thread. + /// + virtual bool RemoveHandler(Handler* handler) =0; + + /// + // Cancel all pending queries associated with either |browser| or |handler|. + // If both |browser| and |handler| are NULL all pending queries will be + // canceled. Handler::OnQueryCanceled will be called and the associated + // JavaScript onFailure callback will be executed in all cases with an error + // code of -1. + /// + virtual void CancelPending(CefRefPtr browser, + Handler* handler) =0; + + /// + // Returns the number of queries currently pending for the specified |browser| + // and/or |handler|. Either or both values may be empty. Must be called on the + // browser process UI thread. + /// + virtual int GetPendingCount(CefRefPtr browser, + Handler* handler) =0; + + + // The below methods should be called from other CEF handlers. They must be + // called exactly as documented for the router to function correctly. + + /// + // Call from CefLifeSpanHandler::OnBeforeClose. Any pending queries associated + // with |browser| will be canceled and Handler::OnQueryCanceled will be called. + // No JavaScript callbacks will be executed since this indicates destruction + // of the browser. + /// + virtual void OnBeforeClose(CefRefPtr browser) =0; + + /// + // Call from CefRequestHandler::OnRenderProcessTerminated. Any pending queries + // associated with |browser| will be canceled and Handler::OnQueryCanceled + // will be called. No JavaScript callbacks will be executed since this + // indicates destruction of the context. + /// + virtual void OnRenderProcessTerminated(CefRefPtr browser) =0; + + /// + // Call from CefRequestHandler::OnBeforeBrowse only if the navigation is + // allowed to proceed. If |frame| is the main frame then any pending queries + // associated with |browser| will be canceled and Handler::OnQueryCanceled + // will be called. No JavaScript callbacks will be executed since this + // indicates destruction of the context. + /// + virtual void OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame) =0; + + /// + // Call from CefClient::OnProcessMessageReceived. Returns true if the message + // is handled by this router or false otherwise. + /// + virtual bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) =0; + + protected: + // Protect against accidental deletion of this object. + friend class base::RefCountedThreadSafe; + virtual ~CefMessageRouterBrowserSide() {} +}; + +/// +// Implements the renderer side of query routing. The methods of this class must +// be called on the render process main thread. +/// +class CefMessageRouterRendererSide : + public base::RefCountedThreadSafe { + public: + /// + // Create a new router with the specified configuration. + /// + static CefRefPtr Create( + const CefMessageRouterConfig& config); + + /// + // Returns the number of queries currently pending for the specified |browser| + // and/or |context|. Either or both values may be empty. + /// + virtual int GetPendingCount(CefRefPtr browser, + CefRefPtr context) =0; + + + // The below methods should be called from other CEF handlers. They must be + // called exactly as documented for the router to function correctly. + + /// + // Call from CefRenderProcessHandler::OnContextCreated. Registers the + // JavaScripts functions with the new context. + /// + virtual void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) =0; + + /// + // Call from CefRenderProcessHandler::OnContextReleased. Any pending queries + // associated with the released context will be canceled and + // Handler::OnQueryCanceled will be called in the browser process. + /// + virtual void OnContextReleased(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) =0; + + /// + // Call from CefRenderProcessHandler::OnProcessMessageReceived. Returns true + // if the message is handled by this router or false otherwise. + /// + virtual bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) =0; + + protected: + // Protect against accidental deletion of this object. + friend class base::RefCountedThreadSafe; + virtual ~CefMessageRouterRendererSide() {} +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_MESSAGE_ROUTER_H_ diff --git a/include/wrapper/cef_stream_resource_handler.h b/include/wrapper/cef_stream_resource_handler.h new file mode 100644 index 000000000..6a9a69814 --- /dev/null +++ b/include/wrapper/cef_stream_resource_handler.h @@ -0,0 +1,104 @@ +// Copyright (c) 2012 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_STREAM_RESOURCE_HANDLER_H_ +#define CEF_INCLUDE_WRAPPER_CEF_STREAM_RESOURCE_HANDLER_H_ +#pragma once + +#include "include/base/cef_macros.h" +#include "include/base/cef_scoped_ptr.h" +#include "include/cef_base.h" +#include "include/cef_resource_handler.h" +#include "include/cef_response.h" + +class CefStreamReader; + +/// +// Implementation of the CefResourceHandler class for reading from a CefStream. +/// +class CefStreamResourceHandler : public CefResourceHandler { + public: + /// + // Create a new object with default response values. + /// + CefStreamResourceHandler(const CefString& mime_type, + CefRefPtr stream); + /// + // Create a new object with explicit response values. + /// + CefStreamResourceHandler(int status_code, + const CefString& status_text, + const CefString& mime_type, + CefResponse::HeaderMap header_map, + CefRefPtr stream); + + virtual ~CefStreamResourceHandler(); + + // CefResourceHandler methods. + 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; + + private: + void ReadOnFileThread(int bytes_to_read, + CefRefPtr callback); + + const int status_code_; + const CefString status_text_; + const CefString mime_type_; + const CefResponse::HeaderMap header_map_; + const CefRefPtr stream_; + bool read_on_file_thread_; + + class Buffer; + scoped_ptr buffer_; +#ifndef NDEBUG + // Used in debug builds to verify that |buffer_| isn't being accessed on + // multiple threads at the same time. + bool buffer_owned_by_file_thread_; +#endif + + IMPLEMENT_REFCOUNTING(CefStreamResourceHandler); + DISALLOW_COPY_AND_ASSIGN(CefStreamResourceHandler); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_STREAM_RESOURCE_HANDLER_H_ diff --git a/include/wrapper/cef_xml_object.h b/include/wrapper/cef_xml_object.h new file mode 100644 index 000000000..bf1755432 --- /dev/null +++ b/include/wrapper/cef_xml_object.h @@ -0,0 +1,196 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_XML_OBJECT_H_ +#define CEF_INCLUDE_WRAPPER_CEF_XML_OBJECT_H_ +#pragma once + +#include +#include + +#include "include/base/cef_lock.h" +#include "include/base/cef_macros.h" +#include "include/base/cef_ref_counted.h" +#include "include/cef_base.h" +#include "include/cef_xml_reader.h" + +class CefStreamReader; + +/// +// Thread safe class for representing XML data as a structured object. This +// class should not be used with large XML documents because all data will be +// resident in memory at the same time. This implementation supports a +// restricted set of XML features: +//
+// (1) Processing instructions, whitespace and comments are ignored.
+// (2) Elements and attributes must always be referenced using the fully
+//     qualified name (ie, namespace:localname).
+// (3) Empty elements () and elements with zero-length values ()
+//     are considered the same.
+// (4) Element nodes are considered part of a value if:
+//     (a) The element node follows a non-element node at the same depth
+//         (see 5), or
+//     (b) The element node does not have a namespace and the parent node does.
+// (5) Mixed node types at the same depth are combined into a single element
+//     value as follows:
+//     (a) All node values are concatenated to form a single string value.
+//     (b) Entity reference nodes are resolved to the corresponding entity
+//         value.
+//     (c) Element nodes are represented by their outer XML string.
+// 
+/// +class CefXmlObject : public base::RefCountedThreadSafe { + public: + typedef std::vector > ObjectVector; + typedef std::map AttributeMap; + + /// + // Create a new object with the specified name. An object name must always be + // at least one character long. + /// + explicit CefXmlObject(const CefString& name); + + /// + // Load the contents of the specified XML stream into this object. The + // existing children and attributes, if any, will first be cleared. + /// + bool Load(CefRefPtr stream, + CefXmlReader::EncodingType encodingType, + const CefString& URI, CefString* loadError); + + /// + // Set the name, children and attributes of this object to a duplicate of the + // specified object's contents. The existing children and attributes, if any, + // will first be cleared. + /// + void Set(CefRefPtr object); + + /// + // Append a duplicate of the children and attributes of the specified object + // to this object. If |overwriteAttributes| is true then any attributes in + // this object that also exist in the specified object will be overwritten + // with the new values. The name of this object is not changed. + /// + void Append(CefRefPtr object, bool overwriteAttributes); + + /// + // Return a new object with the same name, children and attributes as this + // object. The parent of the new object will be NULL. + /// + CefRefPtr Duplicate(); + + /// + // Clears this object's children and attributes. The name and parenting of + // this object are not changed. + /// + void Clear(); + + /// + // Access the object's name. An object name must always be at least one + // character long. + /// + CefString GetName(); + bool SetName(const CefString& name); + + /// + // Access the object's parent. The parent can be NULL if this object has not + // been added as the child on another object. + /// + bool HasParent(); + CefRefPtr GetParent(); + + /// + // Access the object's value. An object cannot have a value if it also has + // children. Attempting to set the value while children exist will fail. + /// + bool HasValue(); + CefString GetValue(); + bool SetValue(const CefString& value); + + /// + // Access the object's attributes. Attributes must have unique names. + /// + bool HasAttributes(); + size_t GetAttributeCount(); + bool HasAttribute(const CefString& name); + CefString GetAttributeValue(const CefString& name); + bool SetAttributeValue(const CefString& name, const CefString& value); + size_t GetAttributes(AttributeMap& attributes); + void ClearAttributes(); + + /// + // Access the object's children. Each object can only have one parent so + // attempting to add an object that already has a parent will fail. Removing a + // child will set the child's parent to NULL. Adding a child will set the + // child's parent to this object. This object's value, if any, will be cleared + // if a child is added. + /// + bool HasChildren(); + size_t GetChildCount(); + bool HasChild(CefRefPtr child); + bool AddChild(CefRefPtr child); + bool RemoveChild(CefRefPtr child); + size_t GetChildren(ObjectVector& children); + void ClearChildren(); + + /// + // Find the first child with the specified name. + /// + CefRefPtr FindChild(const CefString& name); + + /// + // Find all children with the specified name. + /// + size_t FindChildren(const CefString& name, ObjectVector& children); + + private: + // Protect against accidental deletion of this object. + friend class base::RefCountedThreadSafe; + ~CefXmlObject(); + + void SetParent(CefXmlObject* parent); + + CefString name_; + CefXmlObject* parent_; + CefString value_; + AttributeMap attributes_; + ObjectVector children_; + + base::Lock lock_; + + DISALLOW_COPY_AND_ASSIGN(CefXmlObject); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_XML_OBJECT_H_ diff --git a/include/wrapper/cef_zip_archive.h b/include/wrapper/cef_zip_archive.h new file mode 100644 index 000000000..7ad10bda8 --- /dev/null +++ b/include/wrapper/cef_zip_archive.h @@ -0,0 +1,143 @@ +// Copyright (c) 2011 Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// The contents of this file are only available to applications that link +// against the libcef_dll_wrapper target. +// + +#ifndef CEF_INCLUDE_WRAPPER_CEF_ZIP_ARCHIVE_H_ +#define CEF_INCLUDE_WRAPPER_CEF_ZIP_ARCHIVE_H_ +#pragma once + +#include + +#include "include/base/cef_lock.h" +#include "include/base/cef_macros.h" +#include "include/base/cef_ref_counted.h" +#include "include/cef_base.h" + +class CefStreamReader; + +/// +// Thread-safe class for accessing zip archive file contents. This class should +// not be used with large archive files because all data will be resident in +// memory at the same time. This implementation supports a restricted set of zip +// archive features: +// (1) All file names are stored and compared in lower case. +// (2) File ordering from the original zip archive is not maintained. This +// means that files from the same folder may not be located together in the +// file content map. +/// +class CefZipArchive : public base::RefCountedThreadSafe { + public: + /// + // Class representing a file in the archive. Accessing the file data from + // multiple threads is safe provided a reference to the File object is kept. + /// + class File : public CefBase { + public: + /// + // Returns the read-only data contained in the file. + /// + virtual const unsigned char* GetData() const =0; + + /// + // Returns the size of the data in the file. + /// + virtual size_t GetDataSize() const =0; + + /// + // Returns a CefStreamReader object for streaming the contents of the file. + /// + virtual CefRefPtr GetStreamReader() const =0; + }; + + typedef std::map > FileMap; + + /// + // Create a new object. + /// + CefZipArchive(); + + /// + // Load the contents of the specified zip archive stream into this object. + // If the zip archive requires a password then provide it via |password|. + // If |overwriteExisting| is true then any files in this object that also + // exist in the specified archive will be replaced with the new files. + // Returns the number of files successfully loaded. + /// + size_t Load(CefRefPtr stream, + const CefString& password, + bool overwriteExisting); + + /// + // Clears the contents of this object. + /// + void Clear(); + + /// + // Returns the number of files in the archive. + /// + size_t GetFileCount() const; + + /// + // Returns true if the specified file exists and has contents. + /// + bool HasFile(const CefString& fileName) const; + + /// + // Returns the specified file. + /// + CefRefPtr GetFile(const CefString& fileName) const; + + /// + // Removes the specified file. + /// + bool RemoveFile(const CefString& fileName); + + /// + // Returns the map of all files. + /// + size_t GetFiles(FileMap& map) const; + + private: + // Protect against accidental deletion of this object. + friend class base::RefCountedThreadSafe; + ~CefZipArchive(); + + FileMap contents_; + + mutable base::Lock lock_; + + DISALLOW_COPY_AND_ASSIGN(CefZipArchive); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_ZIP_ARCHIVE_H_ diff --git a/libcef/browser/browser_context.h b/libcef/browser/browser_context.h new file mode 100644 index 000000000..6d90d4df6 --- /dev/null +++ b/libcef/browser/browser_context.h @@ -0,0 +1,24 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_H_ +#pragma once + +#include "content/public/browser/browser_context.h" +#include "content/public/browser/content_browser_client.h" + +class CefBrowserContext : public content::BrowserContext { + public: + virtual net::URLRequestContextGetter* CreateRequestContext( + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) = 0; + virtual net::URLRequestContextGetter* CreateRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) = 0; +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_H_ diff --git a/libcef/browser/browser_context_impl.cc b/libcef/browser/browser_context_impl.cc new file mode 100644 index 000000000..59845ede8 --- /dev/null +++ b/libcef/browser/browser_context_impl.cc @@ -0,0 +1,166 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_context_impl.h" + +#include + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/context.h" +#include "libcef/browser/download_manager_delegate.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_context_getter.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/threading/thread.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/browser/download_manager.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/resource_context.h" +#include "content/public/browser/storage_partition.h" + +using content::BrowserThread; + +class CefBrowserContextImpl::CefResourceContext : public content::ResourceContext { + public: + CefResourceContext() : getter_(NULL) {} + + // ResourceContext implementation: + net::HostResolver* GetHostResolver() override { + CHECK(getter_); + return getter_->host_resolver(); + } + net::URLRequestContext* GetRequestContext() override { + CHECK(getter_); + return getter_->GetURLRequestContext(); + } + + void set_url_request_context_getter(CefURLRequestContextGetter* getter) { + getter_ = getter; + } + + private: + CefURLRequestContextGetter* getter_; + + DISALLOW_COPY_AND_ASSIGN(CefResourceContext); +}; + +CefBrowserContextImpl::CefBrowserContextImpl() + : resource_context_(new CefResourceContext) { + BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices( + this); +} + +CefBrowserContextImpl::~CefBrowserContextImpl() { + // Delete the download manager delegate here because otherwise we'll crash + // when it's accessed from the content::BrowserContext destructor. + if (download_manager_delegate_.get()) + download_manager_delegate_.reset(NULL); + + if (resource_context_.get()) { + BrowserThread::DeleteSoon( + BrowserThread::IO, FROM_HERE, resource_context_.release()); + } + + // Remove any BrowserContextKeyedServiceFactory associations. + BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( + this); +} + +base::FilePath CefBrowserContextImpl::GetPath() const { + return CefContext::Get()->cache_path(); +} + +scoped_ptr + CefBrowserContextImpl::CreateZoomLevelDelegate(const base::FilePath&) { + return scoped_ptr(); +} + +bool CefBrowserContextImpl::IsOffTheRecord() const { + return false; +} + +content::DownloadManagerDelegate* + CefBrowserContextImpl::GetDownloadManagerDelegate() { + DCHECK(!download_manager_delegate_.get()); + + content::DownloadManager* manager = BrowserContext::GetDownloadManager(this); + download_manager_delegate_.reset(new CefDownloadManagerDelegate(manager)); + return download_manager_delegate_.get(); +} + +net::URLRequestContextGetter* CefBrowserContextImpl::GetRequestContext() { + CEF_REQUIRE_UIT(); + return GetDefaultStoragePartition(this)->GetURLRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextImpl::GetRequestContextForRenderProcess( + int renderer_child_id) { + return GetRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextImpl::GetMediaRequestContext() { + return GetRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextImpl::GetMediaRequestContextForRenderProcess( + int renderer_child_id) { + return GetRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextImpl::GetMediaRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory) { + return GetRequestContext(); +} + +content::ResourceContext* CefBrowserContextImpl::GetResourceContext() { + return resource_context_.get(); +} + +content::BrowserPluginGuestManager* CefBrowserContextImpl::GetGuestManager() { + return NULL; +} + +storage::SpecialStoragePolicy* + CefBrowserContextImpl::GetSpecialStoragePolicy() { + return NULL; +} + +content::PushMessagingService* + CefBrowserContextImpl::GetPushMessagingService() { + return NULL; +} + +content::SSLHostStateDelegate* + CefBrowserContextImpl::GetSSLHostStateDelegate() { + return NULL; +} + +net::URLRequestContextGetter* CefBrowserContextImpl::CreateRequestContext( + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) { + DCHECK(!url_request_getter_.get()); + url_request_getter_ = new CefURLRequestContextGetter( + BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO), + BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE), + protocol_handlers, + request_interceptors.Pass()); + resource_context_->set_url_request_context_getter(url_request_getter_.get()); + return url_request_getter_.get(); +} + +net::URLRequestContextGetter* + CefBrowserContextImpl::CreateRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) { + return NULL; +} diff --git a/libcef/browser/browser_context_impl.h b/libcef/browser/browser_context_impl.h new file mode 100644 index 000000000..37becfa2b --- /dev/null +++ b/libcef/browser/browser_context_impl.h @@ -0,0 +1,72 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_IMPL_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_IMPL_H_ +#pragma once + +#include "libcef/browser/browser_context.h" + +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" + +namespace content { +class DownloadManagerDelegate; +class SpeechRecognitionPreferences; +} + +class CefDownloadManagerDelegate; +class CefURLRequestContextGetter; + +class CefBrowserContextImpl : public CefBrowserContext { + public: + CefBrowserContextImpl(); + ~CefBrowserContextImpl() override; + + // BrowserContext methods. + base::FilePath GetPath() const override; + scoped_ptr CreateZoomLevelDelegate( + const base::FilePath& partition_path) override; + bool IsOffTheRecord() const override; + content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; + net::URLRequestContextGetter* GetRequestContext() override; + net::URLRequestContextGetter* GetRequestContextForRenderProcess( + int renderer_child_id) override; + net::URLRequestContextGetter* GetMediaRequestContext() override; + net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess( + int renderer_child_id) override; + net::URLRequestContextGetter* + GetMediaRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory) override; + content::ResourceContext* GetResourceContext() override; + content::BrowserPluginGuestManager* GetGuestManager() override; + storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; + content::PushMessagingService* GetPushMessagingService() override; + content::SSLHostStateDelegate* GetSSLHostStateDelegate() override; + + // CefBrowserContext methods. + net::URLRequestContextGetter* CreateRequestContext( + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + override; + net::URLRequestContextGetter* CreateRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + override; + + private: + class CefResourceContext; + + scoped_ptr resource_context_; + scoped_ptr download_manager_delegate_; + scoped_refptr url_request_getter_; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserContextImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_IMPL_H_ diff --git a/libcef/browser/browser_context_proxy.cc b/libcef/browser/browser_context_proxy.cc new file mode 100644 index 000000000..edf9cbc47 --- /dev/null +++ b/libcef/browser/browser_context_proxy.cc @@ -0,0 +1,164 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_context_proxy.h" + +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/download_manager_delegate.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_context_getter.h" +#include "libcef/browser/url_request_context_getter_proxy.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/threading/thread.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/resource_context.h" +#include "content/public/browser/storage_partition.h" + +using content::BrowserThread; + +class CefBrowserContextProxy::CefResourceContext : + public content::ResourceContext { + public: + CefResourceContext() : getter_(NULL) {} + + // ResourceContext implementation: + net::HostResolver* GetHostResolver() override { + CHECK(getter_); + return getter_->GetHostResolver(); + } + net::URLRequestContext* GetRequestContext() override { + CHECK(getter_); + return getter_->GetURLRequestContext(); + } + + void set_url_request_context_getter(CefURLRequestContextGetterProxy* getter) { + getter_ = getter; + } + + private: + CefURLRequestContextGetterProxy* getter_; + + DISALLOW_COPY_AND_ASSIGN(CefResourceContext); +}; + +CefBrowserContextProxy::CefBrowserContextProxy( + CefRefPtr handler, + CefBrowserContext* parent) + : refct_(0), + handler_(handler), + parent_(parent), + resource_context_(new CefResourceContext) { + BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices( + this); +} + +CefBrowserContextProxy::~CefBrowserContextProxy() { + if (resource_context_.get()) { + BrowserThread::DeleteSoon( + BrowserThread::IO, FROM_HERE, resource_context_.release()); + } + + // Remove any BrowserContextKeyedServiceFactory associations. + BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices( + this); +} + +base::FilePath CefBrowserContextProxy::GetPath() const { + return parent_->GetPath(); +} + +scoped_ptr + CefBrowserContextProxy::CreateZoomLevelDelegate( + const base::FilePath& partition_path) { + return parent_->CreateZoomLevelDelegate(partition_path); +} + +bool CefBrowserContextProxy::IsOffTheRecord() const { + return parent_->IsOffTheRecord(); +} + +content::DownloadManagerDelegate* + CefBrowserContextProxy::GetDownloadManagerDelegate() { + DCHECK(!download_manager_delegate_.get()); + + content::DownloadManager* manager = BrowserContext::GetDownloadManager(this); + download_manager_delegate_.reset(new CefDownloadManagerDelegate(manager)); + return download_manager_delegate_.get(); +} + +net::URLRequestContextGetter* CefBrowserContextProxy::GetRequestContext() { + CEF_REQUIRE_UIT(); + return GetDefaultStoragePartition(this)->GetURLRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextProxy::GetRequestContextForRenderProcess( + int renderer_child_id) { + return GetRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextProxy::GetMediaRequestContext() { + return GetRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextProxy::GetMediaRequestContextForRenderProcess( + int renderer_child_id) { + return GetRequestContext(); +} + +net::URLRequestContextGetter* + CefBrowserContextProxy::GetMediaRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory) { + return GetRequestContext(); +} + +content::ResourceContext* CefBrowserContextProxy::GetResourceContext() { + return resource_context_.get(); +} + +content::BrowserPluginGuestManager* CefBrowserContextProxy::GetGuestManager() { + return parent_->GetGuestManager(); +} + +storage::SpecialStoragePolicy* + CefBrowserContextProxy::GetSpecialStoragePolicy() { + return parent_->GetSpecialStoragePolicy(); +} + +content::PushMessagingService* + CefBrowserContextProxy::GetPushMessagingService() { + return parent_->GetPushMessagingService(); +} + +content::SSLHostStateDelegate* + CefBrowserContextProxy::GetSSLHostStateDelegate() { + return parent_->GetSSLHostStateDelegate(); +} + +net::URLRequestContextGetter* CefBrowserContextProxy::CreateRequestContext( + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) { + DCHECK(!url_request_getter_.get()); + url_request_getter_ = + new CefURLRequestContextGetterProxy(handler_, + static_cast( + CefContentBrowserClient::Get()->request_context().get())); + resource_context_->set_url_request_context_getter(url_request_getter_.get()); + return url_request_getter_.get(); +} + +net::URLRequestContextGetter* + CefBrowserContextProxy::CreateRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) { + return NULL; +} diff --git a/libcef/browser/browser_context_proxy.h b/libcef/browser/browser_context_proxy.h new file mode 100644 index 000000000..aa004f0b2 --- /dev/null +++ b/libcef/browser/browser_context_proxy.h @@ -0,0 +1,85 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_PROXY_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_PROXY_H_ +#pragma once + +#include "include/cef_request_context_handler.h" +#include "libcef/browser/browser_context.h" + +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" + +namespace content { +class DownloadManagerDelegate; +class SpeechRecognitionPreferences; +} + +class CefDownloadManagerDelegate; +class CefURLRequestContextGetterProxy; + +// This class is only accessed on the UI thread. +class CefBrowserContextProxy : public CefBrowserContext { + public: + CefBrowserContextProxy(CefRefPtr handler, + CefBrowserContext* parent); + ~CefBrowserContextProxy() override; + + // Reference counting and object life span is managed by + // CefContentBrowserClient. + void AddRef() { refct_++; } + bool Release() { return (--refct_ == 0); } + + // BrowserContext methods. + base::FilePath GetPath() const override; + scoped_ptr CreateZoomLevelDelegate( + const base::FilePath& partition_path) override; + bool IsOffTheRecord() const override; + content::DownloadManagerDelegate* GetDownloadManagerDelegate() override; + net::URLRequestContextGetter* GetRequestContext() override; + net::URLRequestContextGetter* GetRequestContextForRenderProcess( + int renderer_child_id) override; + net::URLRequestContextGetter* GetMediaRequestContext() override; + net::URLRequestContextGetter* GetMediaRequestContextForRenderProcess( + int renderer_child_id) override; + net::URLRequestContextGetter* + GetMediaRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory) override; + content::ResourceContext* GetResourceContext() override; + content::BrowserPluginGuestManager* GetGuestManager() override; + storage::SpecialStoragePolicy* GetSpecialStoragePolicy() override; + content::PushMessagingService* GetPushMessagingService() override; + content::SSLHostStateDelegate* GetSSLHostStateDelegate() override; + + // CefBrowserContext methods. + net::URLRequestContextGetter* CreateRequestContext( + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + override; + net::URLRequestContextGetter* CreateRequestContextForStoragePartition( + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + override; + + CefRefPtr handler() const { return handler_; } + + private: + class CefResourceContext; + + int refct_; + CefRefPtr handler_; + CefBrowserContext* parent_; + scoped_ptr resource_context_; + scoped_ptr download_manager_delegate_; + scoped_refptr url_request_getter_; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserContextProxy); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_CONTEXT_PROXY_H_ diff --git a/libcef/browser/browser_host_impl.cc b/libcef/browser/browser_host_impl.cc new file mode 100644 index 000000000..0d83125b5 --- /dev/null +++ b/libcef/browser/browser_host_impl.cc @@ -0,0 +1,3057 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_host_impl.h" + +#include +#include + +#include "libcef/browser/browser_context.h" +#include "libcef/browser/browser_info.h" +#include "libcef/browser/browser_pref_store.h" +#include "libcef/browser/chrome_scheme_handler.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/devtools_delegate.h" +#include "libcef/browser/devtools_frontend.h" +#include "libcef/browser/media_capture_devices_dispatcher.h" +#include "libcef/browser/navigate_params.h" +#include "libcef/browser/navigation_entry_impl.h" +#include "libcef/browser/printing/print_view_manager.h" +#include "libcef/browser/render_widget_host_view_osr.h" +#include "libcef/browser/request_context_impl.h" +#include "libcef/browser/scheme_handler.h" +#include "libcef/browser/web_contents_view_osr.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/cef_messages.h" +#include "libcef/common/cef_switches.h" +#include "libcef/common/drag_data_impl.h" +#include "libcef/common/http_header_utils.h" +#include "libcef/common/main_delegate.h" +#include "libcef/common/process_message_impl.h" +#include "libcef/common/request_impl.h" + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/command_line.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/spellchecker/spellcheck_factory.h" +#include "chrome/browser/spellchecker/spellcheck_service.h" +#include "components/pdf/common/pdf_messages.h" +#include "content/browser/gpu/compositor_util.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/common/view_messages.h" +#include "content/public/browser/download_manager.h" +#include "content/public/browser/download_url_parameters.h" +#include "content/public/browser/host_zoom_map.h" +#include "content/public/browser/native_web_keyboard_event.h" +#include "content/public/browser/navigation_controller.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/notification_details.h" +#include "content/public/browser/notification_source.h" +#include "content/public/browser/notification_types.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/resource_request_info.h" +#include "content/public/common/file_chooser_params.h" +#include "third_party/WebKit/public/web/WebFindOptions.h" +#include "ui/shell_dialogs/selected_file_info.h" + +#if defined(OS_LINUX) || defined(OS_ANDROID) +#include "ui/gfx/font_render_params.h" +#endif + +#if defined(OS_MACOSX) +#include "chrome/browser/spellchecker/spellcheck_platform_mac.h" +#endif + +#if defined(USE_AURA) +#include "ui/views/widget/widget.h" +#endif + +namespace { + +class CreateBrowserHelper { + public: + CreateBrowserHelper(const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefRefPtr request_context) + : window_info_(windowInfo), + client_(client), + url_(url), + settings_(settings), + request_context_(request_context) {} + + CefWindowInfo window_info_; + CefRefPtr client_; + CefString url_; + CefBrowserSettings settings_; + CefRefPtr request_context_; +}; + +void CreateBrowserWithHelper(CreateBrowserHelper* helper) { + CefBrowserHost::CreateBrowserSync(helper->window_info_, helper->client_, + helper->url_, helper->settings_, helper->request_context_); + delete helper; +} + +class ShowDevToolsHelper { + public: + ShowDevToolsHelper(CefRefPtr browser, + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) + : browser_(browser), + window_info_(windowInfo), + client_(client), + settings_(settings), + inspect_element_at_(inspect_element_at) {} + + CefRefPtr browser_; + CefWindowInfo window_info_; + CefRefPtr client_; + CefBrowserSettings settings_; + CefPoint inspect_element_at_; +}; + +void ShowDevToolsWithHelper(ShowDevToolsHelper* helper) { + helper->browser_->ShowDevTools(helper->window_info_, helper->client_, + helper->settings_, helper->inspect_element_at_); + delete helper; +} + +// Convert a NativeWebKeyboardEvent to a CefKeyEvent. +bool GetCefKeyEvent(const content::NativeWebKeyboardEvent& event, + CefKeyEvent& cef_event) { + switch (event.type) { + case blink::WebKeyboardEvent::RawKeyDown: + cef_event.type = KEYEVENT_RAWKEYDOWN; + break; + case blink::WebKeyboardEvent::KeyDown: + cef_event.type = KEYEVENT_KEYDOWN; + break; + case blink::WebKeyboardEvent::KeyUp: + cef_event.type = KEYEVENT_KEYUP; + break; + case blink::WebKeyboardEvent::Char: + cef_event.type = KEYEVENT_CHAR; + break; + default: + return false; + } + + cef_event.modifiers = 0; + if (event.modifiers & blink::WebKeyboardEvent::ShiftKey) + cef_event.modifiers |= EVENTFLAG_SHIFT_DOWN; + if (event.modifiers & blink::WebKeyboardEvent::ControlKey) + cef_event.modifiers |= EVENTFLAG_CONTROL_DOWN; + if (event.modifiers & blink::WebKeyboardEvent::AltKey) + cef_event.modifiers |= EVENTFLAG_ALT_DOWN; + if (event.modifiers & blink::WebKeyboardEvent::MetaKey) + cef_event.modifiers |= EVENTFLAG_COMMAND_DOWN; + if (event.modifiers & blink::WebKeyboardEvent::IsKeyPad) + cef_event.modifiers |= EVENTFLAG_IS_KEY_PAD; + + cef_event.windows_key_code = event.windowsKeyCode; + cef_event.native_key_code = event.nativeKeyCode; + cef_event.is_system_key = event.isSystemKey; + cef_event.character = event.text[0]; + cef_event.unmodified_character = event.unmodifiedText[0]; + + return true; +} + +// Returns the OS event handle, if any, associated with |event|. +CefEventHandle GetCefEventHandle(const content::NativeWebKeyboardEvent& event) { +#if defined(USE_AURA) + if (!event.os_event) + return NULL; +#if defined(OS_WIN) + return const_cast(&event.os_event->native_event()); +#else + return const_cast(event.os_event->native_event()); +#endif +#else // !defined(USE_AURA) + return event.os_event; +#endif // !defined(USE_AURA) +} + +class CefFileDialogCallbackImpl : public CefFileDialogCallback { + public: + explicit CefFileDialogCallbackImpl( + const CefBrowserHostImpl::RunFileChooserCallback& callback) + : callback_(callback) { + } + ~CefFileDialogCallbackImpl() override { + if (!callback_.is_null()) { + // The callback is still pending. Cancel it now. + if (CEF_CURRENTLY_ON_UIT()) { + CancelNow(callback_); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefFileDialogCallbackImpl::CancelNow, callback_)); + } + } + } + + void Continue(int selected_accept_filter, + const std::vector& file_paths) override { + if (CEF_CURRENTLY_ON_UIT()) { + if (!callback_.is_null()) { + std::vector vec; + if (!file_paths.empty()) { + std::vector::const_iterator it = file_paths.begin(); + for (; it != file_paths.end(); ++it) + vec.push_back(base::FilePath(*it)); + } + callback_.Run(selected_accept_filter, vec); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefFileDialogCallbackImpl::Continue, this, + selected_accept_filter, file_paths)); + } + } + + void Cancel() override { + if (CEF_CURRENTLY_ON_UIT()) { + if (!callback_.is_null()) { + CancelNow(callback_); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefFileDialogCallbackImpl::Cancel, this)); + } + } + + bool IsConnected() { + return !callback_.is_null(); + } + + void Disconnect() { + callback_.Reset(); + } + + private: + static void CancelNow( + const CefBrowserHostImpl::RunFileChooserCallback& callback) { + CEF_REQUIRE_UIT(); + std::vector file_paths; + callback.Run(0, file_paths); + } + + CefBrowserHostImpl::RunFileChooserCallback callback_; + + IMPLEMENT_REFCOUNTING(CefFileDialogCallbackImpl); +}; + +void RunFileDialogDismissed( + CefRefPtr callback, + int selected_accept_filter, + const std::vector& file_paths) { + std::vector paths; + if (file_paths.size() > 0) { + for (size_t i = 0; i < file_paths.size(); ++i) + paths.push_back(file_paths[i].value()); + } + callback->OnFileDialogDismissed(selected_accept_filter, paths); +} + +} // namespace + + +// CefBrowserHost static methods. +// ----------------------------------------------------------------------------- + +// static +bool CefBrowserHost::CreateBrowser( + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefRefPtr request_context) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return false; + } + + // Verify that the settings structure is a valid size. + if (settings.size != sizeof(cef_browser_settings_t)) { + NOTREACHED() << "invalid CefBrowserSettings structure size"; + return false; + } + + // Verify windowless rendering requirements. + if (windowInfo.windowless_rendering_enabled) { + if (!client->GetRenderHandler().get()) { + NOTREACHED() << "CefRenderHandler implementation is required"; + return false; + } + if (!content::IsDelegatedRendererEnabled()) { + NOTREACHED() << "Delegated renderer must be enabled"; + return false; + } + } + + // Create the browser on the UI thread. + CreateBrowserHelper* helper = + new CreateBrowserHelper(windowInfo, client, url, settings, + request_context); + CEF_POST_TASK(CEF_UIT, base::Bind(CreateBrowserWithHelper, helper)); + + return true; +} + +// static +CefRefPtr CefBrowserHost::CreateBrowserSync( + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefRefPtr request_context) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return NULL; + } + + // Verify that the settings structure is a valid size. + if (settings.size != sizeof(cef_browser_settings_t)) { + NOTREACHED() << "invalid CefBrowserSettings structure size"; + return NULL; + } + + // Verify that this method is being called on the UI thread. + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + CefRefPtr browser = + CefBrowserHostImpl::Create(windowInfo, client, url, settings, + kNullWindowHandle, false, request_context); + return browser.get(); +} + + +// CefBrowserHostImpl static methods. +// ----------------------------------------------------------------------------- + +// static +CefRefPtr CefBrowserHostImpl::Create( + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefWindowHandle opener, + bool is_popup, + CefRefPtr request_context) { + // Verify windowless rendering requirements. + if (windowInfo.windowless_rendering_enabled) { + if (!client->GetRenderHandler().get()) { + NOTREACHED() << "CefRenderHandler implementation is required"; + return NULL; + } + if (!content::IsDelegatedRendererEnabled()) { + NOTREACHED() << "Delegated renderer must be enabled"; + return NULL; + } + } + + scoped_refptr info = + CefContentBrowserClient::Get()->CreateBrowserInfo(is_popup); + info->set_windowless(windowInfo.windowless_rendering_enabled ? true : false); + + CefRefPtr browser = + CefBrowserHostImpl::CreateInternal(windowInfo, settings, client, NULL, + info, opener, request_context); + if (browser.get() && !url.empty()) { + browser->LoadURL(CefFrameHostImpl::kMainFrameId, url, content::Referrer(), + ui::PAGE_TRANSITION_TYPED, std::string()); + } + return browser.get(); +} + +// static +CefRefPtr CefBrowserHostImpl::CreateInternal( + const CefWindowInfo& window_info, + const CefBrowserSettings& settings, + CefRefPtr client, + content::WebContents* web_contents, + scoped_refptr browser_info, + CefWindowHandle opener, + CefRefPtr request_context) { + CEF_REQUIRE_UIT(); + DCHECK(browser_info.get()); + + // If |opener| is non-NULL it must be a popup window. + DCHECK(opener == kNullWindowHandle || browser_info->is_popup()); + + if (!web_contents) { + CefBrowserContext* browser_context = NULL; + if (request_context.get()) { + CefRequestContextImpl* request_context_impl = + static_cast(request_context.get()); + browser_context = request_context_impl->GetOrCreateBrowserContext(); + } else { + browser_context = CefContentBrowserClient::Get()->browser_context(); + } + DCHECK(browser_context); + + content::WebContents::CreateParams create_params( + browser_context); + + CefWebContentsViewOSR* view_or = NULL; + if (window_info.windowless_rendering_enabled) { + // Use the OSR view instead of the default view. + view_or = new CefWebContentsViewOSR(); + create_params.view = view_or; + create_params.delegate_view = view_or; + } + web_contents = content::WebContents::Create(create_params); + if (view_or) + view_or->set_web_contents(web_contents); + } + + CefRefPtr browser = + new CefBrowserHostImpl(window_info, settings, client, web_contents, + browser_info, opener); + if (!browser->IsWindowless() && !browser->PlatformCreateWindow()) + return NULL; + +#if defined(OS_LINUX) || defined(OS_ANDROID) + content::RendererPreferences* prefs = web_contents->GetMutableRendererPrefs(); + CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams, params, + (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(true), NULL))); + prefs->should_antialias_text = params.antialiasing; + prefs->use_subpixel_positioning = params.subpixel_positioning; + prefs->hinting = params.hinting; + prefs->use_autohinter = params.autohinter; + prefs->use_bitmaps = params.use_bitmaps; + prefs->subpixel_rendering = params.subpixel_rendering; + web_contents->GetRenderViewHost()->SyncRendererPrefs(); +#endif // defined(OS_LINUX) || defined(OS_ANDROID) + + if (client.get()) { + CefRefPtr handler = client->GetLifeSpanHandler(); + if (handler.get()) + handler->OnAfterCreated(browser.get()); + } + + return browser; +} + +// static +CefRefPtr CefBrowserHostImpl::GetBrowserForHost( + const content::RenderViewHost* host) { + DCHECK(host); + CEF_REQUIRE_UIT(); + content::WebContents* web_contents = + content::WebContents::FromRenderViewHost(host); + if (web_contents) + return static_cast(web_contents->GetDelegate()); + return NULL; +} + +// static +CefRefPtr CefBrowserHostImpl::GetBrowserForHost( + const content::RenderFrameHost* host) { + DCHECK(host); + CEF_REQUIRE_UIT(); + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost( + const_cast(host)); + if (web_contents) + return static_cast(web_contents->GetDelegate()); + return NULL; +} + +// static +CefRefPtr CefBrowserHostImpl::GetBrowserForContents( + content::WebContents* contents) { + DCHECK(contents); + CEF_REQUIRE_UIT(); + return static_cast(contents->GetDelegate()); +} + +// static +CefRefPtr CefBrowserHostImpl::GetBrowserForRequest( + net::URLRequest* request) { + DCHECK(request); + CEF_REQUIRE_IOT(); + int render_process_id = -1; + int render_frame_id = MSG_ROUTING_NONE; + + if (!content::ResourceRequestInfo::GetRenderFrameForRequest( + request, &render_process_id, &render_frame_id) || + render_process_id == -1 || + render_frame_id == MSG_ROUTING_NONE) { + return NULL; + } + + return GetBrowserForFrame(render_process_id, render_frame_id); +} + +// static +CefRefPtr CefBrowserHostImpl::GetBrowserForView( + int render_process_id, int render_routing_id) { + if (render_process_id == -1 || render_routing_id == MSG_ROUTING_NONE) + return NULL; + + if (CEF_CURRENTLY_ON_UIT()) { + // Use the non-thread-safe but potentially faster approach. + content::RenderViewHost* render_view_host = + content::RenderViewHost::FromID(render_process_id, render_routing_id); + if (!render_view_host) + return NULL; + return GetBrowserForHost(render_view_host); + } else { + // Use the thread-safe approach. + scoped_refptr info = + CefContentBrowserClient::Get()->GetBrowserInfoForView( + render_process_id, + render_routing_id); + if (info.get()) { + CefRefPtr browser = info->browser(); + if (!browser.get()) { + LOG(WARNING) << "Found browser id " << info->browser_id() << + " but no browser object matching view process id " << + render_process_id << " and routing id " << + render_routing_id; + } + return browser; + } + return NULL; + } +} + +// static +CefRefPtr CefBrowserHostImpl::GetBrowserForFrame( + int render_process_id, int render_routing_id) { + if (render_process_id == -1 || render_routing_id == MSG_ROUTING_NONE) + return NULL; + + if (CEF_CURRENTLY_ON_UIT()) { + // Use the non-thread-safe but potentially faster approach. + content::RenderFrameHost* render_frame_host = + content::RenderFrameHost::FromID(render_process_id, render_routing_id); + if (!render_frame_host) + return NULL; + return GetBrowserForHost(render_frame_host); + } else { + // Use the thread-safe approach. + scoped_refptr info = + CefContentBrowserClient::Get()->GetBrowserInfoForFrame( + render_process_id, + render_routing_id); + if (info.get()) { + CefRefPtr browser = info->browser(); + if (!browser.get()) { + LOG(WARNING) << "Found browser id " << info->browser_id() << + " but no browser object matching frame process id " << + render_process_id << " and routing id " << + render_routing_id; + } + return browser; + } + return NULL; + } +} + + +// CefBrowserHostImpl methods. +// ----------------------------------------------------------------------------- + +// WebContentsObserver that will be notified when the frontend WebContents is +// destroyed so that the inspected browser can clear its DevTools references. +class CefBrowserHostImpl::DevToolsWebContentsObserver : + public content::WebContentsObserver { + public: + DevToolsWebContentsObserver(CefBrowserHostImpl* browser, + content::WebContents* frontend_web_contents) + : WebContentsObserver(frontend_web_contents), + browser_(browser) { + } + + // WebContentsObserver methods: + void WebContentsDestroyed() override { + browser_->OnDevToolsWebContentsDestroyed(); + } + + private: + CefBrowserHostImpl* browser_; + + DISALLOW_COPY_AND_ASSIGN(DevToolsWebContentsObserver); +}; + +CefBrowserHostImpl::~CefBrowserHostImpl() { +} + +CefRefPtr CefBrowserHostImpl::GetBrowser() { + return this; +} + +void CefBrowserHostImpl::CloseBrowser(bool force_close) { + if (CEF_CURRENTLY_ON_UIT()) { + // Exit early if a close attempt is already pending and this method is + // called again from somewhere other than WindowDestroyed(). + if (destruction_state_ >= DESTRUCTION_STATE_PENDING && + (IsWindowless() || !window_destroyed_)) { + if (force_close && destruction_state_ == DESTRUCTION_STATE_PENDING) { + // Upgrade the destruction state. + destruction_state_ = DESTRUCTION_STATE_ACCEPTED; + } + return; + } + + if (destruction_state_ < DESTRUCTION_STATE_ACCEPTED) { + destruction_state_ = (force_close ? DESTRUCTION_STATE_ACCEPTED : + DESTRUCTION_STATE_PENDING); + } + + content::WebContents* contents = web_contents(); + if (contents && contents->NeedToFireBeforeUnload()) { + // Will result in a call to BeforeUnloadFired() and, if the close isn't + // canceled, CloseContents(). + contents->DispatchBeforeUnload(false); + } else { + CloseContents(contents); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::CloseBrowser, this, force_close)); + } +} + +void CefBrowserHostImpl::SetFocus(bool focus) { + if (focus) { + OnSetFocus(FOCUS_SOURCE_SYSTEM); + } else { + if (CEF_CURRENTLY_ON_UIT()) { + PlatformSetFocus(false); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::PlatformSetFocus, this, false)); + } + } +} + +void CefBrowserHostImpl::SetWindowVisibility(bool visible) { +#if defined(OS_MACOSX) + if (CEF_CURRENTLY_ON_UIT()) { + PlatformSetWindowVisibility(visible); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::PlatformSetWindowVisibility, + this, visible)); + } +#endif +} + +CefWindowHandle CefBrowserHostImpl::GetWindowHandle() { + return PlatformGetWindowHandle(); +} + +CefWindowHandle CefBrowserHostImpl::GetOpenerWindowHandle() { + return opener_; +} + +CefRefPtr CefBrowserHostImpl::GetClient() { + return client_; +} + +CefRefPtr CefBrowserHostImpl::GetRequestContext() { + return request_context_; +} + +double CefBrowserHostImpl::GetZoomLevel() { + // Verify that this method is being called on the UI thread. + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "called on invalid thread"; + return 0; + } + + if (web_contents()) + return content::HostZoomMap::GetZoomLevel(web_contents()); + + return 0; +} + +void CefBrowserHostImpl::SetZoomLevel(double zoomLevel) { + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents()) + content::HostZoomMap::SetZoomLevel(web_contents(), zoomLevel); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SetZoomLevel, this, zoomLevel)); + } +} + +void CefBrowserHostImpl::RunFileDialog( + FileDialogMode mode, + const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, + int selected_accept_filter, + CefRefPtr callback) { + DCHECK(callback.get()); + if (!callback.get()) + return; + + FileChooserParams params; + switch (mode & FILE_DIALOG_TYPE_MASK) { + case FILE_DIALOG_OPEN: + params.mode = content::FileChooserParams::Open; + break; + case FILE_DIALOG_OPEN_MULTIPLE: + params.mode = content::FileChooserParams::OpenMultiple; + break; + case FILE_DIALOG_OPEN_FOLDER: + params.mode = content::FileChooserParams::UploadFolder; + break; + case FILE_DIALOG_SAVE: + params.mode = content::FileChooserParams::Save; + break; + } + + DCHECK_GE(selected_accept_filter, 0); + params.selected_accept_filter = selected_accept_filter; + + params.overwriteprompt = !!(mode & FILE_DIALOG_OVERWRITEPROMPT_FLAG); + params.hidereadonly = !!(mode & FILE_DIALOG_HIDEREADONLY_FLAG); + + params.title = title; + if (!default_file_path.empty()) + params.default_file_name = base::FilePath(default_file_path); + + if (!accept_filters.empty()) { + std::vector::const_iterator it = accept_filters.begin(); + for (; it != accept_filters.end(); ++it) + params.accept_types.push_back(*it); + } + + RunFileChooser(params, base::Bind(RunFileDialogDismissed, callback)); +} + +void CefBrowserHostImpl::StartDownload(const CefString& url) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::StartDownload, this, url)); + return; + } + + GURL gurl = GURL(url.ToString()); + if (gurl.is_empty() || !gurl.is_valid()) + return; + + if (!web_contents()) + return; + + CefBrowserContext* context = + static_cast(web_contents()->GetBrowserContext()); + if (!context) + return; + + content::DownloadManager* manager = + content::BrowserContext::GetDownloadManager(context); + if (!manager) + return; + + scoped_ptr params; + params.reset( + content::DownloadUrlParameters::FromWebContents(web_contents(), gurl)); + manager->DownloadUrl(params.Pass()); +} + +void CefBrowserHostImpl::Print() { + if (CEF_CURRENTLY_ON_UIT()) { + if (!web_contents_) + return; + printing::PrintViewManager::FromWebContents( + web_contents_.get())->PrintNow(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::Print, this)); + } +} + +void CefBrowserHostImpl::Find(int identifier, const CefString& searchText, + bool forward, bool matchCase, bool findNext) { + if (CEF_CURRENTLY_ON_UIT()) { + if (!web_contents_) + return; + + blink::WebFindOptions options; + options.forward = forward; + options.matchCase = matchCase; + options.findNext = findNext; + web_contents()->Find(identifier, searchText, options); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::Find, this, identifier, searchText, + forward, matchCase, findNext)); + } +} + +void CefBrowserHostImpl::StopFinding(bool clearSelection) { + if (CEF_CURRENTLY_ON_UIT()) { + if (!web_contents_) + return; + + content::StopFindAction action = clearSelection ? + content::STOP_FIND_ACTION_CLEAR_SELECTION : + content::STOP_FIND_ACTION_KEEP_SELECTION; + web_contents()->StopFinding(action); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::StopFinding, this, clearSelection)); + } +} + +void CefBrowserHostImpl::ShowDevTools( + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) { + if (CEF_CURRENTLY_ON_UIT()) { + if (!web_contents_) + return; + + if (devtools_frontend_) { + devtools_frontend_->Focus(); + return; + } + + devtools_frontend_ = CefDevToolsFrontend::Show( + this, windowInfo, client, settings, inspect_element_at); + devtools_observer_.reset(new DevToolsWebContentsObserver( + this, devtools_frontend_->frontend_browser()->web_contents())); + } else { + ShowDevToolsHelper* helper = + new ShowDevToolsHelper(this, windowInfo, client, settings, + inspect_element_at); + CEF_POST_TASK(CEF_UIT, base::Bind(ShowDevToolsWithHelper, helper)); + } +} + +void CefBrowserHostImpl::CloseDevTools() { + if (CEF_CURRENTLY_ON_UIT()) { + if (!devtools_frontend_) + return; + devtools_frontend_->Close(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::CloseDevTools, this)); + } +} + +void CefBrowserHostImpl::GetNavigationEntries( + CefRefPtr visitor, + bool current_only) { + DCHECK(visitor.get()); + if (!visitor.get()) + return; + + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::GetNavigationEntries, this, visitor, + current_only)); + return; + } + + if (!web_contents()) + return; + + const content::NavigationController& controller = + web_contents()->GetController(); + const int total = controller.GetEntryCount(); + const int current = controller.GetCurrentEntryIndex(); + + if (current_only) { + // Visit only the current entry. + CefRefPtr entry = + new CefNavigationEntryImpl(controller.GetEntryAtIndex(current)); + visitor->Visit(entry.get(), true, current, total); + entry->Detach(NULL); + } else { + // Visit all entries. + bool cont = true; + for (int i = 0; i < total && cont; ++i) { + CefRefPtr entry = + new CefNavigationEntryImpl(controller.GetEntryAtIndex(i)); + cont = visitor->Visit(entry.get(), (i == current), i, total); + entry->Detach(NULL); + } + } +} + +void CefBrowserHostImpl::SetMouseCursorChangeDisabled(bool disabled) { + base::AutoLock lock_scope(state_lock_); + mouse_cursor_change_disabled_ = disabled; +} + +bool CefBrowserHostImpl::IsMouseCursorChangeDisabled() { + base::AutoLock lock_scope(state_lock_); + return mouse_cursor_change_disabled_; +} + +bool CefBrowserHostImpl::IsWindowRenderingDisabled() { + return IsWindowless(); +} + +void CefBrowserHostImpl::ReplaceMisspelling(const CefString& word) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::ReplaceMisspelling, this, word)); + return; + } + + if(web_contents()) + web_contents()->ReplaceMisspelling(word); +} + +void CefBrowserHostImpl::AddWordToDictionary(const CefString& word) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::AddWordToDictionary, this, word)); + return; + } + + if (!web_contents()) + return; + + content::BrowserContext* browser_context = + web_contents()->GetBrowserContext(); + if (browser_context) { + SpellcheckService* spellcheck = + SpellcheckServiceFactory::GetForContext(browser_context); + if (spellcheck) + spellcheck->GetCustomDictionary()->AddWord(word); + } +#if defined(OS_MACOSX) + spellcheck_mac::AddWord(word); +#endif +} + +void CefBrowserHostImpl::WasResized() { + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, base::Bind(&CefBrowserHostImpl::WasResized, this)); + return; + } + + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->WasResized(); +} + +void CefBrowserHostImpl::WasHidden(bool hidden) { + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHost::WasHidden, this, hidden)); + return; + } + + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) { + if (hidden) + view->WasHidden(); + else + view->WasShown(); + } +} + +void CefBrowserHostImpl::NotifyScreenInfoChanged() { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::NotifyScreenInfoChanged, this)); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->OnScreenInfoChanged(); +} + +void CefBrowserHostImpl::Invalidate(PaintElementType type) { + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::Invalidate, this, type)); + return; + } + + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->Invalidate(type); +} + +void CefBrowserHostImpl::SendKeyEvent(const CefKeyEvent& event) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendKeyEvent, this, event)); + return; + } + + content::NativeWebKeyboardEvent web_event; + PlatformTranslateKeyEvent(web_event, event); + + if (!IsWindowless()) { + content::RenderWidgetHost* widget = web_contents()->GetRenderViewHost(); + if (widget) + widget->ForwardKeyboardEvent(web_event); + } else { + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->SendKeyEvent(web_event); + } +} + +void CefBrowserHostImpl::SendMouseClickEvent(const CefMouseEvent& event, + MouseButtonType type, bool mouseUp, int clickCount) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendMouseClickEvent, this, event, type, + mouseUp, clickCount)); + return; + } + + blink::WebMouseEvent web_event; + PlatformTranslateClickEvent(web_event, event, type, mouseUp, clickCount); + + SendMouseEvent(web_event); +} + +void CefBrowserHostImpl::SendMouseMoveEvent(const CefMouseEvent& event, + bool mouseLeave) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendMouseMoveEvent, this, event, + mouseLeave)); + return; + } + + blink::WebMouseEvent web_event; + PlatformTranslateMoveEvent(web_event, event, mouseLeave); + + SendMouseEvent(web_event); +} + +void CefBrowserHostImpl::SendMouseWheelEvent(const CefMouseEvent& event, + int deltaX, int deltaY) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendMouseWheelEvent, this, event, + deltaX, deltaY)); + return; + } + + blink::WebMouseWheelEvent web_event; + PlatformTranslateWheelEvent(web_event, event, deltaX, deltaY); + + if (!IsWindowless()) { + content::RenderWidgetHost* widget = web_contents()->GetRenderViewHost(); + if (widget) + widget->ForwardWheelEvent(web_event); + } else { + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->SendMouseWheelEvent(web_event); + } +} + +int CefBrowserHostImpl::TranslateModifiers(uint32 cef_modifiers) { + int webkit_modifiers = 0; + // Set modifiers based on key state. + if (cef_modifiers & EVENTFLAG_SHIFT_DOWN) + webkit_modifiers |= blink::WebInputEvent::ShiftKey; + if (cef_modifiers & EVENTFLAG_CONTROL_DOWN) + webkit_modifiers |= blink::WebInputEvent::ControlKey; + if (cef_modifiers & EVENTFLAG_ALT_DOWN) + webkit_modifiers |= blink::WebInputEvent::AltKey; + if (cef_modifiers & EVENTFLAG_COMMAND_DOWN) + webkit_modifiers |= blink::WebInputEvent::MetaKey; + if (cef_modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON) + webkit_modifiers |= blink::WebInputEvent::LeftButtonDown; + if (cef_modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON) + webkit_modifiers |= blink::WebInputEvent::MiddleButtonDown; + if (cef_modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON) + webkit_modifiers |= blink::WebInputEvent::RightButtonDown; + if (cef_modifiers & EVENTFLAG_CAPS_LOCK_ON) + webkit_modifiers |= blink::WebInputEvent::CapsLockOn; + if (cef_modifiers & EVENTFLAG_NUM_LOCK_ON) + webkit_modifiers |= blink::WebInputEvent::NumLockOn; + if (cef_modifiers & EVENTFLAG_IS_LEFT) + webkit_modifiers |= blink::WebInputEvent::IsLeft; + if (cef_modifiers & EVENTFLAG_IS_RIGHT) + webkit_modifiers |= blink::WebInputEvent::IsRight; + if (cef_modifiers & EVENTFLAG_IS_KEY_PAD) + webkit_modifiers |= blink::WebInputEvent::IsKeyPad; + return webkit_modifiers; +} + +void CefBrowserHostImpl::SendMouseEvent(const blink::WebMouseEvent& event) { + if (!IsWindowless()) { + content::RenderWidgetHost* widget = web_contents()->GetRenderViewHost(); + if (widget) + widget->ForwardMouseEvent(event); + } else { + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->SendMouseEvent(event); + } +} + +void CefBrowserHostImpl::SendFocusEvent(bool setFocus) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendFocusEvent, this, setFocus)); + return; + } + + if (!IsWindowless()) { + SetFocus(setFocus); + } else { + if (!web_contents()) + return; + + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents()->GetRenderViewHost()->GetView()); + if (view) + view->SendFocusEvent(setFocus); + } +} + +void CefBrowserHostImpl::SendCaptureLostEvent() { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendCaptureLostEvent, this)); + return; + } + + if (!web_contents()) + return; + + content::RenderWidgetHostImpl* widget = + content::RenderWidgetHostImpl::From(web_contents()->GetRenderViewHost()); + if (widget) + widget->LostCapture(); +} + +void CefBrowserHostImpl::NotifyMoveOrResizeStarted() { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::NotifyMoveOrResizeStarted, this)); + return; + } + + if (!web_contents()) + return; + + // Dismiss any existing popups. + content::RenderViewHost* rvh = web_contents()->GetRenderViewHost(); + if (rvh) + rvh->NotifyMoveOrResizeStarted(); + + PlatformNotifyMoveOrResizeStarted(); +} + +// CefBrowser methods. +// ----------------------------------------------------------------------------- + +CefRefPtr CefBrowserHostImpl::GetHost() { + return this; +} + +bool CefBrowserHostImpl::CanGoBack() { + base::AutoLock lock_scope(state_lock_); + return can_go_back_; +} + +void CefBrowserHostImpl::GoBack() { + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents_.get() && web_contents_->GetController().CanGoBack()) + web_contents_->GetController().GoBack(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::GoBack, this)); + } +} + +bool CefBrowserHostImpl::CanGoForward() { + base::AutoLock lock_scope(state_lock_); + return can_go_forward_; +} + +void CefBrowserHostImpl::GoForward() { + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents_.get() && web_contents_->GetController().CanGoForward()) + web_contents_->GetController().GoForward(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::GoForward, this)); + } +} + +bool CefBrowserHostImpl::IsLoading() { + base::AutoLock lock_scope(state_lock_); + return is_loading_; +} + +void CefBrowserHostImpl::Reload() { + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents_.get()) + web_contents_->GetController().Reload(true); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::Reload, this)); + } +} + +void CefBrowserHostImpl::ReloadIgnoreCache() { + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents_.get()) + web_contents_->GetController().ReloadIgnoringCache(true); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::ReloadIgnoreCache, this)); + } +} + +void CefBrowserHostImpl::StopLoad() { + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents_.get()) + web_contents_->Stop(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::StopLoad, this)); + } +} + +int CefBrowserHostImpl::GetIdentifier() { + return browser_id(); +} + +bool CefBrowserHostImpl::IsSame(CefRefPtr that) { + CefBrowserHostImpl* impl = static_cast(that.get()); + return (impl == this); +} + +bool CefBrowserHostImpl::IsPopup() { + return browser_info_->is_popup(); +} + +bool CefBrowserHostImpl::HasDocument() { + base::AutoLock lock_scope(state_lock_); + return has_document_; +} + +CefRefPtr CefBrowserHostImpl::GetMainFrame() { + return GetFrame(CefFrameHostImpl::kMainFrameId); +} + +CefRefPtr CefBrowserHostImpl::GetFocusedFrame() { + return GetFrame(CefFrameHostImpl::kFocusedFrameId); +} + +CefRefPtr CefBrowserHostImpl::GetFrame(int64 identifier) { + base::AutoLock lock_scope(state_lock_); + + if (main_frame_id_ == CefFrameHostImpl::kInvalidFrameId) { + // A main frame does not exist yet. Return the placeholder frame that + // provides limited functionality. + return placeholder_frame_.get(); + } + + if (identifier == CefFrameHostImpl::kMainFrameId) { + identifier = main_frame_id_; + } else if (identifier == CefFrameHostImpl::kFocusedFrameId) { + // Return the main frame if no focused frame is currently identified. + if (focused_frame_id_ == CefFrameHostImpl::kInvalidFrameId) + identifier = main_frame_id_; + else + identifier = focused_frame_id_; + } + + if (identifier == CefFrameHostImpl::kInvalidFrameId) + return NULL; + + FrameMap::const_iterator it = frames_.find(identifier); + if (it != frames_.end()) + return it->second.get(); + + return NULL; +} + +CefRefPtr CefBrowserHostImpl::GetFrame(const CefString& name) { + base::AutoLock lock_scope(state_lock_); + + FrameMap::const_iterator it = frames_.begin(); + for (; it != frames_.end(); ++it) { + if (it->second->GetName() == name) + return it->second.get(); + } + + return NULL; +} + +size_t CefBrowserHostImpl::GetFrameCount() { + base::AutoLock lock_scope(state_lock_); + return frames_.size(); +} + +void CefBrowserHostImpl::GetFrameIdentifiers(std::vector& identifiers) { + base::AutoLock lock_scope(state_lock_); + + if (identifiers.size() > 0) + identifiers.clear(); + + FrameMap::const_iterator it = frames_.begin(); + for (; it != frames_.end(); ++it) + identifiers.push_back(it->first); +} + +void CefBrowserHostImpl::GetFrameNames(std::vector& names) { + base::AutoLock lock_scope(state_lock_); + + if (names.size() > 0) + names.clear(); + + FrameMap::const_iterator it = frames_.begin(); + for (; it != frames_.end(); ++it) + names.push_back(it->second->GetName()); +} + +bool CefBrowserHostImpl::SendProcessMessage( + CefProcessId target_process, + CefRefPtr message) { + DCHECK(message.get()); + + Cef_Request_Params params; + CefProcessMessageImpl* impl = + static_cast(message.get()); + if (impl->CopyTo(params)) { + return SendProcessMessage(target_process, params.name, ¶ms.arguments, + true); + } + + return false; +} + + +// CefBrowserHostImpl public methods. +// ----------------------------------------------------------------------------- + +bool CefBrowserHostImpl::IsWindowless() const { + return window_info_.windowless_rendering_enabled ? true : false; +} + +bool CefBrowserHostImpl::IsTransparent() const { + return window_info_.transparent_painting_enabled ? true : false; +} + +void CefBrowserHostImpl::WindowDestroyed() { + CEF_REQUIRE_UIT(); + DCHECK(!window_destroyed_); + window_destroyed_ = true; + CloseBrowser(true); +} + +void CefBrowserHostImpl::DestroyBrowser() { + CEF_REQUIRE_UIT(); + + destruction_state_ = DESTRUCTION_STATE_COMPLETED; + + if (client_.get()) { + CefRefPtr handler = client_->GetLifeSpanHandler(); + if (handler.get()) { + // Notify the handler that the window is about to be closed. + handler->OnBeforeClose(this); + } + } + + while (!queued_messages_.empty()) { + delete queued_messages_.front(); + queued_messages_.pop(); + } + + registrar_.reset(NULL); + response_manager_.reset(NULL); + content::WebContentsObserver::Observe(NULL); + web_contents_.reset(NULL); + menu_creator_.reset(NULL); + +#if defined(USE_AURA) + window_widget_ = NULL; +#endif + + DetachAllFrames(); + + CefContentBrowserClient::Get()->RemoveBrowserInfo(browser_info_); + browser_info_->set_browser(NULL); +} + +gfx::NativeView CefBrowserHostImpl::GetContentView() const { + CEF_REQUIRE_UIT(); +#if defined(USE_AURA) + if (!window_widget_) + return NULL; + return window_widget_->GetNativeView(); +#else + if (!web_contents_.get()) + return NULL; + return web_contents_->GetNativeView(); +#endif +} + +void CefBrowserHostImpl::CancelContextMenu() { +#if defined(OS_LINUX) && defined(USE_AURA) + CEF_REQUIRE_UIT(); + // Special case for dismissing views-based context menus on Linux Aura + // when using windowless rendering. + if (IsWindowless() && menu_creator_) + menu_creator_->CancelContextMenu(); +#endif +} + +content::WebContents* CefBrowserHostImpl::GetWebContents() const { + CEF_REQUIRE_UIT(); + return web_contents_.get(); +} + +CefRefPtr CefBrowserHostImpl::GetFrameForRequest( + net::URLRequest* request) { + CEF_REQUIRE_IOT(); + const content::ResourceRequestInfo* info = + content::ResourceRequestInfo::ForRequest(request); + if (!info) + return NULL; + return GetOrCreateFrame(info->GetRenderFrameID(), + info->GetParentRenderFrameID(), + info->IsMainFrame(), + base::string16(), + GURL()); +} + +void CefBrowserHostImpl::Navigate(const CefNavigateParams& params) { + // Only known frame ids and kMainFrameId are supported. + DCHECK(params.frame_id >= CefFrameHostImpl::kMainFrameId); + + CefMsg_LoadRequest_Params request; + request.url = params.url; + if (!request.url.is_valid()) { + LOG(ERROR) << "Invalid URL passed to CefBrowserHostImpl::Navigate: " << + params.url; + return; + } + + request.method = params.method; + request.referrer = params.referrer.url; + request.referrer_policy = params.referrer.policy; + request.frame_id = params.frame_id; + request.first_party_for_cookies = params.first_party_for_cookies; + request.headers = params.headers; + request.load_flags = params.load_flags; + request.upload_data = params.upload_data; + + Send(new CefMsg_LoadRequest(routing_id(), request)); + + OnSetFocus(FOCUS_SOURCE_NAVIGATION); +} + +void CefBrowserHostImpl::LoadRequest(int64 frame_id, + CefRefPtr request) { + CefNavigateParams params(GURL(std::string(request->GetURL())), + ui::PAGE_TRANSITION_TYPED); + params.method = request->GetMethod(); + params.frame_id = frame_id; + params.first_party_for_cookies = + GURL(std::string(request->GetFirstPartyForCookies())); + + CefRequest::HeaderMap headerMap; + request->GetHeaderMap(headerMap); + if (!headerMap.empty()) + params.headers = HttpHeaderUtils::GenerateHeaders(headerMap); + + CefRefPtr postData = request->GetPostData(); + if (postData.get()) { + CefPostDataImpl* impl = static_cast(postData.get()); + params.upload_data = new net::UploadData(); + impl->Get(*params.upload_data.get()); + } + + params.load_flags = request->GetFlags(); + + Navigate(params); +} + +void CefBrowserHostImpl::LoadURL( + int64 frame_id, + const std::string& url, + const content::Referrer& referrer, + ui::PageTransition transition, + const std::string& extra_headers) { + if (frame_id == CefFrameHostImpl::kMainFrameId) { + // Go through the navigation controller. + if (CEF_CURRENTLY_ON_UIT()) { + if (web_contents_.get()) { + GURL gurl = GURL(url); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + std::string new_url = std::string("http://") + url; + gurl = GURL(new_url); + } + + if (!gurl.is_valid()) { + LOG(ERROR) << + "Invalid URL passed to CefBrowserHostImpl::LoadURL: " << url; + return; + } + + // Update the loading URL. + OnLoadingURLChange(gurl); + + web_contents_->GetController().LoadURL( + gurl, + referrer, + transition, + extra_headers); + OnSetFocus(FOCUS_SOURCE_NAVIGATION); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::LoadURL, this, frame_id, url, + referrer, transition, extra_headers)); + } + } else { + CefNavigateParams params(GURL(url), transition); + params.frame_id = frame_id; + params.referrer = referrer; + params.headers = extra_headers; + Navigate(params); + } +} + +void CefBrowserHostImpl::LoadString(int64 frame_id, const std::string& string, + const std::string& url) { + // Only known frame ids or kMainFrameId are supported. + DCHECK(frame_id >= CefFrameHostImpl::kMainFrameId); + + Cef_Request_Params params; + params.name = "load-string"; + params.frame_id = frame_id; + params.user_initiated = false; + params.request_id = -1; + params.expect_response = false; + + params.arguments.AppendString(string); + params.arguments.AppendString(url); + + Send(new CefMsg_Request(routing_id(), params)); +} + +void CefBrowserHostImpl::SendCommand( + int64 frame_id, + const std::string& command, + CefRefPtr responseHandler) { + // Only known frame ids are supported. + DCHECK(frame_id > CefFrameHostImpl::kMainFrameId); + DCHECK(!command.empty()); + + // Execute on the UI thread because CefResponseManager is not thread safe. + if (CEF_CURRENTLY_ON_UIT()) { + TRACE_EVENT2("libcef", "CefBrowserHostImpl::SendCommand", + "frame_id", frame_id, + "needsResponse", responseHandler.get() ? 1 : 0); + Cef_Request_Params params; + params.name = "execute-command"; + params.frame_id = frame_id; + params.user_initiated = false; + + if (responseHandler.get()) { + params.request_id = response_manager_->RegisterHandler(responseHandler); + params.expect_response = true; + } else { + params.request_id = -1; + params.expect_response = false; + } + + params.arguments.AppendString(command); + + Send(new CefMsg_Request(routing_id(), params)); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendCommand, this, frame_id, command, + responseHandler)); + } +} + +void CefBrowserHostImpl::SendCode( + int64 frame_id, + bool is_javascript, + const std::string& code, + const std::string& script_url, + int script_start_line, + CefRefPtr responseHandler) { + // Only known frame ids are supported. + DCHECK(frame_id >= CefFrameHostImpl::kMainFrameId); + DCHECK(!code.empty()); + DCHECK_GE(script_start_line, 0); + + // Execute on the UI thread because CefResponseManager is not thread safe. + if (CEF_CURRENTLY_ON_UIT()) { + TRACE_EVENT2("libcef", "CefBrowserHostImpl::SendCommand", + "frame_id", frame_id, + "needsResponse", responseHandler.get() ? 1 : 0); + Cef_Request_Params params; + params.name = "execute-code"; + params.frame_id = frame_id; + params.user_initiated = false; + + if (responseHandler.get()) { + params.request_id = response_manager_->RegisterHandler(responseHandler); + params.expect_response = true; + } else { + params.request_id = -1; + params.expect_response = false; + } + + params.arguments.AppendBoolean(is_javascript); + params.arguments.AppendString(code); + params.arguments.AppendString(script_url); + params.arguments.AppendInteger(script_start_line); + + Send(new CefMsg_Request(routing_id(), params)); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::SendCode, this, frame_id, is_javascript, + code, script_url, script_start_line, responseHandler)); + } +} + +bool CefBrowserHostImpl::SendProcessMessage(CefProcessId target_process, + const std::string& name, + base::ListValue* arguments, + bool user_initiated) { + DCHECK_EQ(PID_RENDERER, target_process); + DCHECK(!name.empty()); + + Cef_Request_Params params; + params.name = name; + if (arguments) + params.arguments.Swap(arguments); + params.frame_id = -1; + params.user_initiated = user_initiated; + params.request_id = -1; + params.expect_response = false; + + return Send(new CefMsg_Request(routing_id(), params)); +} + +bool CefBrowserHostImpl::ViewText(const std::string& text) { + return PlatformViewText(text); +} + +void CefBrowserHostImpl::HandleExternalProtocol(const GURL& url) { + if (CEF_CURRENTLY_ON_UIT()) { + bool allow_os_execution = false; + + if (client_.get()) { + CefRefPtr handler = client_->GetRequestHandler(); + if (handler.get()) + handler->OnProtocolExecution(this, url.spec(), allow_os_execution); + } + + if (allow_os_execution) + PlatformHandleExternalProtocol(url); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::HandleExternalProtocol, this, url)); + } +} + +int CefBrowserHostImpl::browser_id() const { + return browser_info_->browser_id(); +} + +GURL CefBrowserHostImpl::GetLoadingURL() { + base::AutoLock lock_scope(state_lock_); + return loading_url_; +} + +void CefBrowserHostImpl::OnSetFocus(cef_focus_source_t source) { + if (CEF_CURRENTLY_ON_UIT()) { + // SetFocus() might be called while inside the OnSetFocus() callback. If so, + // don't re-enter the callback. + if (!is_in_onsetfocus_) { + if (client_.get()) { + CefRefPtr handler = client_->GetFocusHandler(); + if (handler.get()) { + is_in_onsetfocus_ = true; + bool handled = handler->OnSetFocus(this, source); + is_in_onsetfocus_ = false; + + if (handled) + return; + } + } + } + + PlatformSetFocus(true); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::OnSetFocus, this, source)); + } +} + +void CefBrowserHostImpl::RunFileChooser( + const FileChooserParams& params, + const RunFileChooserCallback& callback) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::RunFileChooserOnUIThread, this, params, + callback)); +} + +void CefBrowserHostImpl::FindReply( + content::WebContents* web_contents, + int request_id, + int number_of_matches, + const gfx::Rect& selection_rect, + int active_match_ordinal, + bool final_update) { + if (client_.get()) { + CefRefPtr handler = client_->GetFindHandler(); + if (handler.get()) { + CefRect rect(selection_rect.x(), selection_rect.y(), + selection_rect.width(), selection_rect.height()); + handler->OnFindResult(this, request_id, number_of_matches, + rect, active_match_ordinal, final_update); + } + } +} + +#if !defined(OS_MACOSX) +CefTextInputContext CefBrowserHostImpl::GetNSTextInputContext() { + NOTREACHED(); + return NULL; +} + +void CefBrowserHostImpl::HandleKeyEventBeforeTextInputClient( + CefEventHandle keyEvent) { + NOTREACHED(); +} + +void CefBrowserHostImpl::HandleKeyEventAfterTextInputClient( + CefEventHandle keyEvent) { + NOTREACHED(); +} +#endif // !defined(OS_MACOSX) + +void CefBrowserHostImpl::DragTargetDragEnter(CefRefPtr drag_data, + const CefMouseEvent& event, + CefBrowserHost::DragOperationsMask allowed_ops) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::DragTargetDragEnter, this, drag_data, + event, allowed_ops)); + return; + } + + if (!drag_data.get()) { + NOTREACHED(); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + content::RenderViewHost* rvh = + web_contents() ? web_contents()->GetRenderViewHost() : NULL; + if (!rvh) + return; + + int screenX, screenY; + + if (!client_->GetRenderHandler()->GetScreenPoint( + this, event.x, event.y, screenX, screenY)) { + screenX = event.x; + screenY = event.y; + } + + CefDragDataImpl* data_impl = static_cast(drag_data.get()); + base::AutoLock lock_scope(data_impl->lock()); + const content::DropData& drop_data = data_impl->drop_data(); + gfx::Point client_pt(event.x, event.y); + gfx::Point screen_pt(screenX, screenY); + blink::WebDragOperationsMask ops = + static_cast(allowed_ops); + int modifiers = CefBrowserHostImpl::TranslateModifiers(event.modifiers); + + rvh->DragTargetDragEnter(drop_data, client_pt, screen_pt, ops, modifiers); +} + +void CefBrowserHostImpl::DragTargetDragOver(const CefMouseEvent& event, + CefBrowserHost::DragOperationsMask allowed_ops) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::DragTargetDragOver, this, event, + allowed_ops)); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + content::RenderViewHost* rvh = + web_contents() ? web_contents()->GetRenderViewHost() : NULL; + if (!rvh) + return; + + int screenX, screenY; + + if (!client_->GetRenderHandler()->GetScreenPoint( + this, event.x, event.y, screenX, screenY)) { + screenX = event.x; + screenY = event.y; + } + + gfx::Point client_pt(event.x, event.y); + gfx::Point screen_pt(screenX, screenY); + blink::WebDragOperationsMask ops = + static_cast(allowed_ops); + int modifiers = CefBrowserHostImpl::TranslateModifiers(event.modifiers); + + rvh->DragTargetDragOver(client_pt, screen_pt, ops, modifiers); +} + +void CefBrowserHostImpl::DragTargetDragLeave() { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::DragTargetDragLeave, this)); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + content::RenderViewHost* rvh = + web_contents() ? web_contents()->GetRenderViewHost() : NULL; + if (!rvh) + return; + + rvh->DragTargetDragLeave(); +} + +void CefBrowserHostImpl::DragTargetDrop(const CefMouseEvent& event) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::DragTargetDrop, this, event)); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + content::RenderViewHost* rvh = + web_contents() ? web_contents()->GetRenderViewHost() : NULL; + if (!rvh) + return; + + int screenX, screenY; + + if (!client_->GetRenderHandler()->GetScreenPoint( + this, event.x, event.y, screenX, screenY)) { + screenX = event.x; + screenY = event.y; + } + + gfx::Point client_pt(event.x, event.y); + gfx::Point screen_pt(screenX, screenY); + int modifiers = CefBrowserHostImpl::TranslateModifiers(event.modifiers); + + rvh->DragTargetDrop(client_pt, screen_pt, modifiers); +} + +void CefBrowserHostImpl::DragSourceSystemDragEnded() { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::DragSourceSystemDragEnded, this)); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + content::RenderViewHost* rvh = + web_contents() ? web_contents()->GetRenderViewHost() : NULL; + if (!rvh) + return; + + rvh->DragSourceSystemDragEnded(); +} + +void CefBrowserHostImpl::DragSourceEndedAt( + int x, int y, CefBrowserHost::DragOperationsMask op) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::DragSourceEndedAt, this, x, y, op)); + return; + } + + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + content::RenderViewHost* rvh = + web_contents() ? web_contents()->GetRenderViewHost() : NULL; + if (!rvh) + return; + + int screenX, screenY; + + if (!client_->GetRenderHandler()->GetScreenPoint( + this, x, y, screenX, screenY)) { + screenX = x; + screenY = y; + } + + blink::WebDragOperation drag_op = static_cast(op); + + rvh->DragSourceEndedAt(x, y, screenX, screenY, drag_op); +} + + +// content::WebContentsDelegate methods. +// ----------------------------------------------------------------------------- + +content::WebContents* CefBrowserHostImpl::OpenURLFromTab( + content::WebContents* source, + const content::OpenURLParams& params) { + // Start a navigation that will result in the creation of a new render + // process. + LoadURL(CefFrameHostImpl::kMainFrameId, params.url.spec(), params.referrer, + params.transition, params.extra_headers); + + return source; +} + +void CefBrowserHostImpl::LoadingStateChanged(content::WebContents* source, + bool to_different_document) { + int current_index = + web_contents_->GetController().GetLastCommittedEntryIndex(); + int max_index = web_contents_->GetController().GetEntryCount() - 1; + + bool is_loading, can_go_back, can_go_forward; + + { + base::AutoLock lock_scope(state_lock_); + is_loading = is_loading_ = web_contents_->IsLoading(); + can_go_back = can_go_back_ = (current_index > 0); + can_go_forward = can_go_forward_ = (current_index < max_index); + } + + if (client_.get()) { + CefRefPtr handler = client_->GetLoadHandler(); + if (handler.get()) { + handler->OnLoadingStateChange(this, is_loading, can_go_back, + can_go_forward); + } + } +} + +void CefBrowserHostImpl::CloseContents(content::WebContents* source) { + if (destruction_state_ == DESTRUCTION_STATE_COMPLETED) + return; + + bool close_browser = true; + + // If this method is called in response to something other than + // WindowDestroyed() ask the user if the browser should close. + if (client_.get() && (IsWindowless() || !window_destroyed_)) { + CefRefPtr handler = + client_->GetLifeSpanHandler(); + if (handler.get()) { + close_browser = !handler->DoClose(this); + } + } + + if (close_browser) { + if (destruction_state_ != DESTRUCTION_STATE_ACCEPTED) + destruction_state_ = DESTRUCTION_STATE_ACCEPTED; + + if (!IsWindowless() && !window_destroyed_) { + // A window exists so try to close it using the platform method. Will + // result in a call to WindowDestroyed() if/when the window is destroyed + // via the platform window destruction mechanism. + PlatformCloseWindow(); + } else { + // Keep a reference to the browser while it's in the process of being + // destroyed. + CefRefPtr browser(this); + + // No window exists. Destroy the browser immediately. + DestroyBrowser(); + if (!IsWindowless()) { + // Release the reference added in PlatformCreateWindow(). + Release(); + } + } + } else if (destruction_state_ != DESTRUCTION_STATE_NONE) { + destruction_state_ = DESTRUCTION_STATE_NONE; + } +} + +void CefBrowserHostImpl::UpdateTargetURL(content::WebContents* source, + const GURL& url) { + if (client_.get()) { + CefRefPtr handler = client_->GetDisplayHandler(); + if (handler.get()) + handler->OnStatusMessage(this, url.spec()); + } +} + +bool CefBrowserHostImpl::AddMessageToConsole(content::WebContents* source, + int32 level, + const base::string16& message, + int32 line_no, + const base::string16& source_id) { + if (client_.get()) { + CefRefPtr handler = client_->GetDisplayHandler(); + if (handler.get()) + return handler->OnConsoleMessage(this, message, source_id, line_no); + } + + return false; +} + +void CefBrowserHostImpl::BeforeUnloadFired(content::WebContents* source, + bool proceed, + bool* proceed_to_fire_unload) { + if (destruction_state_ == DESTRUCTION_STATE_ACCEPTED || proceed) { + *proceed_to_fire_unload = true; + } else if (!proceed) { + *proceed_to_fire_unload = false; + destruction_state_ = DESTRUCTION_STATE_NONE; + } +} + +bool CefBrowserHostImpl::TakeFocus(content::WebContents* source, + bool reverse) { + if (client_.get()) { + CefRefPtr handler = client_->GetFocusHandler(); + if (handler.get()) + handler->OnTakeFocus(this, !reverse); + } + + return false; +} + +void CefBrowserHostImpl::WebContentsFocused(content::WebContents* contents) { + if (client_.get()) { + CefRefPtr handler = client_->GetFocusHandler(); + if (handler.get()) + handler->OnGotFocus(this); + } +} + +bool CefBrowserHostImpl::HandleContextMenu( + const content::ContextMenuParams& params) { + if (!menu_creator_.get()) + menu_creator_.reset(new CefMenuCreator(this)); + return menu_creator_->CreateContextMenu(params); +} + +bool CefBrowserHostImpl::PreHandleKeyboardEvent( + content::WebContents* source, + const content::NativeWebKeyboardEvent& event, + bool* is_keyboard_shortcut) { + if (client_.get()) { + CefRefPtr handler = client_->GetKeyboardHandler(); + if (handler.get()) { + CefKeyEvent cef_event; + if (!GetCefKeyEvent(event, cef_event)) + return false; + + cef_event.focus_on_editable_field = focus_on_editable_field_; + + return handler->OnPreKeyEvent(this, cef_event, GetCefEventHandle(event), + is_keyboard_shortcut); + } + } + + return false; +} + +void CefBrowserHostImpl::HandleKeyboardEvent( + content::WebContents* source, + const content::NativeWebKeyboardEvent& event) { + // Check to see if event should be ignored. + if (event.skip_in_browser) + return; + + if (client_.get()) { + CefRefPtr handler = client_->GetKeyboardHandler(); + if (handler.get()) { + CefKeyEvent cef_event; + if (GetCefKeyEvent(event, cef_event)) { + cef_event.focus_on_editable_field = focus_on_editable_field_; + + if (handler->OnKeyEvent(this, cef_event, GetCefEventHandle(event))) + return; + } + } + } + + PlatformHandleKeyboardEvent(event); +} + +bool CefBrowserHostImpl::CanDragEnter( + content::WebContents* source, + const content::DropData& data, + blink::WebDragOperationsMask mask) { + CefRefPtr handler = client_->GetDragHandler(); + if (handler.get()) { + CefRefPtr drag_data(new CefDragDataImpl(data)); + drag_data->SetReadOnly(true); + if (handler->OnDragEnter( + this, + drag_data.get(), + static_cast(mask))) { + return false; + } + } + return true; +} + +bool CefBrowserHostImpl::ShouldCreateWebContents( + content::WebContents* web_contents, + int route_id, + int main_frame_route_id, + WindowContainerType window_container_type, + const base::string16& frame_name, + const GURL& target_url, + const std::string& partition_id, + content::SessionStorageNamespace* session_storage_namespace, + content::WebContentsView** view, + content::RenderViewHostDelegateView** delegate_view) { + // In cases where the navigation will occur in a new render process the + // |route_id| value will be MSG_ROUTING_NONE here (because the existing + // renderer will not be able to communicate with the new renderer) and + // OpenURLFromTab will be called after WebContentsCreated. + base::AutoLock lock_scope(pending_popup_info_lock_); + DCHECK(pending_popup_info_.get()); + if (pending_popup_info_->window_info.windowless_rendering_enabled) { + // Use the OSR view instead of the default view. + CefWebContentsViewOSR* view_or = new CefWebContentsViewOSR(); + view_or->set_web_contents(web_contents); + *view = view_or; + *delegate_view = view_or; + } + + return true; +} + +void CefBrowserHostImpl::WebContentsCreated( + content::WebContents* source_contents, + int opener_render_frame_id, + const base::string16& frame_name, + const GURL& target_url, + content::WebContents* new_contents) { + scoped_ptr pending_popup_info; + { + base::AutoLock lock_scope(pending_popup_info_lock_); + pending_popup_info.reset(pending_popup_info_.release()); + } + DCHECK(pending_popup_info.get()); + + content::RenderViewHost* view_host = new_contents->GetRenderViewHost(); + content::RenderFrameHost* main_frame_host = new_contents->GetMainFrame(); + + CefWindowHandle opener = kNullWindowHandle; + scoped_refptr info = + CefContentBrowserClient::Get()->GetOrCreateBrowserInfo( + view_host->GetProcess()->GetID(), + view_host->GetRoutingID(), + main_frame_host->GetProcess()->GetID(), + main_frame_host->GetRoutingID()); + + if (source_contents) { + DCHECK(info->is_popup()); + opener = GetBrowserForContents(source_contents)->GetWindowHandle(); + } else { + DCHECK(!info->is_popup()); + } + + CefRefPtr browser = + CefBrowserHostImpl::CreateInternal(pending_popup_info->window_info, + pending_popup_info->settings, + pending_popup_info->client, + new_contents, info, opener, NULL); +} + +void CefBrowserHostImpl::DidNavigateMainFramePostCommit( + content::WebContents* web_contents) { + base::AutoLock lock_scope(state_lock_); + has_document_ = false; +} + +content::JavaScriptDialogManager* + CefBrowserHostImpl::GetJavaScriptDialogManager( + content::WebContents* source) { + if (!dialog_manager_.get()) + dialog_manager_.reset(new CefJavaScriptDialogManager(this)); + return dialog_manager_.get(); +} + +void CefBrowserHostImpl::RunFileChooser( + content::WebContents* web_contents, + const content::FileChooserParams& params) { + content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); + if (!render_view_host) + return; + + if (params.mode == content::FileChooserParams::UploadFolder) { + // TODO(cef): Implement the logic necessary for the 'webkitdirectory' + // attribute. See CEF issue #958. + OnRunFileChooserDelegateCallback( + web_contents, params.mode, 0, std::vector()); + return; + } + + FileChooserParams cef_params; + static_cast(cef_params) = params; + RunFileChooserOnUIThread(cef_params, + base::Bind(&CefBrowserHostImpl::OnRunFileChooserDelegateCallback, this, + web_contents, params.mode)); +} + +bool CefBrowserHostImpl::SetPendingPopupInfo( + scoped_ptr info) { + base::AutoLock lock_scope(pending_popup_info_lock_); + if (pending_popup_info_.get()) + return false; + pending_popup_info_.reset(info.release()); + return true; +} + +void CefBrowserHostImpl::UpdatePreferredSize(content::WebContents* source, + const gfx::Size& pref_size) { + PlatformSizeTo(pref_size.width(), pref_size.height()); +} + +void CefBrowserHostImpl::RequestMediaAccessPermission( + content::WebContents* web_contents, + const content::MediaStreamRequest& request, + const content::MediaResponseCallback& callback) { + CEF_REQUIRE_UIT(); + + content::MediaStreamDevices devices; + + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (!command_line->HasSwitch(switches::kEnableMediaStream)) { + // Cancel the request. + callback.Run(devices, content::MEDIA_DEVICE_PERMISSION_DENIED, + scoped_ptr()); + return; + } + + // Based on chrome/browser/media/media_stream_devices_controller.cc + bool microphone_requested = + (request.audio_type == content::MEDIA_DEVICE_AUDIO_CAPTURE); + bool webcam_requested = + (request.video_type == content::MEDIA_DEVICE_VIDEO_CAPTURE); + if (microphone_requested || webcam_requested) { + switch (request.request_type) { + case content::MEDIA_OPEN_DEVICE: + // For open device request pick the desired device or fall back to the + // first available of the given type. + CefMediaCaptureDevicesDispatcher::GetInstance()->GetRequestedDevice( + (microphone_requested ? request.requested_audio_device_id : + request.requested_video_device_id), + microphone_requested, + webcam_requested, + &devices); + break; + case content::MEDIA_DEVICE_ACCESS: + case content::MEDIA_GENERATE_STREAM: + case content::MEDIA_ENUMERATE_DEVICES: + // Get the default devices for the request. + CefMediaCaptureDevicesDispatcher::GetInstance()-> + GetDefaultDevices(CefContentBrowserClient::Get()->pref_service(), + microphone_requested, + webcam_requested, + &devices); + break; + } + } + + callback.Run(devices, content::MEDIA_DEVICE_OK, + scoped_ptr()); +} + + +// content::WebContentsObserver methods. +// ----------------------------------------------------------------------------- + +void CefBrowserHostImpl::RenderFrameCreated( + content::RenderFrameHost* render_frame_host) { + browser_info_->add_render_frame_id(render_frame_host->GetProcess()->GetID(), + render_frame_host->GetRoutingID()); +} + +void CefBrowserHostImpl::RenderFrameDeleted( + content::RenderFrameHost* render_frame_host) { + browser_info_->remove_render_frame_id( + render_frame_host->GetProcess()->GetID(), + render_frame_host->GetRoutingID()); +} + +void CefBrowserHostImpl::RenderViewCreated( + content::RenderViewHost* render_view_host) { + browser_info_->add_render_view_id(render_view_host->GetProcess()->GetID(), + render_view_host->GetRoutingID()); + + // May be already registered if the renderer crashed previously. + if (!registrar_->IsRegistered( + this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, + content::Source(render_view_host))) { + registrar_->Add(this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, + content::Source(render_view_host)); + } +} + +void CefBrowserHostImpl::RenderViewDeleted( + content::RenderViewHost* render_view_host) { + browser_info_->remove_render_view_id(render_view_host->GetProcess()->GetID(), + render_view_host->GetRoutingID()); + + if (registrar_->IsRegistered( + this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, + content::Source(render_view_host))) { + registrar_->Remove(this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, + content::Source(render_view_host)); + } +} + +void CefBrowserHostImpl::RenderViewReady() { + // Send the queued messages. + queue_messages_ = false; + while (!queued_messages_.empty()) { + Send(queued_messages_.front()); + queued_messages_.pop(); + } +} + +void CefBrowserHostImpl::RenderProcessGone(base::TerminationStatus status) { + queue_messages_ = true; + + cef_termination_status_t ts = TS_ABNORMAL_TERMINATION; + if (status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED) + ts = TS_PROCESS_WAS_KILLED; + else if (status == base::TERMINATION_STATUS_PROCESS_CRASHED) + ts = TS_PROCESS_CRASHED; + else if (status != base::TERMINATION_STATUS_ABNORMAL_TERMINATION) + return; + + if (client_.get()) { + CefRefPtr handler = client_->GetRequestHandler(); + if (handler.get()) + handler->OnRenderProcessTerminated(this, ts); + } +} + +void CefBrowserHostImpl::DidCommitProvisionalLoadForFrame( + content::RenderFrameHost* render_frame_host, + const GURL& url, + ui::PageTransition transition_type) { + const bool is_main_frame = !render_frame_host->GetParent(); + CefRefPtr frame = GetOrCreateFrame( + render_frame_host->GetRoutingID(), + CefFrameHostImpl::kUnspecifiedFrameId, + is_main_frame, + base::string16(), + url); + OnLoadStart(frame, url, transition_type); + if (is_main_frame) + OnAddressChange(frame, url); +} + +void CefBrowserHostImpl::DidFailProvisionalLoad( + content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + int error_code, + const base::string16& error_description) { + const bool is_main_frame = !render_frame_host->GetParent(); + CefRefPtr frame = GetOrCreateFrame( + render_frame_host->GetRoutingID(), + CefFrameHostImpl::kUnspecifiedFrameId, + is_main_frame, + base::string16(), + GURL()); + OnLoadError(frame, validated_url, error_code, error_description); +} + +void CefBrowserHostImpl::DocumentAvailableInMainFrame() { + base::AutoLock lock_scope(state_lock_); + has_document_ = true; +} + +void CefBrowserHostImpl::DidFailLoad( + content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + int error_code, + const base::string16& error_description) { + const bool is_main_frame = !render_frame_host->GetParent(); + CefRefPtr frame = GetOrCreateFrame( + render_frame_host->GetRoutingID(), + CefFrameHostImpl::kUnspecifiedFrameId, + is_main_frame, + base::string16(), + validated_url); + OnLoadError(frame, validated_url, error_code, error_description); + OnLoadEnd(frame, validated_url, error_code); +} + +void CefBrowserHostImpl::FrameDetached( + content::RenderFrameHost* render_frame_host) { + base::AutoLock lock_scope(state_lock_); + + const int64 frame_id = render_frame_host->GetRoutingID(); + FrameMap::iterator it = frames_.find(frame_id); + if (it != frames_.end()) { + it->second->Detach(); + frames_.erase(it); + } + + if (main_frame_id_ == frame_id) + main_frame_id_ = CefFrameHostImpl::kInvalidFrameId; + if (focused_frame_id_ == frame_id) + focused_frame_id_ = CefFrameHostImpl::kInvalidFrameId; +} + +void CefBrowserHostImpl::PluginCrashed(const base::FilePath& plugin_path, + base::ProcessId plugin_pid) { + if (client_.get()) { + CefRefPtr handler = client_->GetRequestHandler(); + if (handler.get()) + handler->OnPluginCrashed(this, plugin_path.value()); + } +} + +void CefBrowserHostImpl::DidUpdateFaviconURL( + const std::vector& candidates) { + if (client_.get()) { + CefRefPtr handler = client_->GetDisplayHandler(); + if (handler.get()) { + std::vector icon_urls; + std::vector::const_iterator it = + candidates.begin(); + for (; it != candidates.end(); ++it) + icon_urls.push_back(it->icon_url.spec()); + handler->OnFaviconURLChange(this, icon_urls); + } + } +} + +bool CefBrowserHostImpl::OnMessageReceived(const IPC::Message& message) { + // Handle the cursor message here if mouse cursor change is disabled instead + // of propegating the message to the normal handler. + if (message.type() == ViewHostMsg_SetCursor::ID) + return IsMouseCursorChangeDisabled(); + + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(CefBrowserHostImpl, message) + IPC_MESSAGE_HANDLER(CefHostMsg_FrameIdentified, OnFrameIdentified) + IPC_MESSAGE_HANDLER(CefHostMsg_DidFinishLoad, OnDidFinishLoad) + IPC_MESSAGE_HANDLER(CefHostMsg_LoadingURLChange, OnLoadingURLChange) + IPC_MESSAGE_HANDLER(CefHostMsg_Request, OnRequest) + IPC_MESSAGE_HANDLER(CefHostMsg_Response, OnResponse) + IPC_MESSAGE_HANDLER(CefHostMsg_ResponseAck, OnResponseAck) + IPC_MESSAGE_HANDLER(PDFHostMsg_PDFHasUnsupportedFeature, + OnPDFHasUnsupportedFeature) + IPC_MESSAGE_HANDLER(PDFHostMsg_PDFSaveURLAs, OnPDFSaveURLAs) + IPC_MESSAGE_HANDLER(PDFHostMsg_PDFUpdateContentRestrictions, + OnPDFUpdateContentRestrictions) + IPC_MESSAGE_HANDLER_DELAY_REPLY(PDFHostMsg_PDFModalPromptForPassword, + OnPDFModalPromptForPassword) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +bool CefBrowserHostImpl::Send(IPC::Message* message) { + if (CEF_CURRENTLY_ON_UIT()) { + if (queue_messages_) { + queued_messages_.push(message); + return true; + } else { + return content::WebContentsObserver::Send(message); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(base::IgnoreResult(&CefBrowserHostImpl::Send), this, + message)); + return true; + } +} + + +// content::WebContentsObserver::OnMessageReceived() message handlers. +// ----------------------------------------------------------------------------- + +void CefBrowserHostImpl::OnFrameIdentified(int64 frame_id, + int64 parent_frame_id, + base::string16 name) { + bool is_main_frame = (parent_frame_id == CefFrameHostImpl::kMainFrameId); + GetOrCreateFrame(frame_id, parent_frame_id, is_main_frame, name, GURL()); +} + +void CefBrowserHostImpl::OnDidFinishLoad(int64 frame_id, + const GURL& validated_url, + bool is_main_frame, + int http_status_code) { + CefRefPtr frame = GetOrCreateFrame(frame_id, + CefFrameHostImpl::kUnspecifiedFrameId, is_main_frame, base::string16(), + validated_url); + + // Give internal scheme handlers an opportunity to update content. + scheme::DidFinishLoad(frame, validated_url); + + OnLoadEnd(frame, validated_url, http_status_code); +} + +void CefBrowserHostImpl::OnLoadingURLChange(const GURL& loading_url) { + base::AutoLock lock_scope(state_lock_); + loading_url_ = loading_url; +} + +void CefBrowserHostImpl::OnRequest(const Cef_Request_Params& params) { + bool success = false; + std::string response; + bool expect_response_ack = false; + + if (params.user_initiated) { + // Give the user a chance to handle the request. + if (client_.get()) { + CefRefPtr message( + new CefProcessMessageImpl(const_cast(¶ms), + false, true)); + success = client_->OnProcessMessageReceived(this, PID_RENDERER, + message.get()); + message->Detach(NULL); + } + } else { + // Invalid request. + NOTREACHED(); + } + + if (params.expect_response) { + DCHECK_GE(params.request_id, 0); + + // Send a response to the renderer. + Cef_Response_Params response_params; + response_params.request_id = params.request_id; + response_params.success = success; + response_params.response = response; + response_params.expect_response_ack = expect_response_ack; + Send(new CefMsg_Response(routing_id(), response_params)); + } +} + +void CefBrowserHostImpl::OnResponse(const Cef_Response_Params& params) { + response_manager_->RunHandler(params); + if (params.expect_response_ack) + Send(new CefMsg_ResponseAck(routing_id(), params.request_id)); +} + +void CefBrowserHostImpl::OnResponseAck(int request_id) { + response_manager_->RunAckHandler(request_id); +} + +void CefBrowserHostImpl::OnPDFHasUnsupportedFeature() { + // TODO(cef): Use Adobe PDF plugin instead. See PDFHasUnsupportedFeature in + // chrome/browser/ui/pdf/pdf_unsupported_feature.cc. +} + +void CefBrowserHostImpl::OnPDFSaveURLAs( + const GURL& url, + const content::Referrer& referrer) { + web_contents()->SaveFrame(url, referrer); +} + +void CefBrowserHostImpl::OnPDFUpdateContentRestrictions( + int content_restrictions) { + // TODO(cef): Add support for communicating PDF content restrictions. +} + +void CefBrowserHostImpl::OnPDFModalPromptForPassword( + const std::string& prompt, + IPC::Message* reply_message) { + // TODO(cef): Add support for PDF password prompt. + OnPDFModalPromptForPasswordClosed(reply_message, false, base::string16()); +} + +void CefBrowserHostImpl::OnPDFModalPromptForPasswordClosed( + IPC::Message* reply_message, + bool success, + const base::string16& actual_value) { + PDFHostMsg_PDFModalPromptForPassword::WriteReplyParams( + reply_message, base::UTF16ToUTF8(actual_value)); + Send(reply_message); +} + + +// content::NotificationObserver methods. +// ----------------------------------------------------------------------------- + +void CefBrowserHostImpl::Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + DCHECK(type == content::NOTIFICATION_LOAD_STOP || + type == content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE || + type == content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED); + + if (type == content::NOTIFICATION_LOAD_STOP || + type == content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) { + base::string16 title; + + if (type == content::NOTIFICATION_LOAD_STOP) { + content::NavigationController* controller = + content::Source(source).ptr(); + title = controller->GetWebContents()->GetTitle(); + } else { + content::WebContents* web_contents = + content::Source(source).ptr(); + title = web_contents->GetTitle(); + } + + if (client_.get()) { + CefRefPtr handler = client_->GetDisplayHandler(); + if (handler.get()) + handler->OnTitleChange(this, title); + } + } else if (type == content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE) { + focus_on_editable_field_ = *content::Details(details).ptr(); + } +} + + +// CefBrowserHostImpl private methods. +// ----------------------------------------------------------------------------- + +CefBrowserHostImpl::CefBrowserHostImpl( + const CefWindowInfo& window_info, + const CefBrowserSettings& settings, + CefRefPtr client, + content::WebContents* web_contents, + scoped_refptr browser_info, + CefWindowHandle opener) + : content::WebContentsObserver(web_contents), + window_info_(window_info), + settings_(settings), + client_(client), + browser_info_(browser_info), + opener_(opener), + is_loading_(false), + can_go_back_(false), + can_go_forward_(false), + has_document_(false), + queue_messages_(true), + main_frame_id_(CefFrameHostImpl::kInvalidFrameId), + focused_frame_id_(CefFrameHostImpl::kInvalidFrameId), + destruction_state_(DESTRUCTION_STATE_NONE), + window_destroyed_(false), + is_in_onsetfocus_(false), + focus_on_editable_field_(false), + mouse_cursor_change_disabled_(false), + devtools_frontend_(NULL), + file_chooser_pending_(false) { +#if defined(USE_AURA) + window_widget_ = NULL; +#endif +#if defined(USE_X11) + window_x11_ = NULL; +#endif + + DCHECK(!browser_info_->browser().get()); + browser_info_->set_browser(this); + + web_contents_.reset(web_contents); + web_contents->SetDelegate(this); + + CefBrowserContext* browser_context = + static_cast(web_contents->GetBrowserContext()); + request_context_ = new CefRequestContextImpl(browser_context); + + registrar_.reset(new content::NotificationRegistrar); + registrar_->Add(this, content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED, + content::Source(web_contents)); + + // When navigating through the history, the restored NavigationEntry's title + // will be used. If the entry ends up having the same title after we return + // to it, as will usually be the case, the + // NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED will then be suppressed, since the + // NavigationEntry's title hasn't changed. + registrar_->Add(this, content::NOTIFICATION_LOAD_STOP, + content::Source( + &web_contents->GetController())); + + response_manager_.reset(new CefResponseManager); + + placeholder_frame_ = + new CefFrameHostImpl(this, CefFrameHostImpl::kInvalidFrameId, true, + CefString(), CefString(), + CefFrameHostImpl::kInvalidFrameId); + + printing::PrintViewManager::CreateForWebContents(web_contents_.get()); + + // Make sure RenderViewCreated is called at least one time. + RenderViewCreated(web_contents->GetRenderViewHost()); + + if (IsWindowless()) { + CefRenderWidgetHostViewOSR* view = + static_cast( + web_contents->GetRenderViewHost()->GetView()); + if (view) + view->set_browser_impl(this); + } +} + +CefRefPtr CefBrowserHostImpl::GetOrCreateFrame( + int64 frame_id, int64 parent_frame_id, bool is_main_frame, + base::string16 frame_name, const GURL& frame_url) { + DCHECK(frame_id > CefFrameHostImpl::kInvalidFrameId); + if (frame_id <= CefFrameHostImpl::kInvalidFrameId) + return NULL; + + CefString url; + if (frame_url.is_valid()) + url = frame_url.spec(); + + CefString name; + if (!frame_name.empty()) + name = frame_name; + + CefRefPtr frame; + bool frame_created = false; + + { + base::AutoLock lock_scope(state_lock_); + + if (is_main_frame) + main_frame_id_ = frame_id; + + // Check if a frame object already exists. + FrameMap::const_iterator it = frames_.find(frame_id); + if (it != frames_.end()) + frame = it->second.get(); + + if (!frame.get()) { + frame = new CefFrameHostImpl(this, frame_id, is_main_frame, url, name, + parent_frame_id); + frame_created = true; + frames_.insert(std::make_pair(frame_id, frame)); + } + } + + if (!frame_created) + frame->SetAttributes(url, name, parent_frame_id); + + return frame.get(); +} + +void CefBrowserHostImpl::DetachAllFrames() { + FrameMap frames; + + { + base::AutoLock lock_scope(state_lock_); + + frames = frames_; + frames_.clear(); + + if (main_frame_id_ != CefFrameHostImpl::kInvalidFrameId) + main_frame_id_ = CefFrameHostImpl::kInvalidFrameId; + if (focused_frame_id_ != CefFrameHostImpl::kInvalidFrameId) + focused_frame_id_ = CefFrameHostImpl::kInvalidFrameId; + } + + FrameMap::const_iterator it = frames.begin(); + for (; it != frames.end(); ++it) + it->second->Detach(); +} + +void CefBrowserHostImpl::SetFocusedFrame(int64 frame_id) { + CefRefPtr unfocused_frame; + CefRefPtr focused_frame; + + { + base::AutoLock lock_scope(state_lock_); + + if (focused_frame_id_ != CefFrameHostImpl::kInvalidFrameId) { + // Unfocus the previously focused frame. + FrameMap::const_iterator it = frames_.find(frame_id); + if (it != frames_.end()) + unfocused_frame = it->second; + } + + if (frame_id != CefFrameHostImpl::kInvalidFrameId) { + // Focus the newly focused frame. + FrameMap::iterator it = frames_.find(frame_id); + if (it != frames_.end()) + focused_frame = it->second; + } + + focused_frame_id_ = + focused_frame.get() ? frame_id : CefFrameHostImpl::kInvalidFrameId; + } + + if (unfocused_frame.get()) + unfocused_frame->SetFocused(false); + if (focused_frame.get()) + focused_frame->SetFocused(true); +} + +void CefBrowserHostImpl::OnAddressChange(CefRefPtr frame, + const GURL& url) { + if (client_.get()) { + CefRefPtr handler = client_->GetDisplayHandler(); + if (handler.get()) { + // Notify the handler of an address change. + handler->OnAddressChange(this, GetMainFrame(), url.spec()); + } + } +} + +void CefBrowserHostImpl::OnLoadStart(CefRefPtr frame, + const GURL& url, + ui::PageTransition transition_type) { + if (client_.get()) { + CefRefPtr handler = client_->GetLoadHandler(); + if (handler.get()) { + // Notify the handler that loading has started. + handler->OnLoadStart(this, frame); + } + } +} + +void CefBrowserHostImpl::OnLoadError(CefRefPtr frame, + const GURL& url, + int error_code, + const base::string16& error_description) { + if (client_.get()) { + CefRefPtr handler = client_->GetLoadHandler(); + if (handler.get()) { + // Notify the handler that loading has failed. + handler->OnLoadError(this, frame, + static_cast(error_code), + CefString(error_description), + url.spec()); + } + } +} + +void CefBrowserHostImpl::OnLoadEnd(CefRefPtr frame, + const GURL& url, + int http_status_code) { + if (client_.get()) { + CefRefPtr handler = client_->GetLoadHandler(); + if (handler.get()) + handler->OnLoadEnd(this, frame, http_status_code); + } +} + +void CefBrowserHostImpl::RunFileChooserOnUIThread( + const FileChooserParams& params, + const RunFileChooserCallback& callback) { + CEF_REQUIRE_UIT(); + + if (file_chooser_pending_) { + // Dismiss the new dialog immediately. + callback.Run(0, std::vector()); + return; + } + + file_chooser_pending_ = true; + + // Ensure that the |file_chooser_pending_| flag is cleared. + const RunFileChooserCallback& host_callback = + base::Bind(&CefBrowserHostImpl::OnRunFileChooserCallback, this, callback); + + bool handled = false; + + if (client_.get()) { + CefRefPtr handler = client_->GetDialogHandler(); + if (handler.get()) { + int mode = FILE_DIALOG_OPEN; + switch (params.mode) { + case content::FileChooserParams::Open: + mode = FILE_DIALOG_OPEN; + break; + case content::FileChooserParams::OpenMultiple: + mode = FILE_DIALOG_OPEN_MULTIPLE; + break; + case content::FileChooserParams::UploadFolder: + mode = FILE_DIALOG_OPEN_FOLDER; + break; + case content::FileChooserParams::Save: + mode = FILE_DIALOG_SAVE; + break; + default: + NOTREACHED(); + break; + } + + if (params.overwriteprompt) + mode |= FILE_DIALOG_OVERWRITEPROMPT_FLAG; + if (params.hidereadonly) + mode |= FILE_DIALOG_HIDEREADONLY_FLAG; + + std::vector::const_iterator it; + + std::vector accept_filters; + it = params.accept_types.begin(); + for (; it != params.accept_types.end(); ++it) + accept_filters.push_back(*it); + + CefRefPtr callbackImpl( + new CefFileDialogCallbackImpl(host_callback)); + handled = handler->OnFileDialog( + this, + static_cast(mode), + params.title, + params.default_file_name.value(), + accept_filters, + params.selected_accept_filter, + callbackImpl.get()); + if (!handled) { + if (callbackImpl->IsConnected()) { + callbackImpl->Disconnect(); + } else { + // User executed the callback even though they returned false. + NOTREACHED(); + handled = true; + } + } + } + } + + if (!handled) + PlatformRunFileChooser(params, host_callback); +} + +void CefBrowserHostImpl::OnRunFileChooserCallback( + const RunFileChooserCallback& callback, + int selected_accept_filter, + const std::vector& file_paths) { + CEF_REQUIRE_UIT(); + + file_chooser_pending_ = false; + + // Execute the callback asynchronously. + CEF_POST_TASK(CEF_UIT, + base::Bind(callback, selected_accept_filter, file_paths)); +} + +void CefBrowserHostImpl::OnRunFileChooserDelegateCallback( + content::WebContents* web_contents, + content::FileChooserParams::Mode mode, + int selected_accept_filter, + const std::vector& file_paths) { + CEF_REQUIRE_UIT(); + + content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); + if (!render_view_host) + return; + + // Convert FilePath list to SelectedFileInfo list. + std::vector selected_files; + for (size_t i = 0; i < file_paths.size(); ++i) { + content::FileChooserFileInfo info; + info.file_path = file_paths[i]; + selected_files.push_back(info); + } + + // Notify our RenderViewHost in all cases. + render_view_host->FilesSelectedInChooser(selected_files, mode); +} + +void CefBrowserHostImpl::OnDevToolsWebContentsDestroyed() { + devtools_observer_.reset(); + devtools_frontend_ = NULL; +} diff --git a/libcef/browser/browser_host_impl.h b/libcef/browser/browser_host_impl.h new file mode 100644 index 000000000..630fda3d7 --- /dev/null +++ b/libcef/browser/browser_host_impl.h @@ -0,0 +1,690 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_HOST_IMPL_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_HOST_IMPL_H_ +#pragma once + +#include +#include +#include +#include + +#include "include/cef_browser.h" +#include "include/cef_client.h" +#include "include/cef_frame.h" +#include "libcef/browser/frame_host_impl.h" +#include "libcef/browser/javascript_dialog_manager.h" +#include "libcef/browser/menu_creator.h" +#include "libcef/common/response_manager.h" + +#include "base/memory/scoped_ptr.h" +#include "base/strings/string16.h" +#include "base/synchronization/lock.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_delegate.h" +#include "content/public/browser/web_contents_observer.h" +#include "content/public/common/file_chooser_params.h" + +#if defined(USE_AURA) +#include "third_party/WebKit/public/platform/WebCursorInfo.h" +#include "ui/base/cursor/cursor.h" +#endif + +#if defined(USE_X11) +#include "ui/base/x/x11_util.h" +#endif + +namespace content { +struct NativeWebKeyboardEvent; +} + +namespace blink { +class WebMouseEvent; +class WebMouseWheelEvent; +class WebInputEvent; +} + +namespace net { +class URLRequest; +} + +#if defined(USE_AURA) +namespace views { +class Widget; +} +#endif + +#if defined(USE_X11) +class CefWindowX11; +#endif + +struct Cef_Request_Params; +struct Cef_Response_Params; +class CefBrowserInfo; +class CefDevToolsFrontend; +struct CefNavigateParams; +class SiteInstance; + +// Implementation of CefBrowser. +// +// WebContentsDelegate: Interface for handling WebContents delegations. There is +// a one-to-one relationship between CefBrowserHostImpl and WebContents +// instances. +// +// WebContentsObserver: Interface for observing WebContents notifications and +// IPC messages. There is a one-to-one relationship between WebContents and +// RenderViewHost instances. IPC messages received by the RenderViewHost will be +// forwarded to this WebContentsObserver implementation via WebContents. IPC +// messages sent using CefBrowserHostImpl::Send() will be forwarded to the +// RenderViewHost (after posting to the UI thread if necessary). Use +// WebContentsObserver::routing_id() when sending IPC messages. +// +// NotificationObserver: Interface for observing post-processed notifications. +class CefBrowserHostImpl : public CefBrowserHost, + public CefBrowser, + public content::WebContentsDelegate, + public content::WebContentsObserver, + public content::NotificationObserver { + public: + // Used for handling the response to command messages. + class CommandResponseHandler : public virtual CefBase { + public: + virtual void OnResponse(const std::string& response) =0; + }; + + // Extend content::FileChooserParams with some options unique to CEF. + struct FileChooserParams : public content::FileChooserParams { + // 0-based index of the selected value in |accept_types|. + int selected_accept_filter = 0; + + // True if the Save dialog should prompt before overwriting files. + bool overwriteprompt = true; + + // True if read-only files should be hidden. + bool hidereadonly = true; + }; + + ~CefBrowserHostImpl() override; + + // Create a new CefBrowserHostImpl instance. + static CefRefPtr Create( + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings, + CefWindowHandle opener, + bool is_popup, + CefRefPtr request_context); + + // Returns the browser associated with the specified RenderViewHost. + static CefRefPtr GetBrowserForHost( + const content::RenderViewHost* host); + // Returns the browser associated with the specified RenderFrameHost. + static CefRefPtr GetBrowserForHost( + const content::RenderFrameHost* host); + // Returns the browser associated with the specified WebContents. + static CefRefPtr GetBrowserForContents( + content::WebContents* contents); + // Returns the browser associated with the specified URLRequest. + static CefRefPtr GetBrowserForRequest( + net::URLRequest* request); + // Returns the browser associated with the specified view routing IDs. + static CefRefPtr GetBrowserForView( + int render_process_id, int render_routing_id); + // Returns the browser associated with the specified frame routing IDs. + static CefRefPtr GetBrowserForFrame( + int render_process_id, int render_routing_id); + + // CefBrowserHost methods. + CefRefPtr GetBrowser() override; + void CloseBrowser(bool force_close) override; + void SetFocus(bool focus) override; + void SetWindowVisibility(bool visible) override; + CefWindowHandle GetWindowHandle() override; + CefWindowHandle GetOpenerWindowHandle() override; + CefRefPtr GetClient() override; + CefRefPtr GetRequestContext() override; + double GetZoomLevel() override; + void SetZoomLevel(double zoomLevel) override; + void RunFileDialog( + FileDialogMode mode, + const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, + int selected_accept_filter, + CefRefPtr callback) override; + void StartDownload(const CefString& url) override; + void Print() override; + void Find(int identifier, const CefString& searchText, + bool forward, bool matchCase, bool findNext) override; + void StopFinding(bool clearSelection) override; + void ShowDevTools(const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) override; + void CloseDevTools() override; + void GetNavigationEntries( + CefRefPtr visitor, + bool current_only) override; + void SetMouseCursorChangeDisabled(bool disabled) override; + bool IsMouseCursorChangeDisabled() override; + bool IsWindowRenderingDisabled() override; + void ReplaceMisspelling(const CefString& word) override; + void AddWordToDictionary(const CefString& word) override; + void WasResized() override; + void WasHidden(bool hidden) override; + void NotifyScreenInfoChanged() override; + void Invalidate(PaintElementType type) override; + void SendKeyEvent(const CefKeyEvent& event) override; + void SendMouseClickEvent(const CefMouseEvent& event, + MouseButtonType type, + bool mouseUp, int clickCount) override; + void SendMouseMoveEvent(const CefMouseEvent& event, + bool mouseLeave) override; + void SendMouseWheelEvent(const CefMouseEvent& event, + int deltaX, int deltaY) override; + void SendFocusEvent(bool setFocus) override; + void SendCaptureLostEvent() override; + void NotifyMoveOrResizeStarted() override; + CefTextInputContext GetNSTextInputContext() override; + void HandleKeyEventBeforeTextInputClient(CefEventHandle keyEvent) override; + void HandleKeyEventAfterTextInputClient(CefEventHandle keyEvent) override; + void DragTargetDragEnter(CefRefPtr drag_data, + const CefMouseEvent& event, + DragOperationsMask allowed_ops) override; + void DragTargetDragOver(const CefMouseEvent& event, + DragOperationsMask allowed_ops) override; + void DragTargetDragLeave() override; + void DragTargetDrop(const CefMouseEvent& event) override; + void DragSourceSystemDragEnded() override; + void DragSourceEndedAt(int x, int y, DragOperationsMask op) override; + + // CefBrowser methods. + CefRefPtr GetHost() override; + bool CanGoBack() override; + void GoBack() override; + bool CanGoForward() override; + void GoForward() override; + bool IsLoading() override; + void Reload() override; + void ReloadIgnoreCache() override; + void StopLoad() override; + int GetIdentifier() override; + bool IsSame(CefRefPtr that) override; + bool IsPopup() override; + bool HasDocument() override; + CefRefPtr GetMainFrame() override; + CefRefPtr GetFocusedFrame() override; + CefRefPtr GetFrame(int64 identifier) override; + CefRefPtr GetFrame(const CefString& name) override; + size_t GetFrameCount() override; + void GetFrameIdentifiers(std::vector& identifiers) override; + void GetFrameNames(std::vector& names) override; + bool SendProcessMessage( + CefProcessId target_process, + CefRefPtr message) override; + + // Returns true if windowless rendering is enabled. + bool IsWindowless() const; + // Returns true if transparent painting is enabled. + bool IsTransparent() const; + + // Called when the OS window hosting the browser is destroyed. + void WindowDestroyed(); + + // Destroy the browser members. This method should only be called after the + // native browser window is not longer processing messages. + void DestroyBrowser(); + + // Cancel display of the context menu, if any. + void CancelContextMenu(); + + // Returns the native view for the WebContents. + gfx::NativeView GetContentView() const; + + // Returns a pointer to the WebContents. + content::WebContents* GetWebContents() const; + + // Returns the frame associated with the specified URLRequest. + CefRefPtr GetFrameForRequest(net::URLRequest* request); + + // Navigate as specified by the |params| argument. + void Navigate(const CefNavigateParams& params); + + // Load the specified request. + void LoadRequest(int64 frame_id, CefRefPtr request); + + // Load the specified URL. + void LoadURL(int64 frame_id, + const std::string& url, + const content::Referrer& referrer, + ui::PageTransition transition, + const std::string& extra_headers); + + // Load the specified string. + void LoadString(int64 frame_id, const std::string& string, + const std::string& url); + + // Send a command to the renderer for execution. + void SendCommand(int64 frame_id, const std::string& command, + CefRefPtr responseHandler); + + // Send code to the renderer for execution. + void SendCode(int64 frame_id, bool is_javascript, const std::string& code, + const std::string& script_url, int script_start_line, + CefRefPtr responseHandler); + + bool SendProcessMessage(CefProcessId target_process, + const std::string& name, + base::ListValue* arguments, + bool user_initiated); + + // Open the specified text in the default text editor. + bool ViewText(const std::string& text); + + // Handler for URLs involving external protocols. + void HandleExternalProtocol(const GURL& url); + + // Set the frame that currently has focus. + void SetFocusedFrame(int64 frame_id); + + // Thread safe accessors. + const CefBrowserSettings& settings() const { return settings_; } + CefRefPtr client() const { return client_; } + int browser_id() const; + +#if defined(USE_AURA) + views::Widget* window_widget() const { return window_widget_; } +#endif + +#if defined(USE_X11) + CefWindowX11* window_x11() const { return window_x11_; } +#endif + + // Returns the URL that is currently loading (or loaded) in the main frame. + GURL GetLoadingURL(); + +#if defined(OS_WIN) + static void RegisterWindowClass(); +#endif + +#if defined(USE_AURA) + ui::PlatformCursor GetPlatformCursor(blink::WebCursorInfo::Type type); +#endif + + void OnSetFocus(cef_focus_source_t source); + + // The argument vector will be empty if the dialog was cancelled. + typedef base::Callback&)> + RunFileChooserCallback; + + // Run the file chooser dialog specified by |params|. Only a single dialog may + // be pending at any given time. |callback| will be executed asynchronously + // after the dialog is dismissed or if another dialog is already pending. + void RunFileChooser(const FileChooserParams& params, + const RunFileChooserCallback& callback); + + // Used when creating a new popup window. + struct PendingPopupInfo { + CefWindowInfo window_info; + CefBrowserSettings settings; + CefRefPtr client; + }; + // Returns false if a popup is already pending. + bool SetPendingPopupInfo(scoped_ptr info); + + enum DestructionState { + DESTRUCTION_STATE_NONE = 0, + DESTRUCTION_STATE_PENDING, + DESTRUCTION_STATE_ACCEPTED, + DESTRUCTION_STATE_COMPLETED + }; + DestructionState destruction_state() const { return destruction_state_; } + + // content::WebContentsDelegate methods. + content::WebContents* OpenURLFromTab( + content::WebContents* source, + const content::OpenURLParams& params) override; + void LoadingStateChanged(content::WebContents* source, + bool to_different_document) override; + void CloseContents(content::WebContents* source) override; + void UpdateTargetURL(content::WebContents* source, + const GURL& url) override; + bool AddMessageToConsole(content::WebContents* source, + int32 level, + const base::string16& message, + int32 line_no, + const base::string16& source_id) override; + void BeforeUnloadFired(content::WebContents* source, + bool proceed, + bool* proceed_to_fire_unload) override; + bool TakeFocus(content::WebContents* source, + bool reverse) override; + void WebContentsFocused(content::WebContents* contents) override; + bool HandleContextMenu( + const content::ContextMenuParams& params) override; + bool PreHandleKeyboardEvent( + content::WebContents* source, + const content::NativeWebKeyboardEvent& event, + bool* is_keyboard_shortcut) override; + void HandleKeyboardEvent( + content::WebContents* source, + const content::NativeWebKeyboardEvent& event) override; + bool CanDragEnter( + content::WebContents* source, + const content::DropData& data, + blink::WebDragOperationsMask operations_allowed) override; + bool ShouldCreateWebContents( + content::WebContents* web_contents, + int route_id, + int main_frame_route_id, + WindowContainerType window_container_type, + const base::string16& frame_name, + const GURL& target_url, + const std::string& partition_id, + content::SessionStorageNamespace* session_storage_namespace, + content::WebContentsView** view, + content::RenderViewHostDelegateView** delegate_view) override; + void WebContentsCreated(content::WebContents* source_contents, + int opener_render_frame_id, + const base::string16& frame_name, + const GURL& target_url, + content::WebContents* new_contents) override; + void DidNavigateMainFramePostCommit( + content::WebContents* web_contents) override; + content::JavaScriptDialogManager* GetJavaScriptDialogManager( + content::WebContents* source) override; + void RunFileChooser( + content::WebContents* web_contents, + const content::FileChooserParams& params) override; + void FindReply( + content::WebContents* web_contents, + int request_id, + int number_of_matches, + const gfx::Rect& selection_rect, + int active_match_ordinal, + bool final_update) override; + void UpdatePreferredSize(content::WebContents* source, + const gfx::Size& pref_size) override; + void RequestMediaAccessPermission( + content::WebContents* web_contents, + const content::MediaStreamRequest& request, + const content::MediaResponseCallback& callback) override; + + // content::WebContentsObserver methods. + using content::WebContentsObserver::BeforeUnloadFired; + using content::WebContentsObserver::WasHidden; + void RenderFrameCreated( + content::RenderFrameHost* render_frame_host) override; + void RenderFrameDeleted( + content::RenderFrameHost* render_frame_host) override; + void RenderViewCreated( + content::RenderViewHost* render_view_host) override; + void RenderViewDeleted( + content::RenderViewHost* render_view_host) override; + void RenderViewReady() override; + void RenderProcessGone(base::TerminationStatus status) override; + void DidCommitProvisionalLoadForFrame( + content::RenderFrameHost* render_frame_host, + const GURL& url, + ui::PageTransition transition_type) override; + void DidFailProvisionalLoad( + content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + int error_code, + const base::string16& error_description) override; + void DocumentAvailableInMainFrame() override; + void DidFailLoad(content::RenderFrameHost* render_frame_host, + const GURL& validated_url, + int error_code, + const base::string16& error_description) override; + void FrameDetached( + content::RenderFrameHost* render_frame_host) override; + void PluginCrashed(const base::FilePath& plugin_path, + base::ProcessId plugin_pid) override; + void DidUpdateFaviconURL( + const std::vector& candidates) override; + bool OnMessageReceived(const IPC::Message& message) override; + // Override to provide a thread safe implementation. + bool Send(IPC::Message* message) override; + + private: + class DevToolsWebContentsObserver; + + static CefRefPtr CreateInternal( + const CefWindowInfo& window_info, + const CefBrowserSettings& settings, + CefRefPtr client, + content::WebContents* web_contents, + scoped_refptr browser_info, + CefWindowHandle opener, + CefRefPtr request_context); + + // content::WebContentsObserver::OnMessageReceived() message handlers. + void OnFrameIdentified(int64 frame_id, + int64 parent_frame_id, + base::string16 name); + void OnDidFinishLoad( + int64 frame_id, + const GURL& validated_url, + bool is_main_frame, + int http_status_code); + void OnLoadingURLChange(const GURL& pending_url); + void OnRequest(const Cef_Request_Params& params); + void OnResponse(const Cef_Response_Params& params); + void OnResponseAck(int request_id); + void OnPDFHasUnsupportedFeature(); + void OnPDFSaveURLAs(const GURL& url, + const content::Referrer& referrer); + void OnPDFUpdateContentRestrictions(int content_restrictions); + void OnPDFModalPromptForPassword(const std::string& prompt, + IPC::Message* reply_message); + + void OnPDFModalPromptForPasswordClosed(IPC::Message* reply_message, + bool success, + const base::string16& actual_value); + + // content::NotificationObserver methods. + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; + + CefBrowserHostImpl(const CefWindowInfo& window_info, + const CefBrowserSettings& settings, + CefRefPtr client, + content::WebContents* web_contents, + scoped_refptr browser_info, + CefWindowHandle opener); + + // Updates and returns an existing frame or creates a new frame. Pass + // CefFrameHostImpl::kUnspecifiedFrameId for |parent_frame_id| if unknown. + CefRefPtr GetOrCreateFrame(int64 frame_id, + int64 parent_frame_id, + bool is_main_frame, + base::string16 frame_name, + const GURL& frame_url); + // Remove the references to all frames and mark them as detached. + void DetachAllFrames(); + +#if defined(OS_WIN) + static LPCTSTR GetWndClass(); + static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam); +#endif + + // Create the window. + bool PlatformCreateWindow(); + // Sends a message via the OS to close the native browser window. + // DestroyBrowser will be called after the native window has closed. + void PlatformCloseWindow(); + // Resize the window to the given dimensions. + void PlatformSizeTo(int width, int height); + // Set or remove focus from the window. + void PlatformSetFocus(bool focus); +#if defined(OS_MACOSX) + // Set or remove window visibility. + void PlatformSetWindowVisibility(bool visible); +#endif + // Return the handle for this window. + CefWindowHandle PlatformGetWindowHandle(); + // Open the specified text in the default text editor. + bool PlatformViewText(const std::string& text); + // Forward the keyboard event to the application or frame window to allow + // processing of shortcut keys. + void PlatformHandleKeyboardEvent( + const content::NativeWebKeyboardEvent& event); + // Invoke platform specific handling for the external protocol. + void PlatformHandleExternalProtocol(const GURL& url); + // Invoke platform specific file chooser dialog. + void PlatformRunFileChooser(const FileChooserParams& params, + RunFileChooserCallback callback); + + void PlatformTranslateKeyEvent(content::NativeWebKeyboardEvent& native_event, + const CefKeyEvent& key_event); + void PlatformTranslateClickEvent(blink::WebMouseEvent& web_event, + const CefMouseEvent& mouse_event, + CefBrowserHost::MouseButtonType type, + bool mouseUp, int clickCount); + void PlatformTranslateMoveEvent(blink::WebMouseEvent& web_event, + const CefMouseEvent& mouse_event, + bool mouseLeave); + void PlatformTranslateWheelEvent(blink::WebMouseWheelEvent& web_event, + const CefMouseEvent& mouse_event, + int deltaX, int deltaY); + void PlatformTranslateMouseEvent(blink::WebMouseEvent& web_event, + const CefMouseEvent& mouse_event); + + void PlatformNotifyMoveOrResizeStarted(); + + int TranslateModifiers(uint32 cefKeyStates); + void SendMouseEvent(const blink::WebMouseEvent& web_event); + + void OnAddressChange(CefRefPtr frame, + const GURL& url); + void OnLoadStart(CefRefPtr frame, + const GURL& url, + ui::PageTransition transition_type); + void OnLoadError(CefRefPtr frame, + const GURL& url, + int error_code, + const base::string16& error_description); + void OnLoadEnd(CefRefPtr frame, + const GURL& url, + int http_status_code); + + // Continuation from RunFileChooser. + void RunFileChooserOnUIThread(const FileChooserParams& params, + const RunFileChooserCallback& callback); + + // Used with RunFileChooser to clear the |file_chooser_pending_| flag. + void OnRunFileChooserCallback(const RunFileChooserCallback& callback, + int selected_accept_filter, + const std::vector& file_paths); + + // Used with WebContentsDelegate::RunFileChooser to notify the WebContents. + void OnRunFileChooserDelegateCallback( + content::WebContents* web_contents, + content::FileChooserParams::Mode mode, + int selected_accept_filter, + const std::vector& file_paths); + + void OnDevToolsWebContentsDestroyed(); + + CefWindowInfo window_info_; + CefBrowserSettings settings_; + CefRefPtr client_; + scoped_ptr web_contents_; + scoped_refptr browser_info_; + CefWindowHandle opener_; + CefRefPtr request_context_; + + // Pending popup information. Access must be protected by + // |pending_popup_info_lock_|. + base::Lock pending_popup_info_lock_; + scoped_ptr pending_popup_info_; + + // Volatile state information. All access must be protected by the state lock. + base::Lock state_lock_; + bool is_loading_; + bool can_go_back_; + bool can_go_forward_; + bool has_document_; + GURL loading_url_; + + // Messages we queue while waiting for the RenderView to be ready. We queue + // them here instead of in the RenderProcessHost to ensure that they're sent + // after the CefRenderViewObserver has been created on the renderer side. + std::queue queued_messages_; + bool queue_messages_; + + // Map of unique frame ids to CefFrameHostImpl references. + typedef std::map > FrameMap; + FrameMap frames_; + // The unique frame id currently identified as the main frame. + int64 main_frame_id_; + // The unique frame id currently identified as the focused frame. + int64 focused_frame_id_; + // Used when no other frame exists. Provides limited functionality. + CefRefPtr placeholder_frame_; + + // Represents the current browser destruction state. Only accessed on the UI + // thread. + DestructionState destruction_state_; + + // True if the OS window hosting the browser has been destroyed. Only accessed + // on the UI thread. + bool window_destroyed_; + + // True if currently in the OnSetFocus callback. Only accessed on the UI + // thread. + bool is_in_onsetfocus_; + + // True if the focus is currently on an editable field on the page. Only + // accessed on the UI thread. + bool focus_on_editable_field_; + + // True if mouse cursor change is disabled. + bool mouse_cursor_change_disabled_; + + // Used for managing notification subscriptions. + scoped_ptr registrar_; + + // Manages response registrations. + scoped_ptr response_manager_; + + // Used for creating and managing JavaScript dialogs. + scoped_ptr dialog_manager_; + + // Used for creating and managing context menus. + scoped_ptr menu_creator_; + + // Track the lifespan of the frontend WebContents associated with this + // browser. + scoped_ptr devtools_observer_; + // CefDevToolsFrontend will delete itself when the frontend WebContents is + // destroyed. + CefDevToolsFrontend* devtools_frontend_; + + // True if a file chooser is currently pending. + bool file_chooser_pending_; + +#if defined(USE_AURA) + // Widget hosting the web contents. It will be deleted automatically when the + // associated root window is destroyed. + views::Widget* window_widget_; +#endif // defined(USE_AURA) +#if defined(USE_X11) + CefWindowX11* window_x11_; + scoped_ptr invisible_cursor_; +#endif // defined(USE_X11) + + IMPLEMENT_REFCOUNTING(CefBrowserHostImpl); + DISALLOW_EVIL_CONSTRUCTORS(CefBrowserHostImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_HOST_IMPL_H_ diff --git a/libcef/browser/browser_host_impl_linux.cc b/libcef/browser/browser_host_impl_linux.cc new file mode 100644 index 000000000..d8bafcb85 --- /dev/null +++ b/libcef/browser/browser_host_impl_linux.cc @@ -0,0 +1,460 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_host_impl.h" + +// Include this first to avoid type conflict errors. +#include "base/tracked_objects.h" +#undef Status + +#include +#include + +#include "libcef/browser/context.h" +#include "libcef/browser/window_delegate_view.h" +#include "libcef/browser/window_x11.h" +#include "libcef/browser/thread_util.h" + +#include "base/bind.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/public/browser/native_web_keyboard_event.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/common/file_chooser_params.h" +#include "content/public/common/renderer_preferences.h" +#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h" +#include "ui/views/widget/widget.h" + +namespace { + +// Returns the number of seconds since system boot. +long GetSystemUptime() { + struct sysinfo info; + if (sysinfo(&info) == 0) + return info.uptime; + return 0; +} + +// Based on ui/base/cursor/cursor_loader_x11.cc. + +using blink::WebCursorInfo; + +int ToCursorID(WebCursorInfo::Type type) { + switch (type) { + case WebCursorInfo::TypePointer: + return XC_left_ptr; + case WebCursorInfo::TypeCross: + return XC_crosshair; + case WebCursorInfo::TypeHand: + return XC_hand2; + case WebCursorInfo::TypeIBeam: + return XC_xterm; + case WebCursorInfo::TypeWait: + return XC_watch; + case WebCursorInfo::TypeHelp: + return XC_question_arrow; + case WebCursorInfo::TypeEastResize: + return XC_right_side; + case WebCursorInfo::TypeNorthResize: + return XC_top_side; + case WebCursorInfo::TypeNorthEastResize: + return XC_top_right_corner; + case WebCursorInfo::TypeNorthWestResize: + return XC_top_left_corner; + case WebCursorInfo::TypeSouthResize: + return XC_bottom_side; + case WebCursorInfo::TypeSouthEastResize: + return XC_bottom_right_corner; + case WebCursorInfo::TypeSouthWestResize: + return XC_bottom_left_corner; + case WebCursorInfo::TypeWestResize: + return XC_left_side; + case WebCursorInfo::TypeNorthSouthResize: + return XC_sb_v_double_arrow; + case WebCursorInfo::TypeEastWestResize: + return XC_sb_h_double_arrow; + case WebCursorInfo::TypeNorthEastSouthWestResize: + return XC_left_ptr; + case WebCursorInfo::TypeNorthWestSouthEastResize: + return XC_left_ptr; + case WebCursorInfo::TypeColumnResize: + return XC_sb_h_double_arrow; + case WebCursorInfo::TypeRowResize: + return XC_sb_v_double_arrow; + case WebCursorInfo::TypeMiddlePanning: + return XC_fleur; + case WebCursorInfo::TypeEastPanning: + return XC_sb_right_arrow; + case WebCursorInfo::TypeNorthPanning: + return XC_sb_up_arrow; + case WebCursorInfo::TypeNorthEastPanning: + return XC_top_right_corner; + case WebCursorInfo::TypeNorthWestPanning: + return XC_top_left_corner; + case WebCursorInfo::TypeSouthPanning: + return XC_sb_down_arrow; + case WebCursorInfo::TypeSouthEastPanning: + return XC_bottom_right_corner; + case WebCursorInfo::TypeSouthWestPanning: + return XC_bottom_left_corner; + case WebCursorInfo::TypeWestPanning: + return XC_sb_left_arrow; + case WebCursorInfo::TypeMove: + return XC_fleur; + case WebCursorInfo::TypeVerticalText: + return XC_left_ptr; + case WebCursorInfo::TypeCell: + return XC_left_ptr; + case WebCursorInfo::TypeContextMenu: + return XC_left_ptr; + case WebCursorInfo::TypeAlias: + return XC_left_ptr; + case WebCursorInfo::TypeProgress: + return XC_left_ptr; + case WebCursorInfo::TypeNoDrop: + return XC_left_ptr; + case WebCursorInfo::TypeCopy: + return XC_left_ptr; + case WebCursorInfo::TypeNotAllowed: + return XC_left_ptr; + case WebCursorInfo::TypeZoomIn: + return XC_left_ptr; + case WebCursorInfo::TypeZoomOut: + return XC_left_ptr; + case WebCursorInfo::TypeGrab: + return XC_left_ptr; + case WebCursorInfo::TypeGrabbing: + return XC_left_ptr; + case WebCursorInfo::TypeCustom: + case WebCursorInfo::TypeNone: + break; + } + NOTREACHED(); + return 0; +} + +} // namespace + +ui::PlatformCursor CefBrowserHostImpl::GetPlatformCursor( + blink::WebCursorInfo::Type type) { + if (type == WebCursorInfo::TypeNone) { + if (!invisible_cursor_) { + invisible_cursor_.reset( + new ui::XScopedCursor(ui::CreateInvisibleCursor(), + gfx::GetXDisplay())); + } + return invisible_cursor_->get(); + } else { + return ui::GetXCursor(ToCursorID(type)); + } +} + +bool CefBrowserHostImpl::PlatformCreateWindow() { + DCHECK(!window_x11_); + DCHECK(!window_widget_); + + if (window_info_.width == 0) + window_info_.width = 800; + if (window_info_.height == 0) + window_info_.height = 600; + + gfx::Rect rect(window_info_.x, window_info_.y, + window_info_.width, window_info_.height); + + // Create a new window object. It will delete itself when the associated X11 + // window is destroyed. + window_x11_ = new CefWindowX11(this, window_info_.parent_window, rect); + window_info_.window = window_x11_->xwindow(); + + // Add a reference that will be released in the destroy handler. + AddRef(); + + SkColor background_color = SK_ColorWHITE; + const CefSettings& settings = CefContext::Get()->settings(); + if (CefColorGetA(settings.background_color) > 0) { + background_color = SkColorSetRGB( + CefColorGetR(settings.background_color), + CefColorGetG(settings.background_color), + CefColorGetB(settings.background_color)); + } + + CefWindowDelegateView* delegate_view = + new CefWindowDelegateView(background_color); + delegate_view->Init(window_info_.window, + web_contents(), + gfx::Rect(gfx::Point(), rect.size())); + + window_widget_ = delegate_view->GetWidget(); + window_widget_->Show(); + + window_x11_->Show(); + + // As an additional requirement on Linux, we must set the colors for the + // render widgets in webkit. + content::RendererPreferences* prefs = + web_contents_->GetMutableRendererPrefs(); + prefs->focus_ring_color = SkColorSetARGB(255, 229, 151, 0); + prefs->thumb_active_color = SkColorSetRGB(244, 244, 244); + prefs->thumb_inactive_color = SkColorSetRGB(234, 234, 234); + prefs->track_color = SkColorSetRGB(211, 211, 211); + + prefs->active_selection_bg_color = SkColorSetRGB(30, 144, 255); + prefs->active_selection_fg_color = SK_ColorWHITE; + prefs->inactive_selection_bg_color = SkColorSetRGB(200, 200, 200); + prefs->inactive_selection_fg_color = SkColorSetRGB(50, 50, 50); + + return true; +} + +void CefBrowserHostImpl::PlatformCloseWindow() { + if (window_x11_) + window_x11_->Close(); +} + +void CefBrowserHostImpl::PlatformSizeTo(int width, int height) { + if (window_x11_) { + window_x11_->SetBounds( + gfx::Rect(window_x11_->bounds().origin(), gfx::Size(width, height))); + } +} + +void CefBrowserHostImpl::PlatformSetFocus(bool focus) { + if (!focus) + return; + + if (web_contents_) { + // Give logical focus to the RenderWidgetHostViewAura in the views + // hierarchy. This does not change the native keyboard focus. + web_contents_->Focus(); + } + + if (window_x11_) { + // Give native focus to the DesktopNativeWidgetAura for the root window. + // Needs to be done via the ::Window so that keyboard focus is assigned + // correctly. + window_x11_->Focus(); + } +} + +CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() { + return IsWindowless() ? window_info_.parent_window : window_info_.window; +} + +bool CefBrowserHostImpl::PlatformViewText(const std::string& text) { + CEF_REQUIRE_UIT(); + + char buff[] = "/tmp/CEFSourceXXXXXX"; + int fd = mkstemp(buff); + + if (fd == -1) + return false; + + FILE* srcOutput = fdopen(fd, "w+"); + if (!srcOutput) + return false; + + if (fputs(text.c_str(), srcOutput) < 0) { + fclose(srcOutput); + return false; + } + + fclose(srcOutput); + + std::string newName(buff); + newName.append(".txt"); + if (rename(buff, newName.c_str()) != 0) + return false; + + std::string openCommand("xdg-open "); + openCommand += newName; + + if (system(openCommand.c_str()) != 0) + return false; + + return true; +} + +void CefBrowserHostImpl::PlatformHandleKeyboardEvent( + const content::NativeWebKeyboardEvent& event) { + // TODO(cef): Is something required here to handle shortcut keys? +} + +void CefBrowserHostImpl::PlatformRunFileChooser( + const FileChooserParams& params, + RunFileChooserCallback callback) { + NOTIMPLEMENTED(); + callback.Run(0, std::vector()); +} + +void CefBrowserHostImpl::PlatformHandleExternalProtocol(const GURL& url) { +} + +void CefBrowserHostImpl::PlatformTranslateKeyEvent( + content::NativeWebKeyboardEvent& result, + const CefKeyEvent& key_event) { + result.timeStampSeconds = GetSystemUptime(); + + result.windowsKeyCode = key_event.windows_key_code; + result.nativeKeyCode = key_event.native_key_code; + result.isSystemKey = key_event.is_system_key ? 1 : 0; + switch (key_event.type) { + case KEYEVENT_RAWKEYDOWN: + case KEYEVENT_KEYDOWN: + result.type = blink::WebInputEvent::RawKeyDown; + break; + case KEYEVENT_KEYUP: + result.type = blink::WebInputEvent::KeyUp; + break; + case KEYEVENT_CHAR: + result.type = blink::WebInputEvent::Char; + break; + default: + NOTREACHED(); + } + + result.text[0] = key_event.character; + result.unmodifiedText[0] = key_event.unmodified_character; + + result.setKeyIdentifierFromWindowsKeyCode(); + + result.modifiers |= TranslateModifiers(key_event.modifiers); +} + +void CefBrowserHostImpl::PlatformTranslateClickEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event, + MouseButtonType type, + bool mouseUp, int clickCount) { + PlatformTranslateMouseEvent(result, mouse_event); + + switch (type) { + case MBT_LEFT: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonLeft; + break; + case MBT_MIDDLE: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonMiddle; + break; + case MBT_RIGHT: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonRight; + break; + default: + NOTREACHED(); + } + + result.clickCount = clickCount; +} + +void CefBrowserHostImpl::PlatformTranslateMoveEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event, + bool mouseLeave) { + PlatformTranslateMouseEvent(result, mouse_event); + + if (!mouseLeave) { + result.type = blink::WebInputEvent::MouseMove; + if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonLeft; + else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonMiddle; + else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonRight; + else + result.button = blink::WebMouseEvent::ButtonNone; + } else { + result.type = blink::WebInputEvent::MouseLeave; + result.button = blink::WebMouseEvent::ButtonNone; + } + + result.clickCount = 0; +} + +void CefBrowserHostImpl::PlatformTranslateWheelEvent( + blink::WebMouseWheelEvent& result, + const CefMouseEvent& mouse_event, + int deltaX, int deltaY) { + result = blink::WebMouseWheelEvent(); + PlatformTranslateMouseEvent(result, mouse_event); + + result.type = blink::WebInputEvent::MouseWheel; + + static const double scrollbarPixelsPerGtkTick = 40.0; + result.deltaX = deltaX; + result.deltaY = deltaY; + result.wheelTicksX = result.deltaX / scrollbarPixelsPerGtkTick; + result.wheelTicksY = result.deltaY / scrollbarPixelsPerGtkTick; + result.hasPreciseScrollingDeltas = true; + + // Unless the phase and momentumPhase are passed in as parameters to this + // function, there is no way to know them + result.phase = blink::WebMouseWheelEvent::PhaseNone; + result.momentumPhase = blink::WebMouseWheelEvent::PhaseNone; + + if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonLeft; + else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonMiddle; + else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonRight; + else + result.button = blink::WebMouseEvent::ButtonNone; +} + +void CefBrowserHostImpl::PlatformTranslateMouseEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event) { + // position + result.x = mouse_event.x; + result.y = mouse_event.y; + result.windowX = result.x; + result.windowY = result.y; + result.globalX = result.x; + result.globalY = result.y; + + if (IsWindowless()) { + GetClient()->GetRenderHandler()->GetScreenPoint( + GetBrowser(), + result.x, result.y, + result.globalX, result.globalY); + } else if (window_x11_) { + const gfx::Point& origin = window_x11_->bounds().origin(); + result.globalX += origin.x(); + result.globalY += origin.y(); + } + + // modifiers + result.modifiers |= TranslateModifiers(mouse_event.modifiers); + + // timestamp + result.timeStampSeconds = GetSystemUptime(); +} + +void CefBrowserHostImpl::PlatformNotifyMoveOrResizeStarted() { + if (IsWindowless()) + return; + + if (!window_x11_) + return; + + views::DesktopWindowTreeHostX11* tree_host = window_x11_->GetHost(); + if (!tree_host) + return; + + // Explicitly set the screen bounds so that WindowTreeHost::*Screen() + // methods return the correct results. + const gfx::Rect& bounds = window_x11_->GetBoundsInScreen(); + tree_host->set_screen_bounds(bounds); + + // Send updated screen rectangle information to the renderer process so that + // popups are displayed in the correct location. + content::RenderWidgetHostImpl::From(web_contents()->GetRenderViewHost())-> + SendScreenRects(); +} + diff --git a/libcef/browser/browser_host_impl_mac.mm b/libcef/browser/browser_host_impl_mac.mm new file mode 100644 index 000000000..34d553288 --- /dev/null +++ b/libcef/browser/browser_host_impl_mac.mm @@ -0,0 +1,938 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_host_impl.h" + +#import +#import + +#include "libcef/browser/render_widget_host_view_osr.h" +#include "libcef/browser/text_input_client_osr_mac.h" +#include "libcef/browser/thread_util.h" + +#include "base/files/file_util.h" +#include "base/mac/mac_util.h" +#include "base/mac/scoped_nsautorelease_pool.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_restrictions.h" +#include "content/public/browser/native_web_keyboard_event.h" +#include "content/public/browser/render_widget_host_view.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/file_chooser_params.h" +#include "grit/cef_strings.h" +#include "grit/ui_strings.h" +#include "net/base/mime_util.h" +#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "third_party/WebKit/public/web/mac/WebInputEventFactory.h" +#import "ui/base/cocoa/underlay_opengl_hosting_window.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/events/keycodes/keyboard_codes_posix.h" +#include "ui/gfx/geometry/rect.h" + +// Wrapper NSView for the native view. Necessary to destroy the browser when +// the view is deleted. +@interface CefBrowserHostView : NSView { + @private + CefBrowserHostImpl* browser_; // weak +} + +@property (nonatomic, assign) CefBrowserHostImpl* browser; + +@end + +@implementation CefBrowserHostView + +@synthesize browser = browser_; + +- (void) dealloc { + if (browser_) { + // Force the browser to be destroyed and release the reference added in + // PlatformCreateWindow(). + browser_->WindowDestroyed(); + } + + [super dealloc]; +} + +@end + +// Receives notifications from the browser window. Will delete itself when done. +@interface CefWindowDelegate : NSObject { + @private + CefBrowserHostImpl* browser_; // weak + NSWindow* window_; +} +- (id)initWithWindow:(NSWindow*)window andBrowser:(CefBrowserHostImpl*)browser; +@end + +@implementation CefWindowDelegate + +- (id)initWithWindow:(NSWindow*)window andBrowser:(CefBrowserHostImpl*)browser { + if (self = [super init]) { + window_ = window; + browser_ = browser; + + [window_ setDelegate:self]; + + // Register for application hide/unhide notifications. + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationDidHide:) + name:NSApplicationDidHideNotification + object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationDidUnhide:) + name:NSApplicationDidUnhideNotification + object:nil]; + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [super dealloc]; +} + +// Called when we are activated (when we gain focus). +- (void)windowDidBecomeKey:(NSNotification*)notification { + if (browser_) + browser_->SetFocus(true); +} + +// Called when we are deactivated (when we lose focus). +- (void)windowDidResignKey:(NSNotification*)notification { + if (browser_) + browser_->SetFocus(false); +} + +// Called when we have been minimized. +- (void)windowDidMiniaturize:(NSNotification *)notification { + if (browser_) + browser_->SetWindowVisibility(false); +} + +// Called when we have been unminimized. +- (void)windowDidDeminiaturize:(NSNotification *)notification { + if (browser_) + browser_->SetWindowVisibility(true); +} + +// Called when the application has been hidden. +- (void)applicationDidHide:(NSNotification *)notification { + // If the window is miniaturized then nothing has really changed. + if (![window_ isMiniaturized]) { + if (browser_) + browser_->SetWindowVisibility(false); + } +} + +// Called when the application has been unhidden. +- (void)applicationDidUnhide:(NSNotification *)notification { + // If the window is miniaturized then nothing has really changed. + if (![window_ isMiniaturized]) { + if (browser_) + browser_->SetWindowVisibility(true); + } +} + +- (BOOL)windowShouldClose:(id)window { + // Protect against multiple requests to close while the close is pending. + if (browser_ && browser_->destruction_state() <= + CefBrowserHostImpl::DESTRUCTION_STATE_PENDING) { + if (browser_->destruction_state() == + CefBrowserHostImpl::DESTRUCTION_STATE_NONE) { + // Request that the browser close. + browser_->CloseBrowser(false); + } + + // Cancel the close. + return NO; + } + + // Clean ourselves up after clearing the stack of anything that might have the + // window on it. + [self performSelectorOnMainThread:@selector(cleanup:) + withObject:window + waitUntilDone:NO]; + + // Allow the close. + return YES; +} + +- (void)cleanup:(id)window { + [self release]; +} + +@end + +namespace { + +base::string16 GetDescriptionFromMimeType(const std::string& mime_type) { + // Check for wild card mime types and return an appropriate description. + static const struct { + const char* mime_type; + int string_id; + } kWildCardMimeTypes[] = { + { "audio", IDS_APP_AUDIO_FILES }, + { "image", IDS_APP_IMAGE_FILES }, + { "text", IDS_APP_TEXT_FILES }, + { "video", IDS_APP_VIDEO_FILES }, + }; + + for (size_t i = 0; i < arraysize(kWildCardMimeTypes); ++i) { + if (mime_type == std::string(kWildCardMimeTypes[i].mime_type) + "/*") + return l10n_util::GetStringUTF16(kWildCardMimeTypes[i].string_id); + } + + return base::string16(); +} + +void AddFilters(NSPopUpButton *button, + const std::vector& accept_filters, + bool include_all_files, + std::vector >* all_extensions) { + for (size_t i = 0; i < accept_filters.size(); ++i) { + const base::string16& filter = accept_filters[i]; + if (filter.empty()) + continue; + + std::vector extensions; + base::string16 description; + + size_t sep_index = filter.find('|'); + if (sep_index != std::string::npos) { + // Treat as a filter of the form "Filter Name|.ext1;.ext2;.ext3". + description = filter.substr(0, sep_index); + + std::vector ext; + base::SplitString(filter.substr(sep_index + 1), ';', &ext); + for (size_t x = 0; x < ext.size(); ++x) { + const base::string16& file_ext = ext[x]; + if (!file_ext.empty() && file_ext[0] == '.') + extensions.push_back(file_ext); + } + } else if (filter[0] == '.') { + // Treat as an extension beginning with the '.' character. + extensions.push_back(filter); + } else { + // Otherwise convert mime type to one or more extensions. + const std::string& ascii = base::UTF16ToASCII(filter); + std::vector ext; + net::GetExtensionsForMimeType(ascii, &ext); + if (!ext.empty()) { + for (size_t x = 0; x < ext.size(); ++x) + extensions.push_back(base::ASCIIToUTF16("." + ext[x])); + description = GetDescriptionFromMimeType(ascii); + } + } + + if (extensions.empty()) + continue; + + // Don't display a crazy number of extensions since the NSPopUpButton width + // will keep growing. + const size_t kMaxExtensions = 10; + + base::string16 ext_str; + for (size_t x = 0; x < std::min(kMaxExtensions, extensions.size()); ++x) { + const base::string16& pattern = base::ASCIIToUTF16("*") + extensions[x]; + if (x != 0) + ext_str += base::ASCIIToUTF16(";"); + ext_str += pattern; + } + + if (extensions.size() > kMaxExtensions) + ext_str += base::ASCIIToUTF16(";..."); + + if (description.empty()) { + description = ext_str; + } else { + description += + base::ASCIIToUTF16(" (") + ext_str + base::ASCIIToUTF16(")"); + } + + [button addItemWithTitle:base::SysUTF16ToNSString(description)]; + + all_extensions->push_back(extensions); + } + + // Add the *.* filter, but only if we have added other filters (otherwise it + // is implied). + if (include_all_files && !all_extensions->empty()) { + [button addItemWithTitle:base::SysUTF8ToNSString("All Files (*)")]; + all_extensions->push_back(std::vector()); + } +} + +} // namespace + +// Used to manage the file type filter in the NSSavePanel/NSOpenPanel. +@interface CefFilterDelegate : NSObject { + @private + NSSavePanel* panel_; + std::vector > extensions_; + int selected_index_; +} +- (id)initWithPanel:(NSSavePanel*)panel + andAcceptFilters:(const std::vector&)accept_filters + andFilterIndex:(int)index; +- (void)setFilter:(int)index; +- (int)filter; +- (void)filterSelectionChanged:(id)sender; +- (void)setFileExtension; +@end + +@implementation CefFilterDelegate + +- (id)initWithPanel:(NSSavePanel*)panel + andAcceptFilters:(const std::vector&)accept_filters + andFilterIndex:(int)index { + if (self = [super init]) { + DCHECK(panel); + panel_ = panel; + selected_index_ = 0; + + NSPopUpButton *button = [[NSPopUpButton alloc] init]; + AddFilters(button, accept_filters, true, &extensions_); + [button sizeToFit]; + [button setTarget:self]; + [button setAction:@selector(filterSelectionChanged:)]; + + if (index < static_cast(extensions_.size())) { + [button selectItemAtIndex:index]; + [self setFilter:index]; + } + + [panel_ setAccessoryView:button]; + } + return self; +} + +// Set the current filter index. +- (void)setFilter:(int)index { + DCHECK(index >= 0 && index < static_cast(extensions_.size())); + selected_index_ = index; + + // Set the selectable file types. For open panels this limits the files that + // can be selected. For save panels this applies a default file extenion when + // the dialog is dismissed if none is already provided. + NSMutableArray* acceptArray = nil; + if (!extensions_[index].empty()) { + acceptArray = [[NSMutableArray alloc] init]; + for (size_t i = 0; i < extensions_[index].size(); ++i) { + [acceptArray addObject: + base::SysUTF16ToNSString(extensions_[index][i].substr(1))]; + } + } + [panel_ setAllowedFileTypes:acceptArray]; + + if (![panel_ isKindOfClass:[NSOpenPanel class]]) { + // For save panels set the file extension. + [self setFileExtension]; + } +} + +// Returns the current filter index. +- (int)filter { + return selected_index_; +} + +// Called when the selected filter is changed via the NSPopUpButton. +- (void)filterSelectionChanged:(id)sender { + NSPopUpButton *button = (NSPopUpButton*)sender; + [self setFilter:[button indexOfSelectedItem]]; +} + +// Set the extension on the currently selected file name. +- (void)setFileExtension { + const std::vector& filter = extensions_[selected_index_]; + if (filter.empty()) { + // All extensions are allowed so don't change anything. + return; + } + + base::FilePath path(base::SysNSStringToUTF8([panel_ nameFieldStringValue])); + + // If the file name currently includes an extension from |filter| then don't + // change anything. + base::string16 extension = base::UTF8ToUTF16(path.Extension()); + if (!extension.empty()) { + for (size_t i = 0; i < filter.size(); ++i) { + if (filter[i] == extension) + return; + } + } + + // Change the extension to the first value in |filter|. + path = path.ReplaceExtension(base::UTF16ToUTF8(filter[0])); + [panel_ setNameFieldStringValue:base::SysUTF8ToNSString(path.value())]; +} + +@end + +namespace { + +void RunOpenFileDialog(const CefBrowserHostImpl::FileChooserParams& params, + NSView* view, + int* filter_index, + std::vector* files) { + NSOpenPanel* openPanel = [NSOpenPanel openPanel]; + + base::string16 title; + if (!params.title.empty()) { + title = params.title; + } else { + title = l10n_util::GetStringUTF16( + params.mode == content::FileChooserParams::Open ? + IDS_OPEN_FILE_DIALOG_TITLE : + (params.mode == content::FileChooserParams::OpenMultiple ? + IDS_OPEN_FILES_DIALOG_TITLE : IDS_SELECT_FOLDER_DIALOG_TITLE)); + } + [openPanel setTitle:base::SysUTF16ToNSString(title)]; + + std::string filename, directory; + if (!params.default_file_name.empty()) { + if (params.mode == content::FileChooserParams::UploadFolder || + params.default_file_name.EndsWithSeparator()) { + // The value is only a directory. + directory = params.default_file_name.value(); + } else { + // The value is a file name and possibly a directory. + filename = params.default_file_name.BaseName().value(); + directory = params.default_file_name.DirName().value(); + } + } + if (!filename.empty()) { + [openPanel setNameFieldStringValue:base::SysUTF8ToNSString(filename)]; + } + if (!directory.empty()) { + [openPanel setDirectoryURL: + [NSURL fileURLWithPath:base::SysUTF8ToNSString(directory)]]; + } + + CefFilterDelegate* filter_delegate = nil; + if (params.mode != content::FileChooserParams::UploadFolder && + !params.accept_types.empty()) { + // Add the file filter control. + filter_delegate = + [[CefFilterDelegate alloc] initWithPanel:openPanel + andAcceptFilters:params.accept_types + andFilterIndex:*filter_index]; + } + + // Further panel configuration. + [openPanel setAllowsOtherFileTypes:YES]; + [openPanel setAllowsMultipleSelection: + (params.mode == content::FileChooserParams::OpenMultiple)]; + [openPanel setCanChooseFiles: + (params.mode != content::FileChooserParams::UploadFolder)]; + [openPanel setCanChooseDirectories: + (params.mode == content::FileChooserParams::UploadFolder)]; + [openPanel setShowsHiddenFiles:!params.hidereadonly]; + + // Show panel. + [openPanel beginSheetModalForWindow:[view window] completionHandler:nil]; + if ([openPanel runModal] == NSFileHandlingPanelOKButton) { + NSArray *urls = [openPanel URLs]; + int i, count = [urls count]; + for (i=0; ipush_back(base::FilePath(base::SysNSStringToUTF8([url path]))); + } + } + + if (filter_delegate != nil) + *filter_index = [filter_delegate filter]; + + [NSApp endSheet:openPanel]; +} + +bool RunSaveFileDialog(const CefBrowserHostImpl::FileChooserParams& params, + NSView* view, + int* filter_index, + base::FilePath* file) { + NSSavePanel* savePanel = [NSSavePanel savePanel]; + + base::string16 title; + if (!params.title.empty()) + title = params.title; + else + title = l10n_util::GetStringUTF16(IDS_SAVE_AS_DIALOG_TITLE); + [savePanel setTitle:base::SysUTF16ToNSString(title)]; + + std::string filename, directory; + if (!params.default_file_name.empty()) { + if (params.default_file_name.EndsWithSeparator()) { + // The value is only a directory. + directory = params.default_file_name.value(); + } else { + // The value is a file name and possibly a directory. + filename = params.default_file_name.BaseName().value(); + directory = params.default_file_name.DirName().value(); + } + } + if (!filename.empty()) { + [savePanel setNameFieldStringValue:base::SysUTF8ToNSString(filename)]; + } + if (!directory.empty()) { + [savePanel setDirectoryURL: + [NSURL fileURLWithPath:base::SysUTF8ToNSString(directory)]]; + } + + CefFilterDelegate* filter_delegate = nil; + if (!params.accept_types.empty()) { + // Add the file filter control. + filter_delegate = + [[CefFilterDelegate alloc] initWithPanel:savePanel + andAcceptFilters:params.accept_types + andFilterIndex:*filter_index]; + } + + [savePanel setAllowsOtherFileTypes:YES]; + [savePanel setShowsHiddenFiles:!params.hidereadonly]; + + bool success = false; + + [savePanel beginSheetModalForWindow:[view window] completionHandler:nil]; + if ([savePanel runModal] == NSFileHandlingPanelOKButton) { + NSURL * url = [savePanel URL]; + NSString* path = [url path]; + *file = base::FilePath([path UTF8String]); + success = true; + } + + if (filter_delegate != nil) + *filter_index = [filter_delegate filter]; + + [NSApp endSheet:savePanel]; + + return success; +} + +} // namespace + +bool CefBrowserHostImpl::PlatformViewText(const std::string& text) { + NOTIMPLEMENTED(); + return false; +} + +CefTextInputContext CefBrowserHostImpl::GetNSTextInputContext() { + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return NULL; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "Called on invalid thread"; + return NULL; + } + + CefRenderWidgetHostViewOSR* rwhv = static_cast( + GetWebContents()->GetRenderWidgetHostView()); + + return rwhv->GetNSTextInputContext(); +} + +void CefBrowserHostImpl::HandleKeyEventBeforeTextInputClient( + CefEventHandle keyEvent) { + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "Called on invalid thread"; + return; + } + + CefRenderWidgetHostViewOSR* rwhv = static_cast( + GetWebContents()->GetRenderWidgetHostView()); + + rwhv->HandleKeyEventBeforeTextInputClient(keyEvent); +} + +void CefBrowserHostImpl::HandleKeyEventAfterTextInputClient( + CefEventHandle keyEvent) { + if (!IsWindowless()) { + NOTREACHED() << "Window rendering is not disabled"; + return; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "Called on invalid thread"; + return; + } + + CefRenderWidgetHostViewOSR* rwhv = static_cast( + GetWebContents()->GetRenderWidgetHostView()); + + rwhv->HandleKeyEventAfterTextInputClient(keyEvent); +} + +bool CefBrowserHostImpl::PlatformCreateWindow() { + base::mac::ScopedNSAutoreleasePool autorelease_pool; + + NSWindow* newWnd = nil; + + NSView* parentView = window_info_.parent_view; + NSRect contentRect = {{window_info_.x, window_info_.y}, + {window_info_.width, window_info_.height}}; + if (parentView == nil) { + // Create a new window. + NSRect screen_rect = [[NSScreen mainScreen] visibleFrame]; + NSRect window_rect = {{window_info_.x, + screen_rect.size.height - window_info_.y}, + {window_info_.width, window_info_.height}}; + if (window_rect.size.width == 0) + window_rect.size.width = 750; + if (window_rect.size.height == 0) + window_rect.size.height = 750; + + contentRect.origin.x = 0; + contentRect.origin.y = 0; + contentRect.size.width = window_rect.size.width; + contentRect.size.height = window_rect.size.height; + + newWnd = [[UnderlayOpenGLHostingWindow alloc] + initWithContentRect:window_rect + styleMask:(NSTitledWindowMask | + NSClosableWindowMask | + NSMiniaturizableWindowMask | + NSResizableWindowMask | + NSUnifiedTitleAndToolbarWindowMask ) + backing:NSBackingStoreBuffered + defer:NO]; + + // Create the delegate for control and browser window events. + [[CefWindowDelegate alloc] initWithWindow:newWnd andBrowser:this]; + + parentView = [newWnd contentView]; + window_info_.parent_view = parentView; + } + + // Make the content view for the window have a layer. This will make all + // sub-views have layers. This is necessary to ensure correct layer + // ordering of all child views and their layers. + [[[parentView window] contentView] setWantsLayer:YES]; + + // Add a reference that will be released in the dealloc handler. + AddRef(); + + // Create the browser view. + CefBrowserHostView* browser_view = + [[CefBrowserHostView alloc] initWithFrame:contentRect]; + browser_view.browser = this; + [parentView addSubview:browser_view]; + [browser_view setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)]; + [browser_view setNeedsDisplay:YES]; + [browser_view release]; + + // Parent the TabContents to the browser view. + const NSRect bounds = [browser_view bounds]; + NSView* native_view = web_contents_->GetNativeView(); + [browser_view addSubview:native_view]; + [native_view setFrame:bounds]; + [native_view setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)]; + [native_view setNeedsDisplay:YES]; + + window_info_.view = browser_view; + + if (newWnd != nil && !window_info_.hidden) { + // Show the window. + [newWnd makeKeyAndOrderFront: nil]; + } + + return true; +} + +void CefBrowserHostImpl::PlatformCloseWindow() { + if (window_info_.view != nil) { + [[window_info_.view window] + performSelectorOnMainThread:@selector(performClose:) + withObject:nil + waitUntilDone:NO]; + } +} + +void CefBrowserHostImpl::PlatformSizeTo(int width, int height) { + // Not needed; subviews are bound. +} + +void CefBrowserHostImpl::PlatformSetFocus(bool focus) { + if (web_contents_) { + if (content::RenderWidgetHostView* view = + web_contents_->GetRenderWidgetHostView()) { + view->SetActive(focus); + + if (focus && !IsWindowless()) { + // Give keyboard focus to the native view. + NSView* view = web_contents_->GetContentNativeView(); + DCHECK([view canBecomeKeyView]); + [[view window] makeFirstResponder:view]; + } + } + } +} + +void CefBrowserHostImpl::PlatformSetWindowVisibility(bool visible) { + if (web_contents_) { + if (content::RenderWidgetHostView* view = + web_contents_->GetRenderWidgetHostView()) { + view->SetWindowVisibility(visible); + } + } +} + +CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() { + return IsWindowless() ? window_info_.parent_view : window_info_.view; +} + +void CefBrowserHostImpl::PlatformHandleKeyboardEvent( + const content::NativeWebKeyboardEvent& event) { + // Give the top level menu equivalents a chance to handle the event. + if ([event.os_event type] == NSKeyDown) + [[NSApp mainMenu] performKeyEquivalent:event.os_event]; +} + +void CefBrowserHostImpl::PlatformRunFileChooser( + const FileChooserParams& params, + RunFileChooserCallback callback) { + std::vector files; + int filter_index = params.selected_accept_filter; + NSView* owner = PlatformGetWindowHandle(); + + if (params.mode == content::FileChooserParams::Open || + params.mode == content::FileChooserParams::OpenMultiple || + params.mode == content::FileChooserParams::UploadFolder) { + RunOpenFileDialog(params, owner, &filter_index, &files); + } else if (params.mode == content::FileChooserParams::Save) { + base::FilePath file; + if (RunSaveFileDialog(params, owner, &filter_index, &file)) { + files.push_back(file); + } + } else { + NOTIMPLEMENTED(); + } + + callback.Run(filter_index, files); +} + +void CefBrowserHostImpl::PlatformHandleExternalProtocol(const GURL& url) { +} + +static NSTimeInterval currentEventTimestamp() { + NSEvent* currentEvent = [NSApp currentEvent]; + if (currentEvent) + return [currentEvent timestamp]; + else { + // FIXME(API): In case there is no current event, the timestamp could be + // obtained by getting the time since the application started. This involves + // taking some more static functions from Chromium code. + // Another option is to have the timestamp as a field in CefEvent structures + // and let the client provide it. + return 0; + } +} + +static NSUInteger NativeModifiers(int cef_modifiers) { + NSUInteger native_modifiers = 0; + if (cef_modifiers & EVENTFLAG_SHIFT_DOWN) + native_modifiers |= NSShiftKeyMask; + if (cef_modifiers & EVENTFLAG_CONTROL_DOWN) + native_modifiers |= NSControlKeyMask; + if (cef_modifiers & EVENTFLAG_ALT_DOWN) + native_modifiers |= NSAlternateKeyMask; + if (cef_modifiers & EVENTFLAG_COMMAND_DOWN) + native_modifiers |= NSCommandKeyMask; + if (cef_modifiers & EVENTFLAG_CAPS_LOCK_ON) + native_modifiers |= NSAlphaShiftKeyMask; + if (cef_modifiers & EVENTFLAG_NUM_LOCK_ON) + native_modifiers |= NSNumericPadKeyMask; + + return native_modifiers; +} + +void CefBrowserHostImpl::PlatformTranslateKeyEvent( + content::NativeWebKeyboardEvent& native_event, + const CefKeyEvent& key_event) { + // Use a synthetic NSEvent in order to obtain the windowsKeyCode member from + // the NativeWebKeyboardEvent constructor. This is the only member which can + // not be easily translated (without hardcoding keyCodes) + // Determining whether a modifier key is left or right seems to be done + // through the key code as well. + + NSEventType event_type; + if (key_event.character == 0 && key_event.unmodified_character == 0) { + // Check if both character and unmodified_characther are empty to determine + // if this was a NSFlagsChanged event. + // A dead key will have an empty character, but a non-empty unmodified + // character + event_type = NSFlagsChanged; + } else { + switch (key_event.type) { + case KEYEVENT_RAWKEYDOWN: + case KEYEVENT_KEYDOWN: + case KEYEVENT_CHAR: + event_type = NSKeyDown; + break; + case KEYEVENT_KEYUP: + event_type = NSKeyUp; + break; + } + } + + NSString* charactersIgnoringModifiers = [[[NSString alloc] + initWithCharacters:&key_event.unmodified_character length:1] + autorelease]; + NSString* characters = [[[NSString alloc] + initWithCharacters:&key_event.character length:1] autorelease]; + + NSEvent* synthetic_event = + [NSEvent keyEventWithType:event_type + location:NSMakePoint(0, 0) + modifierFlags:NativeModifiers(key_event.modifiers) + timestamp:currentEventTimestamp() + windowNumber:0 + context:nil + characters:characters + charactersIgnoringModifiers:charactersIgnoringModifiers + isARepeat:NO + keyCode:key_event.native_key_code]; + + native_event = content::NativeWebKeyboardEvent(synthetic_event); + if (key_event.type == KEYEVENT_CHAR) + native_event.type = blink::WebInputEvent::Char; + + native_event.isSystemKey = key_event.is_system_key; +} + +void CefBrowserHostImpl::PlatformTranslateClickEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event, + MouseButtonType type, + bool mouseUp, int clickCount) { + PlatformTranslateMouseEvent(result, mouse_event); + + switch (type) { + case MBT_LEFT: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonLeft; + break; + case MBT_MIDDLE: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonMiddle; + break; + case MBT_RIGHT: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonRight; + break; + default: + NOTREACHED(); + } + + result.clickCount = clickCount; +} + +void CefBrowserHostImpl::PlatformTranslateMoveEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event, + bool mouseLeave) { + PlatformTranslateMouseEvent(result, mouse_event); + + if (!mouseLeave) { + result.type = blink::WebInputEvent::MouseMove; + if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonLeft; + else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonMiddle; + else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonRight; + else + result.button = blink::WebMouseEvent::ButtonNone; + } else { + result.type = blink::WebInputEvent::MouseLeave; + result.button = blink::WebMouseEvent::ButtonNone; + } + + result.clickCount = 0; +} + +void CefBrowserHostImpl::PlatformTranslateWheelEvent( + blink::WebMouseWheelEvent& result, + const CefMouseEvent& mouse_event, + int deltaX, int deltaY) { + result = blink::WebMouseWheelEvent(); + PlatformTranslateMouseEvent(result, mouse_event); + + result.type = blink::WebInputEvent::MouseWheel; + + static const double scrollbarPixelsPerCocoaTick = 40.0; + result.deltaX = deltaX; + result.deltaY = deltaY; + result.wheelTicksX = result.deltaX / scrollbarPixelsPerCocoaTick; + result.wheelTicksY = result.deltaY / scrollbarPixelsPerCocoaTick; + result.hasPreciseScrollingDeltas = true; + + // Unless the phase and momentumPhase are passed in as parameters to this + // function, there is no way to know them + result.phase = blink::WebMouseWheelEvent::PhaseNone; + result.momentumPhase = blink::WebMouseWheelEvent::PhaseNone; + + if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonLeft; + else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonMiddle; + else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonRight; + else + result.button = blink::WebMouseEvent::ButtonNone; +} + +void CefBrowserHostImpl::PlatformTranslateMouseEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event) { + // position + result.x = mouse_event.x; + result.y = mouse_event.y; + result.windowX = result.x; + result.windowY = result.y; + result.globalX = result.x; + result.globalY = result.y; + + if (IsWindowless()) { + GetClient()->GetRenderHandler()->GetScreenPoint( + GetBrowser(), + result.x, result.y, + result.globalX, result.globalY); + } else { + NSView* view = window_info_.parent_view; + if (view) { + NSRect bounds = [view bounds]; + NSPoint view_pt = {result.x, bounds.size.height - result.y}; + NSPoint window_pt = [view convertPoint:view_pt toView:nil]; + NSPoint screen_pt = [[view window] convertBaseToScreen:window_pt]; + result.globalX = screen_pt.x; + result.globalY = screen_pt.y; + } + } + + // modifiers + result.modifiers |= TranslateModifiers(mouse_event.modifiers); + + // timestamp - Mac OSX specific + result.timeStampSeconds = currentEventTimestamp(); +} + +void CefBrowserHostImpl::PlatformNotifyMoveOrResizeStarted() { +} diff --git a/libcef/browser/browser_host_impl_win.cc b/libcef/browser/browser_host_impl_win.cc new file mode 100644 index 000000000..c1e286079 --- /dev/null +++ b/libcef/browser/browser_host_impl_win.cc @@ -0,0 +1,1145 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_host_impl.h" + +#include +#include +#include +#include +#include +#include + +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/window_delegate_view.h" + +#include "base/files/file_util.h" +#include "base/i18n/case_conversion.h" +#include "base/memory/ref_counted_memory.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "base/win/registry.h" +#include "base/win/scoped_comptr.h" +#include "base/win/windows_version.h" +#include "content/common/cursors/webcursor.h" +#include "content/public/browser/native_web_keyboard_event.h" +#include "content/public/common/file_chooser_params.h" +#include "grit/cef_strings.h" +#include "grit/ui_strings.h" +#include "grit/ui_unscaled_resources.h" +#include "net/base/mime_util.h" +#include "third_party/WebKit/public/web/WebInputEvent.h" +#include "ui/aura/window_tree_host.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/base/win/shell.h" +#include "ui/gfx/win/hwnd_util.h" +#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" +#include "ui/views/widget/widget.h" +#include "ui/views/win/hwnd_message_handler_delegate.h" +#include "ui/views/win/hwnd_util.h" + +#pragma comment(lib, "dwmapi.lib") + +namespace { + +void WriteTempFileAndView(scoped_refptr str) { + CEF_REQUIRE_FILET(); + + base::FilePath tmp_file; + if (!base::CreateTemporaryFile(&tmp_file)) + return; + + // The shell command will look at the file extension to identify the correct + // program to open. + tmp_file = tmp_file.AddExtension(L"txt"); + + const std::string& data = str->data(); + int write_ct = base::WriteFile(tmp_file, data.c_str(), data.size()); + DCHECK_EQ(static_cast(data.size()), write_ct); + + ui::win::OpenItemViaShell(tmp_file); +} + +// From ui/base/dialogs/select_file_dialog_win.cc. + +// Get the file type description from the registry. This will be "Text Document" +// for .txt files, "JPEG Image" for .jpg files, etc. If the registry doesn't +// have an entry for the file type, we return false, true if the description was +// found. 'file_ext' must be in form ".txt". +static bool GetRegistryDescriptionFromExtension(const std::wstring& file_ext, + std::wstring* reg_description) { + DCHECK(reg_description); + base::win::RegKey reg_ext(HKEY_CLASSES_ROOT, file_ext.c_str(), KEY_READ); + std::wstring reg_app; + if (reg_ext.ReadValue(NULL, ®_app) == ERROR_SUCCESS && !reg_app.empty()) { + base::win::RegKey reg_link(HKEY_CLASSES_ROOT, reg_app.c_str(), KEY_READ); + if (reg_link.ReadValue(NULL, reg_description) == ERROR_SUCCESS) + return true; + } + return false; +} + +// Set up a filter for a Save/Open dialog, which will consist of |file_ext| file +// extensions (internally separated by semicolons), |ext_desc| as the text +// descriptions of the |file_ext| types (optional), and (optionally) the default +// 'All Files' view. The purpose of the filter is to show only files of a +// particular type in a Windows Save/Open dialog box. The resulting filter is +// returned. The filters created here are: +// 1. only files that have 'file_ext' as their extension +// 2. all files (only added if 'include_all_files' is true) +// Example: +// file_ext: { "*.txt", "*.htm;*.html" } +// ext_desc: { "Text Document" } +// returned: "Text Document\0*.txt\0HTML Document\0*.htm;*.html\0" +// "All Files\0*.*\0\0" (in one big string) +// If a description is not provided for a file extension, it will be retrieved +// from the registry. If the file extension does not exist in the registry, it +// will be omitted from the filter, as it is likely a bogus extension. +std::wstring FormatFilterForExtensions( + const std::vector& file_ext, + const std::vector& ext_desc, + bool include_all_files) { + const std::wstring all_ext = L"*.*"; + const std::wstring all_desc = + l10n_util::GetStringUTF16(IDS_APP_SAVEAS_ALL_FILES) + + L" (" + all_ext + L")"; + + DCHECK(file_ext.size() >= ext_desc.size()); + + if (file_ext.empty()) + include_all_files = true; + + std::wstring result; + + for (size_t i = 0; i < file_ext.size(); ++i) { + std::wstring ext = file_ext[i]; + std::wstring desc; + if (i < ext_desc.size()) + desc = ext_desc[i]; + + if (ext.empty()) { + // Force something reasonable to appear in the dialog box if there is no + // extension provided. + include_all_files = true; + continue; + } + + if (desc.empty()) { + DCHECK(ext.find(L'.') != std::wstring::npos); + std::wstring first_extension = ext.substr(ext.find(L'.')); + size_t first_separator_index = first_extension.find(L';'); + if (first_separator_index != std::wstring::npos) + first_extension = first_extension.substr(0, first_separator_index); + + // Find the extension name without the preceeding '.' character. + std::wstring ext_name = first_extension; + size_t ext_index = ext_name.find_first_not_of(L'.'); + if (ext_index != std::wstring::npos) + ext_name = ext_name.substr(ext_index); + + if (!GetRegistryDescriptionFromExtension(first_extension, &desc)) { + // The extension doesn't exist in the registry. + include_all_files = true; + } + } + + if (!desc.empty()) + desc += L" (" + ext + L")"; + else + desc = ext; + + result.append(desc.c_str(), desc.size() + 1); // Append NULL too. + result.append(ext.c_str(), ext.size() + 1); + } + + if (include_all_files) { + result.append(all_desc.c_str(), all_desc.size() + 1); + result.append(all_ext.c_str(), all_ext.size() + 1); + } + + result.append(1, '\0'); // Double NULL required. + return result; +} + +std::wstring GetDescriptionFromMimeType(const std::string& mime_type) { + // Check for wild card mime types and return an appropriate description. + static const struct { + const char* mime_type; + int string_id; + } kWildCardMimeTypes[] = { + { "audio", IDS_APP_AUDIO_FILES }, + { "image", IDS_APP_IMAGE_FILES }, + { "text", IDS_APP_TEXT_FILES }, + { "video", IDS_APP_VIDEO_FILES }, + }; + + for (size_t i = 0; i < arraysize(kWildCardMimeTypes); ++i) { + if (mime_type == std::string(kWildCardMimeTypes[i].mime_type) + "/*") + return l10n_util::GetStringUTF16(kWildCardMimeTypes[i].string_id); + } + + return std::wstring(); +} + +std::wstring GetFilterString( + const std::vector& accept_filters) { + std::vector extensions; + std::vector descriptions; + + for (size_t i = 0; i < accept_filters.size(); ++i) { + const base::string16& filter = accept_filters[i]; + if (filter.empty()) + continue; + + size_t sep_index = filter.find('|'); + if (sep_index != base::string16::npos) { + // Treat as a filter of the form "Filter Name|.ext1;.ext2;.ext3". + const base::string16& desc = filter.substr(0, sep_index); + std::vector ext; + base::SplitString(filter.substr(sep_index + 1), ';', &ext); + std::wstring ext_str; + for (size_t x = 0; x < ext.size(); ++x) { + const base::string16& file_ext = ext[x]; + if (!file_ext.empty() && file_ext[0] == '.') { + if (!ext_str.empty()) + ext_str += L";"; + ext_str += L"*" + file_ext; + } + } + if (!ext_str.empty()) { + extensions.push_back(ext_str); + descriptions.push_back(desc); + } + } else if (filter[0] == L'.') { + // Treat as an extension beginning with the '.' character. + extensions.push_back(L"*" + filter); + descriptions.push_back(std::wstring()); + } else { + // Otherwise convert mime type to one or more extensions. + const std::string& ascii = base::UTF16ToASCII(filter); + std::vector ext; + std::wstring ext_str; + net::GetExtensionsForMimeType(ascii, &ext); + if (!ext.empty()) { + for (size_t x = 0; x < ext.size(); ++x) { + if (x != 0) + ext_str += L";"; + ext_str += L"*." + ext[x]; + } + extensions.push_back(ext_str); + descriptions.push_back(GetDescriptionFromMimeType(ascii)); + } + } + } + + return FormatFilterForExtensions(extensions, descriptions, true); +} + +// from chrome/browser/views/shell_dialogs_win.cc + +bool RunOpenFileDialog(const CefBrowserHostImpl::FileChooserParams& params, + HWND owner, + int* filter_index, + base::FilePath* path) { + OPENFILENAME ofn; + + // We must do this otherwise the ofn's FlagsEx may be initialized to random + // junk in release builds which can cause the Places Bar not to show up! + ZeroMemory(&ofn, sizeof(ofn)); + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = owner; + + wchar_t filename[MAX_PATH] = {0}; + + ofn.lpstrFile = filename; + ofn.nMaxFile = MAX_PATH; + + std::wstring directory; + if (!params.default_file_name.empty()) { + if (params.default_file_name.EndsWithSeparator()) { + // The value is only a directory. + directory = params.default_file_name.value(); + } else { + // The value is a file name and possibly a directory. + base::wcslcpy(filename, params.default_file_name.value().c_str(), + arraysize(filename)); + directory = params.default_file_name.DirName().value(); + } + } + if (!directory.empty()) + ofn.lpstrInitialDir = directory.c_str(); + + std::wstring title; + if (!params.title.empty()) + title = params.title; + else + title = l10n_util::GetStringUTF16(IDS_OPEN_FILE_DIALOG_TITLE); + if (!title.empty()) + ofn.lpstrTitle = title.c_str(); + + // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory + // without having to close Chrome first. + ofn.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER | + OFN_ENABLESIZING; + if (params.hidereadonly) + ofn.Flags |= OFN_HIDEREADONLY; + + const std::wstring& filter = GetFilterString(params.accept_types); + if (!filter.empty()) { + ofn.lpstrFilter = filter.c_str(); + // Indices into |lpstrFilter| start at 1. + ofn.nFilterIndex = *filter_index + 1; + } + + bool success = !!GetOpenFileName(&ofn); + if (success) { + *filter_index = ofn.nFilterIndex == 0 ? 0 : ofn.nFilterIndex - 1; + *path = base::FilePath(filename); + } + return success; +} + +bool RunOpenMultiFileDialog(const CefBrowserHostImpl::FileChooserParams& params, + HWND owner, + int* filter_index, + std::vector* paths) { + OPENFILENAME ofn; + + // We must do this otherwise the ofn's FlagsEx may be initialized to random + // junk in release builds which can cause the Places Bar not to show up! + ZeroMemory(&ofn, sizeof(ofn)); + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = owner; + + scoped_ptr filename(new wchar_t[UNICODE_STRING_MAX_CHARS]); + filename[0] = 0; + + ofn.lpstrFile = filename.get(); + ofn.nMaxFile = UNICODE_STRING_MAX_CHARS; + + std::wstring directory; + if (!params.default_file_name.empty()) { + if (params.default_file_name.EndsWithSeparator()) { + // The value is only a directory. + directory = params.default_file_name.value(); + } else { + // The value is a file name and possibly a directory. + directory = params.default_file_name.DirName().value(); + } + } + if (!directory.empty()) + ofn.lpstrInitialDir = directory.c_str(); + + std::wstring title; + if (!params.title.empty()) + title = params.title; + else + title = l10n_util::GetStringUTF16(IDS_OPEN_FILES_DIALOG_TITLE); + if (!title.empty()) + ofn.lpstrTitle = title.c_str(); + + // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory + // without having to close Chrome first. + ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | + OFN_ALLOWMULTISELECT | OFN_ENABLESIZING; + if (params.hidereadonly) + ofn.Flags |= OFN_HIDEREADONLY; + + const std::wstring& filter = GetFilterString(params.accept_types); + if (!filter.empty()) { + ofn.lpstrFilter = filter.c_str(); + // Indices into |lpstrFilter| start at 1. + ofn.nFilterIndex = *filter_index + 1; + } + + bool success = !!GetOpenFileName(&ofn); + + if (success) { + std::vector files; + const wchar_t* selection = ofn.lpstrFile; + while (*selection) { // Empty string indicates end of list. + files.push_back(base::FilePath(selection)); + // Skip over filename and null-terminator. + selection += files.back().value().length() + 1; + } + if (files.empty()) { + success = false; + } else if (files.size() == 1) { + // When there is one file, it contains the path and filename. + paths->swap(files); + } else { + // Otherwise, the first string is the path, and the remainder are + // filenames. + std::vector::iterator path = files.begin(); + for (std::vector::iterator file = path + 1; + file != files.end(); ++file) { + paths->push_back(path->Append(*file)); + } + } + } + + if (success) + *filter_index = ofn.nFilterIndex == 0 ? 0 : ofn.nFilterIndex - 1; + + return success; +} + +// The callback function for when the select folder dialog is opened. +int CALLBACK BrowseCallbackProc(HWND window, + UINT message, + LPARAM parameter, + LPARAM data) +{ + if (message == BFFM_INITIALIZED) { + // WParam is TRUE since passing a path. + // data lParam member of the BROWSEINFO structure. + SendMessage(window, BFFM_SETSELECTION, TRUE, (LPARAM)data); + } + return 0; +} + +bool RunOpenFolderDialog(const CefBrowserHostImpl::FileChooserParams& params, + HWND owner, + base::FilePath* path) { + wchar_t dir_buffer[MAX_PATH + 1] = {0}; + + bool result = false; + BROWSEINFO browse_info = {0}; + browse_info.hwndOwner = owner; + browse_info.pszDisplayName = dir_buffer; + browse_info.ulFlags = BIF_USENEWUI | BIF_RETURNONLYFSDIRS; + + std::wstring title; + if (!params.title.empty()) + title = params.title; + else + title = l10n_util::GetStringUTF16(IDS_SELECT_FOLDER_DIALOG_TITLE); + if (!title.empty()) + browse_info.lpszTitle = title.c_str(); + + const std::wstring& file_path = params.default_file_name.value(); + if (!file_path.empty()) { + // Highlight the current value. + browse_info.lParam = (LPARAM)file_path.c_str(); + browse_info.lpfn = &BrowseCallbackProc; + } + + LPITEMIDLIST list = SHBrowseForFolder(&browse_info); + if (list) { + STRRET out_dir_buffer; + ZeroMemory(&out_dir_buffer, sizeof(out_dir_buffer)); + out_dir_buffer.uType = STRRET_WSTR; + base::win::ScopedComPtr shell_folder; + if (SHGetDesktopFolder(shell_folder.Receive()) == NOERROR) { + HRESULT hr = shell_folder->GetDisplayNameOf(list, SHGDN_FORPARSING, + &out_dir_buffer); + if (SUCCEEDED(hr) && out_dir_buffer.uType == STRRET_WSTR) { + *path = base::FilePath(out_dir_buffer.pOleStr); + CoTaskMemFree(out_dir_buffer.pOleStr); + result = true; + } else { + // Use old way if we don't get what we want. + wchar_t old_out_dir_buffer[MAX_PATH + 1]; + if (SHGetPathFromIDList(list, old_out_dir_buffer)) { + *path = base::FilePath(old_out_dir_buffer); + result = true; + } + } + } + CoTaskMemFree(list); + } + + return result; +} + +bool RunSaveFileDialog(const CefBrowserHostImpl::FileChooserParams& params, + HWND owner, + int* filter_index, + base::FilePath* path) { + OPENFILENAME ofn; + + // We must do this otherwise the ofn's FlagsEx may be initialized to random + // junk in release builds which can cause the Places Bar not to show up! + ZeroMemory(&ofn, sizeof(ofn)); + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = owner; + + wchar_t filename[MAX_PATH] = {0}; + + ofn.lpstrFile = filename; + ofn.nMaxFile = MAX_PATH; + + std::wstring directory; + if (!params.default_file_name.empty()) { + if (params.default_file_name.EndsWithSeparator()) { + // The value is only a directory. + directory = params.default_file_name.value(); + } else { + // The value is a file name and possibly a directory. + base::wcslcpy(filename, params.default_file_name.value().c_str(), + arraysize(filename)); + directory = params.default_file_name.DirName().value(); + } + } + if (!directory.empty()) + ofn.lpstrInitialDir = directory.c_str(); + + std::wstring title; + if (!params.title.empty()) + title = params.title; + else + title = l10n_util::GetStringUTF16(IDS_SAVE_AS_DIALOG_TITLE); + if (!title.empty()) + ofn.lpstrTitle = title.c_str(); + + // We use OFN_NOCHANGEDIR so that the user can rename or delete the directory + // without having to close Chrome first. + ofn.Flags = OFN_EXPLORER | OFN_ENABLESIZING | OFN_NOCHANGEDIR | + OFN_PATHMUSTEXIST; + if (params.hidereadonly) + ofn.Flags |= OFN_HIDEREADONLY; + if (params.overwriteprompt) + ofn.Flags |= OFN_OVERWRITEPROMPT; + + const std::wstring& filter = GetFilterString(params.accept_types); + if (!filter.empty()) { + ofn.lpstrFilter = filter.c_str(); + // Indices into |lpstrFilter| start at 1. + ofn.nFilterIndex = *filter_index + 1; + } + + bool success = !!GetSaveFileName(&ofn); + if (success) { + *filter_index = ofn.nFilterIndex == 0 ? 0 : ofn.nFilterIndex - 1; + *path = base::FilePath(filename); + } + return success; +} + + +// According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp: +// "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in +// ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6 +// support URLS of 2083 chars in length, 2K is safe." +const int kMaxAddressLengthChars = 2048; + +bool HasExternalHandler(const std::string& scheme) { + base::win::RegKey key; + const std::wstring registry_path = + base::ASCIIToUTF16(scheme + "\\shell\\open\\command"); + key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ); + if (key.Valid()) { + DWORD size = 0; + key.ReadValue(NULL, NULL, &size, NULL); + if (size > 2) { + // ShellExecute crashes the process when the command is empty. + // We check for "2" because it always returns the trailing NULL. + return true; + } + } + + return false; +} + +WORD KeyStatesToWord() { + static const USHORT kHighBitMaskShort = 0x8000; + WORD result = 0; + + if (GetKeyState(VK_CONTROL) & kHighBitMaskShort) + result |= MK_CONTROL; + if (GetKeyState(VK_SHIFT) & kHighBitMaskShort) + result |= MK_SHIFT; + if (GetKeyState(VK_LBUTTON) & kHighBitMaskShort) + result |= MK_LBUTTON; + if (GetKeyState(VK_MBUTTON) & kHighBitMaskShort) + result |= MK_MBUTTON; + if (GetKeyState(VK_RBUTTON) & kHighBitMaskShort) + result |= MK_RBUTTON; + return result; +} + +// From content/common/cursors/webcursor_win.cc. + +using blink::WebCursorInfo; + +LPCWSTR ToCursorID(WebCursorInfo::Type type) { + switch (type) { + case WebCursorInfo::TypePointer: + return IDC_ARROW; + case WebCursorInfo::TypeCross: + return IDC_CROSS; + case WebCursorInfo::TypeHand: + return IDC_HAND; + case WebCursorInfo::TypeIBeam: + return IDC_IBEAM; + case WebCursorInfo::TypeWait: + return IDC_WAIT; + case WebCursorInfo::TypeHelp: + return IDC_HELP; + case WebCursorInfo::TypeEastResize: + return IDC_SIZEWE; + case WebCursorInfo::TypeNorthResize: + return IDC_SIZENS; + case WebCursorInfo::TypeNorthEastResize: + return IDC_SIZENESW; + case WebCursorInfo::TypeNorthWestResize: + return IDC_SIZENWSE; + case WebCursorInfo::TypeSouthResize: + return IDC_SIZENS; + case WebCursorInfo::TypeSouthEastResize: + return IDC_SIZENWSE; + case WebCursorInfo::TypeSouthWestResize: + return IDC_SIZENESW; + case WebCursorInfo::TypeWestResize: + return IDC_SIZEWE; + case WebCursorInfo::TypeNorthSouthResize: + return IDC_SIZENS; + case WebCursorInfo::TypeEastWestResize: + return IDC_SIZEWE; + case WebCursorInfo::TypeNorthEastSouthWestResize: + return IDC_SIZENESW; + case WebCursorInfo::TypeNorthWestSouthEastResize: + return IDC_SIZENWSE; + case WebCursorInfo::TypeColumnResize: + return MAKEINTRESOURCE(IDC_COLRESIZE); + case WebCursorInfo::TypeRowResize: + return MAKEINTRESOURCE(IDC_ROWRESIZE); + case WebCursorInfo::TypeMiddlePanning: + return MAKEINTRESOURCE(IDC_PAN_MIDDLE); + case WebCursorInfo::TypeEastPanning: + return MAKEINTRESOURCE(IDC_PAN_EAST); + case WebCursorInfo::TypeNorthPanning: + return MAKEINTRESOURCE(IDC_PAN_NORTH); + case WebCursorInfo::TypeNorthEastPanning: + return MAKEINTRESOURCE(IDC_PAN_NORTH_EAST); + case WebCursorInfo::TypeNorthWestPanning: + return MAKEINTRESOURCE(IDC_PAN_NORTH_WEST); + case WebCursorInfo::TypeSouthPanning: + return MAKEINTRESOURCE(IDC_PAN_SOUTH); + case WebCursorInfo::TypeSouthEastPanning: + return MAKEINTRESOURCE(IDC_PAN_SOUTH_EAST); + case WebCursorInfo::TypeSouthWestPanning: + return MAKEINTRESOURCE(IDC_PAN_SOUTH_WEST); + case WebCursorInfo::TypeWestPanning: + return MAKEINTRESOURCE(IDC_PAN_WEST); + case WebCursorInfo::TypeMove: + return IDC_SIZEALL; + case WebCursorInfo::TypeVerticalText: + return MAKEINTRESOURCE(IDC_VERTICALTEXT); + case WebCursorInfo::TypeCell: + return MAKEINTRESOURCE(IDC_CELL); + case WebCursorInfo::TypeContextMenu: + return MAKEINTRESOURCE(IDC_ARROW); + case WebCursorInfo::TypeAlias: + return MAKEINTRESOURCE(IDC_ALIAS); + case WebCursorInfo::TypeProgress: + return IDC_APPSTARTING; + case WebCursorInfo::TypeNoDrop: + return IDC_NO; + case WebCursorInfo::TypeCopy: + return MAKEINTRESOURCE(IDC_COPYCUR); + case WebCursorInfo::TypeNone: + return MAKEINTRESOURCE(IDC_CURSOR_NONE); + case WebCursorInfo::TypeNotAllowed: + return IDC_NO; + case WebCursorInfo::TypeZoomIn: + return MAKEINTRESOURCE(IDC_ZOOMIN); + case WebCursorInfo::TypeZoomOut: + return MAKEINTRESOURCE(IDC_ZOOMOUT); + case WebCursorInfo::TypeGrab: + return MAKEINTRESOURCE(IDC_HAND_GRAB); + case WebCursorInfo::TypeGrabbing: + return MAKEINTRESOURCE(IDC_HAND_GRABBING); + } + NOTREACHED(); + return NULL; +} + +bool IsSystemCursorID(LPCWSTR cursor_id) { + return cursor_id >= IDC_ARROW; // See WinUser.h +} + +} // namespace + +// static +void CefBrowserHostImpl::RegisterWindowClass() { + // Register the window class + WNDCLASSEX wcex = { + /* cbSize = */ sizeof(WNDCLASSEX), + /* style = */ CS_HREDRAW | CS_VREDRAW, + /* lpfnWndProc = */ CefBrowserHostImpl::WndProc, + /* cbClsExtra = */ 0, + /* cbWndExtra = */ 0, + /* hInstance = */ ::GetModuleHandle(NULL), + /* hIcon = */ NULL, + /* hCursor = */ LoadCursor(NULL, IDC_ARROW), + /* hbrBackground = */ 0, + /* lpszMenuName = */ NULL, + /* lpszClassName = */ CefBrowserHostImpl::GetWndClass(), + /* hIconSm = */ NULL, + }; + RegisterClassEx(&wcex); +} + +// static +LPCTSTR CefBrowserHostImpl::GetWndClass() { + return L"CefBrowserWindow"; +} + +// static +LRESULT CALLBACK CefBrowserHostImpl::WndProc(HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam) { + CefBrowserHostImpl* browser = + static_cast(gfx::GetWindowUserData(hwnd)); + + switch (message) { + case WM_CLOSE: + // Protect against multiple requests to close while the close is pending. + if (browser && browser->destruction_state() <= DESTRUCTION_STATE_PENDING) { + if (browser->destruction_state() == DESTRUCTION_STATE_NONE) { + // Request that the browser close. + browser->CloseBrowser(false); + } + + // Cancel the close. + return 0; + } + + // Allow the close. + break; + + case WM_DESTROY: + if (browser) { + // Clear the user data pointer. + gfx::SetWindowUserData(hwnd, NULL); + + // Force the browser to be destroyed and release the reference added in + // PlatformCreateWindow(). + browser->WindowDestroyed(); + } + return 0; + + case WM_SIZE: + if (browser && browser->window_widget_) { + // Pass window resize events to the HWND for the DesktopNativeWidgetAura + // root window. Passing size 0x0 (wParam == SIZE_MINIMIZED, for example) + // will cause the widget to be hidden which reduces resource usage. + RECT rc; + GetClientRect(hwnd, &rc); + SetWindowPos(HWNDForWidget(browser->window_widget_), NULL, + rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, + SWP_NOZORDER); + } + return 0; + + case WM_MOVING: + case WM_MOVE: + if (browser) + browser->NotifyMoveOrResizeStarted(); + return 0; + + case WM_SETFOCUS: + if (browser) + browser->SetFocus(true); + return 0; + + case WM_ERASEBKGND: + return 0; + } + + return DefWindowProc(hwnd, message, wParam, lParam); +} + +ui::PlatformCursor CefBrowserHostImpl::GetPlatformCursor( + blink::WebCursorInfo::Type type) { + HMODULE module_handle = NULL; + const wchar_t* cursor_id = ToCursorID(type); + if (!IsSystemCursorID(cursor_id)) { + module_handle = ::GetModuleHandle( + CefContentBrowserClient::Get()->GetResourceDllName()); + if (!module_handle) + module_handle = ::GetModuleHandle(NULL); + } + + return LoadCursor(module_handle, cursor_id); +} + +bool CefBrowserHostImpl::PlatformCreateWindow() { + std::wstring windowName(CefString(&window_info_.window_name)); + + // Create the new browser window. + window_info_.window = CreateWindowEx(window_info_.ex_style, + GetWndClass(), windowName.c_str(), window_info_.style, + window_info_.x, window_info_.y, window_info_.width, + window_info_.height, window_info_.parent_window, window_info_.menu, + ::GetModuleHandle(NULL), NULL); + + // It's possible for CreateWindowEx to fail if the parent window was + // destroyed between the call to CreateBrowser and the above one. + DCHECK(window_info_.window != NULL); + if (!window_info_.window) + return false; + + // Set window user data to this object for future reference from the window + // procedure. + gfx::SetWindowUserData(window_info_.window, this); + + // Add a reference that will be released in the WM_DESTROY handler. + AddRef(); + + RECT cr; + GetClientRect(window_info_.window, &cr); + + DCHECK(!window_widget_); + + SkColor background_color = SK_ColorWHITE; + const CefSettings& settings = CefContext::Get()->settings(); + if (CefColorGetA(settings.background_color) > 0) { + background_color = SkColorSetRGB( + CefColorGetR(settings.background_color), + CefColorGetG(settings.background_color), + CefColorGetB(settings.background_color)); + } + + CefWindowDelegateView* delegate_view = + new CefWindowDelegateView(background_color); + delegate_view->Init(window_info_.window, + web_contents(), + gfx::Rect(0, 0, cr.right, cr.bottom)); + + window_widget_ = delegate_view->GetWidget(); + window_widget_->Show(); + + return true; +} + +void CefBrowserHostImpl::PlatformCloseWindow() { + if (window_info_.window != NULL) { + HWND frameWnd = GetAncestor(window_info_.window, GA_ROOT); + PostMessage(frameWnd, WM_CLOSE, 0, 0); + } +} + +void CefBrowserHostImpl::PlatformSizeTo(int width, int height) { + RECT rect = {0, 0, width, height}; + DWORD style = GetWindowLong(window_info_.window, GWL_STYLE); + DWORD ex_style = GetWindowLong(window_info_.window, GWL_EXSTYLE); + bool has_menu = !(style & WS_CHILD) && (GetMenu(window_info_.window) != NULL); + + // The size value is for the client area. Calculate the whole window size + // based on the current style. + AdjustWindowRectEx(&rect, style, has_menu, ex_style); + + // Size the window. + SetWindowPos(window_info_.window, NULL, 0, 0, rect.right, + rect.bottom, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); +} + +void CefBrowserHostImpl::PlatformSetFocus(bool focus) { + if (!focus) + return; + + if (web_contents_) { + // Give logical focus to the RenderWidgetHostViewAura in the views + // hierarchy. This does not change the native keyboard focus. + web_contents_->Focus(); + } + + if (window_widget_) { + // Give native focus to the DesktopNativeWidgetAura for the root window. + // Needs to be done via the HWND so that keyboard focus is assigned + // correctly. DesktopNativeWidgetAura will update focus state on the + // aura::Window when WM_SETFOCUS and WM_KILLFOCUS are received. + ::SetFocus(HWNDForWidget(window_widget_)); + } +} + +CefWindowHandle CefBrowserHostImpl::PlatformGetWindowHandle() { + return IsWindowless() ? window_info_.parent_window : window_info_.window; +} + +bool CefBrowserHostImpl::PlatformViewText(const std::string& text) { + CEF_REQUIRE_UIT(); + + std::string str = text; + scoped_refptr str_ref = + base::RefCountedString::TakeString(&str); + CEF_POST_TASK(CEF_FILET, base::Bind(WriteTempFileAndView, str_ref)); + return true; +} + +void CefBrowserHostImpl::PlatformHandleKeyboardEvent( + const content::NativeWebKeyboardEvent& event) { + // Any unhandled keyboard/character messages are sent to DefWindowProc so that + // shortcut keys work correctly. + if (event.os_event) { + const MSG& msg = event.os_event->native_event(); + DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam); + } else { + MSG msg = {}; + + msg.hwnd = PlatformGetWindowHandle(); + if (!msg.hwnd) + return; + + switch (event.type) { + case blink::WebInputEvent::RawKeyDown: + msg.message = event.isSystemKey ? WM_SYSKEYDOWN : WM_KEYDOWN; + break; + case blink::WebInputEvent::KeyUp: + msg.message = event.isSystemKey ? WM_SYSKEYUP : WM_KEYUP; + break; + case blink::WebInputEvent::Char: + msg.message = event.isSystemKey ? WM_SYSCHAR: WM_CHAR; + break; + default: + NOTREACHED(); + return; + } + + msg.wParam = event.windowsKeyCode; + + UINT scan_code = ::MapVirtualKeyW(event.windowsKeyCode, MAPVK_VK_TO_VSC); + msg.lParam = (scan_code << 16) | // key scan code + 1; // key repeat count + if (event.modifiers & content::NativeWebKeyboardEvent::AltKey) + msg.lParam |= (1 << 29); + + DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam); + } +} + +void CefBrowserHostImpl::PlatformRunFileChooser( + const FileChooserParams& params, + RunFileChooserCallback callback) { + int filter_index = params.selected_accept_filter; + std::vector files; + + HWND owner = PlatformGetWindowHandle(); + + if (params.mode == content::FileChooserParams::Open) { + base::FilePath file; + if (RunOpenFileDialog(params, owner, &filter_index, &file)) + files.push_back(file); + } else if (params.mode == content::FileChooserParams::OpenMultiple) { + RunOpenMultiFileDialog(params, owner, &filter_index, &files); + } else if (params.mode == content::FileChooserParams::UploadFolder) { + base::FilePath file; + if (RunOpenFolderDialog(params, owner, &file)) + files.push_back(file); + } else if (params.mode == content::FileChooserParams::Save) { + base::FilePath file; + if (RunSaveFileDialog(params, owner, &filter_index, &file)) + files.push_back(file); + } else { + NOTIMPLEMENTED(); + } + + callback.Run(filter_index, files); +} + +void CefBrowserHostImpl::PlatformHandleExternalProtocol(const GURL& url) { + if (CEF_CURRENTLY_ON_FILET()) { + if (!HasExternalHandler(url.scheme())) + return; + + const std::string& address = url.spec(); + if (address.length() > kMaxAddressLengthChars) + return; + + ShellExecuteA(NULL, "open", address.c_str(), NULL, NULL, SW_SHOWNORMAL); + } else { + // Execute on the FILE thread. + CEF_POST_TASK(CEF_FILET, + base::Bind(&CefBrowserHostImpl::PlatformHandleExternalProtocol, this, + url)); + } +} + +void CefBrowserHostImpl::PlatformTranslateKeyEvent( + content::NativeWebKeyboardEvent& result, const CefKeyEvent& key_event) { + result.timeStampSeconds = GetMessageTime() / 1000.0; + + result.windowsKeyCode = key_event.windows_key_code; + result.nativeKeyCode = key_event.native_key_code; + result.isSystemKey = key_event.is_system_key ? 1 : 0; + switch (key_event.type) { + case KEYEVENT_RAWKEYDOWN: + case KEYEVENT_KEYDOWN: + result.type = blink::WebInputEvent::RawKeyDown; + break; + case KEYEVENT_KEYUP: + result.type = blink::WebInputEvent::KeyUp; + break; + case KEYEVENT_CHAR: + result.type = blink::WebInputEvent::Char; + break; + default: + NOTREACHED(); + } + + if (result.type == blink::WebInputEvent::Char || + result.type == blink::WebInputEvent::RawKeyDown) { + result.text[0] = result.windowsKeyCode; + result.unmodifiedText[0] = result.windowsKeyCode; + } + if (result.type != blink::WebInputEvent::Char) + result.setKeyIdentifierFromWindowsKeyCode(); + + result.modifiers |= TranslateModifiers(key_event.modifiers); +} + +void CefBrowserHostImpl::PlatformTranslateClickEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event, + CefBrowserHost::MouseButtonType type, + bool mouseUp, int clickCount) { + PlatformTranslateMouseEvent(result, mouse_event); + + switch (type) { + case MBT_LEFT: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonLeft; + break; + case MBT_MIDDLE: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonMiddle; + break; + case MBT_RIGHT: + result.type = mouseUp ? blink::WebInputEvent::MouseUp : + blink::WebInputEvent::MouseDown; + result.button = blink::WebMouseEvent::ButtonRight; + break; + default: + NOTREACHED(); + } + + result.clickCount = clickCount; +} + +void CefBrowserHostImpl::PlatformTranslateMoveEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event, + bool mouseLeave) { + PlatformTranslateMouseEvent(result, mouse_event); + + if (!mouseLeave) { + result.type = blink::WebInputEvent::MouseMove; + if (mouse_event.modifiers & EVENTFLAG_LEFT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonLeft; + else if (mouse_event.modifiers & EVENTFLAG_MIDDLE_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonMiddle; + else if (mouse_event.modifiers & EVENTFLAG_RIGHT_MOUSE_BUTTON) + result.button = blink::WebMouseEvent::ButtonRight; + else + result.button = blink::WebMouseEvent::ButtonNone; + } else { + result.type = blink::WebInputEvent::MouseLeave; + result.button = blink::WebMouseEvent::ButtonNone; + } + + result.clickCount = 0; +} + +void CefBrowserHostImpl::PlatformTranslateWheelEvent( + blink::WebMouseWheelEvent& result, + const CefMouseEvent& mouse_event, + int deltaX, int deltaY) { + PlatformTranslateMouseEvent(result, mouse_event); + + result.type = blink::WebInputEvent::MouseWheel; + result.button = blink::WebMouseEvent::ButtonNone; + + float wheelDelta; + bool horizontalScroll = false; + + wheelDelta = static_cast(deltaY ? deltaY : deltaX); + + horizontalScroll = (deltaY == 0); + + static const ULONG defaultScrollCharsPerWheelDelta = 1; + static const FLOAT scrollbarPixelsPerLine = 100.0f / 3.0f; + static const ULONG defaultScrollLinesPerWheelDelta = 3; + wheelDelta /= WHEEL_DELTA; + float scrollDelta = wheelDelta; + if (horizontalScroll) { + ULONG scrollChars = defaultScrollCharsPerWheelDelta; + SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scrollChars, 0); + scrollDelta *= static_cast(scrollChars) * scrollbarPixelsPerLine; + } else { + ULONG scrollLines = defaultScrollLinesPerWheelDelta; + SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0); + if (scrollLines == WHEEL_PAGESCROLL) + result.scrollByPage = true; + if (!result.scrollByPage) + scrollDelta *= static_cast(scrollLines) * scrollbarPixelsPerLine; + } + + // Set scroll amount based on above calculations. WebKit expects positive + // deltaY to mean "scroll up" and positive deltaX to mean "scroll left". + if (horizontalScroll) { + result.deltaX = scrollDelta; + result.wheelTicksX = wheelDelta; + } else { + result.deltaY = scrollDelta; + result.wheelTicksY = wheelDelta; + } +} + +void CefBrowserHostImpl::PlatformTranslateMouseEvent( + blink::WebMouseEvent& result, + const CefMouseEvent& mouse_event) { + // position + result.x = mouse_event.x; + result.y = mouse_event.y; + result.windowX = result.x; + result.windowY = result.y; + result.globalX = result.x; + result.globalY = result.y; + + if (IsWindowless()) { + GetClient()->GetRenderHandler()->GetScreenPoint( + GetBrowser(), + result.x, result.y, + result.globalX, result.globalY); + } else { + POINT globalPoint = { result.x, result.y }; + ClientToScreen(GetWindowHandle(), &globalPoint); + result.globalX = globalPoint.x; + result.globalY = globalPoint.y; + } + + // modifiers + result.modifiers |= TranslateModifiers(mouse_event.modifiers); + + // timestamp + result.timeStampSeconds = GetMessageTime() / 1000.0; +} + +void CefBrowserHostImpl::PlatformNotifyMoveOrResizeStarted() { + if (IsWindowless()) + return; + + if (!window_widget_) + return; + + // Notify DesktopWindowTreeHostWin of move events so that screen rectangle + // information is communicated to the renderer process and popups are + // displayed in the correct location. + views::DesktopWindowTreeHostWin* tree_host = + static_cast( + aura::WindowTreeHost::GetForAcceleratedWidget( + HWNDForWidget(window_widget_))); + DCHECK(tree_host); + if (tree_host) { + // Cast to HWNDMessageHandlerDelegate so we can access HandleMove(). + static_cast(tree_host)->HandleMove(); + } +} diff --git a/libcef/browser/browser_info.cc b/libcef/browser/browser_info.cc new file mode 100644 index 000000000..6ca13c4cd --- /dev/null +++ b/libcef/browser/browser_info.cc @@ -0,0 +1,112 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/browser_info.h" +#include "ipc/ipc_message.h" + +CefBrowserInfo::CefBrowserInfo(int browser_id, bool is_popup) + : browser_id_(browser_id), + is_popup_(is_popup), + is_windowless_(false) { + DCHECK_GT(browser_id, 0); +} + +CefBrowserInfo::~CefBrowserInfo() { +} + +void CefBrowserInfo::set_windowless(bool windowless) { + is_windowless_ = windowless; +} + +void CefBrowserInfo::add_render_view_id( + int render_process_id, int render_routing_id) { + add_render_id(&render_view_id_set_, render_process_id, render_routing_id); +} + +void CefBrowserInfo::add_render_frame_id( + int render_process_id, int render_routing_id) { + add_render_id(&render_frame_id_set_, render_process_id, render_routing_id); +} + +void CefBrowserInfo::remove_render_view_id( + int render_process_id, int render_routing_id) { + remove_render_id(&render_view_id_set_, render_process_id, render_routing_id); +} + +void CefBrowserInfo::remove_render_frame_id( + int render_process_id, int render_routing_id) { + remove_render_id(&render_frame_id_set_, render_process_id, render_routing_id); +} + +bool CefBrowserInfo::is_render_view_id_match( + int render_process_id, int render_routing_id) { + return is_render_id_match(&render_view_id_set_, + render_process_id, + render_routing_id); +} + +bool CefBrowserInfo::is_render_frame_id_match( + int render_process_id, int render_routing_id) { + return is_render_id_match(&render_frame_id_set_, + render_process_id, + render_routing_id); +} + +CefRefPtr CefBrowserInfo::browser() { + base::AutoLock lock_scope(lock_); + return browser_; +} + +void CefBrowserInfo::set_browser(CefRefPtr browser) { + base::AutoLock lock_scope(lock_); + browser_ = browser; +} + +void CefBrowserInfo::add_render_id(RenderIdSet* id_set, + int render_process_id, + int render_routing_id) { + DCHECK_GT(render_process_id, 0); + DCHECK_GT(render_routing_id, 0); + + base::AutoLock lock_scope(lock_); + + if (!id_set->empty()) { + RenderIdSet::const_iterator it = + id_set->find(std::make_pair(render_process_id, render_routing_id)); + if (it != id_set->end()) + return; + } + + id_set->insert(std::make_pair(render_process_id, render_routing_id)); +} + +void CefBrowserInfo::remove_render_id(RenderIdSet* id_set, + int render_process_id, + int render_routing_id) { + DCHECK_GT(render_process_id, 0); + DCHECK_GT(render_routing_id, 0); + + base::AutoLock lock_scope(lock_); + + DCHECK(!id_set->empty()); + if (id_set->empty()) + return; + + bool erased = id_set->erase( + std::make_pair(render_process_id, render_routing_id)) != 0; + DCHECK(erased); +} + +bool CefBrowserInfo::is_render_id_match(const RenderIdSet* id_set, + int render_process_id, + int render_routing_id) { + base::AutoLock lock_scope(lock_); + + if (id_set->empty()) + return false; + + RenderIdSet::const_iterator it = + id_set->find(std::make_pair(render_process_id, render_routing_id)); + return (it != id_set->end()); +} diff --git a/libcef/browser/browser_info.h b/libcef/browser/browser_info.h new file mode 100644 index 000000000..5593ccf06 --- /dev/null +++ b/libcef/browser/browser_info.h @@ -0,0 +1,89 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_INFO_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_INFO_H_ +#pragma once + +#include + +#include "libcef/browser/browser_host_impl.h" +#include "base/memory/ref_counted.h" + +// CefBrowserInfo is used to associate a browser ID and render view/process +// IDs with a particular CefBrowserHostImpl. Render view/process IDs may change +// during the lifetime of a single CefBrowserHostImpl. +// +// CefBrowserInfo objects are managed by CefContentBrowserClient and should not +// be created directly. +class CefBrowserInfo : public base::RefCountedThreadSafe { + public: + CefBrowserInfo(int browser_id, bool is_popup); + + int browser_id() const { return browser_id_; }; + bool is_popup() const { return is_popup_; } + bool is_windowless() const { return is_windowless_; } + + void set_windowless(bool windowless); + + // Adds an ID pair if it doesn't already exist. + void add_render_view_id(int render_process_id, int render_routing_id); + void add_render_frame_id(int render_process_id, int render_routing_id); + + // Remove an ID pair if it exists. + void remove_render_view_id(int render_process_id, int render_routing_id); + void remove_render_frame_id(int render_process_id, int render_routing_id); + + // Returns true if this browser matches the specified ID pair. + bool is_render_view_id_match(int render_process_id, int render_routing_id); + bool is_render_frame_id_match(int render_process_id, int render_routing_id); + + CefRefPtr browser(); + void set_browser(CefRefPtr browser); + + private: + friend class base::RefCountedThreadSafe; + + ~CefBrowserInfo(); + + typedef std::set > RenderIdSet; + + void add_render_id(RenderIdSet* id_set, + int render_process_id, + int render_routing_id); + void remove_render_id(RenderIdSet* id_set, + int render_process_id, + int render_routing_id); + bool is_render_id_match(const RenderIdSet* id_set, + int render_process_id, + int render_routing_id); + + int browser_id_; + bool is_popup_; + bool is_windowless_; + + base::Lock lock_; + + // The below members must be protected by |lock_|. + + // Set of mapped (process_id, routing_id) pairs. Keeping this set is + // necessary for the following reasons: + // 1. When navigating cross-origin the new (pending) RenderViewHost will be + // created before the old (current) RenderViewHost is destroyed. + // 2. When canceling and asynchronously continuing navigation of the same URL + // a new RenderViewHost may be created for the first (canceled) navigation + // and then destroyed as a result of the second (allowed) navigation. + // 3. Out-of-process iframes have their own render IDs which must also be + // associated with the host browser. + RenderIdSet render_view_id_set_; + RenderIdSet render_frame_id_set_; + + // May be NULL if the browser has not yet been created or if the browser has + // been destroyed. + CefRefPtr browser_; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserInfo); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_INFO_H_ diff --git a/libcef/browser/browser_main.cc b/libcef/browser/browser_main.cc new file mode 100644 index 000000000..fbadf3349 --- /dev/null +++ b/libcef/browser/browser_main.cc @@ -0,0 +1,206 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_main.h" + +#include + +#include "libcef/browser/browser_context_impl.h" +#include "libcef/browser/browser_message_loop.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/devtools_delegate.h" +#include "libcef/common/net_resource_provider.h" + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/message_loop/message_loop.h" +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/net/proxy_service_factory.h" +#include "components/user_prefs/user_prefs.h" +#include "content/browser/webui/content_web_ui_controller_factory.h" +#include "content/public/browser/gpu_data_manager.h" +#include "content/public/browser/web_ui_controller_factory.h" +#include "content/public/common/content_switches.h" +#include "net/base/net_module.h" +#include "net/proxy/proxy_resolver_v8.h" +#include "ui/base/resource/resource_bundle.h" + +#if defined(USE_AURA) +#include "ui/aura/env.h" +#include "ui/gfx/screen.h" +#include "ui/views/test/desktop_test_views_delegate.h" +#include "ui/views/widget/desktop_aura/desktop_screen.h" + +#if defined(OS_WIN) +#include "ui/base/cursor/cursor_loader_win.h" +#endif +#endif // defined(USE_AURA) + +#if defined(USE_AURA) && defined(OS_LINUX) +#include "ui/base/ime/input_method_initializer.h" +#endif + +#if defined(OS_LINUX) +#include "libcef/browser/printing/print_dialog_linux.h" +#endif + +CefBrowserMainParts::CefBrowserMainParts( + const content::MainFunctionParams& parameters) + : BrowserMainParts(), + devtools_delegate_(NULL) { +} + +CefBrowserMainParts::~CefBrowserMainParts() { +} + +void CefBrowserMainParts::PreMainMessageLoopStart() { + if (!base::MessageLoop::current()) { + // Create the browser message loop. + message_loop_.reset(new CefBrowserMessageLoop()); + message_loop_->set_thread_name("CrBrowserMain"); + } +} + +void CefBrowserMainParts::PreEarlyInitialization() { +#if defined(USE_AURA) && defined(OS_LINUX) + // TODO(linux): Consider using a real input method or + // views::LinuxUI::SetInstance. + ui::InitializeInputMethodForTesting(); +#endif +} + +void CefBrowserMainParts::ToolkitInitialized() { +#if defined(USE_AURA) + CHECK(aura::Env::GetInstance()); + + DCHECK(!views::ViewsDelegate::views_delegate); + new views::DesktopTestViewsDelegate; + +#if defined(OS_WIN) + ui::CursorLoaderWin::SetCursorResourceModule( + CefContentBrowserClient::Get()->GetResourceDllName()); +#endif +#endif // defined(USE_AURA) +} + +void CefBrowserMainParts::PostMainMessageLoopStart() { + // Don't use the default WebUI controller factory because is conflicts with + // CEF's internal handling of "chrome://tracing". + content::WebUIControllerFactory::UnregisterFactoryForTesting( + content::ContentWebUIControllerFactory::GetInstance()); + +#if defined(OS_LINUX) + printing::PrintingContextLinux::SetCreatePrintDialogFunction( + &CefPrintDialogLinux::CreatePrintDialog); +#endif +} + +int CefBrowserMainParts::PreCreateThreads() { + PlatformInitialize(); + net::NetModule::SetResourceProvider(&NetResourceProvider); + + // Initialize the GpuDataManager before IO access restrictions are applied and + // before the IO thread is started. + content::GpuDataManager::GetInstance(); + +#if defined(USE_AURA) + gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, + views::CreateDesktopScreen()); +#endif + + // Initialize user preferences. + pref_store_ = new CefBrowserPrefStore(); + pref_store_->SetInitializationCompleted(); + pref_service_ = pref_store_->CreateService().Pass(); + + // Initialize the V8 proxy integration. + net::ProxyResolverV8::EnsureIsolateCreated(); + + // Initialize proxy configuration tracker. + pref_proxy_config_tracker_.reset( + ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState( + pref_service_.get())); + + return 0; +} + +void CefBrowserMainParts::PreMainMessageLoopRun() { + // Create the global browser context. + global_browser_context_.reset(new CefBrowserContextImpl()); + + // Initialize the proxy configuration service. This needs to occur before + // CefURLRequestContextGetter::GetURLRequestContext() is called for the + // first time. + proxy_config_service_.reset( + ProxyServiceFactory::CreateProxyConfigService( + pref_proxy_config_tracker_.get())); + + // Initialize the request context getter. This indirectly triggers a call + // to CefURLRequestContextGetter::GetURLRequestContext() on the IO thread. + global_request_context_ = global_browser_context_->GetRequestContext(); + + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { + std::string port_str = + command_line->GetSwitchValueASCII(switches::kRemoteDebuggingPort); + int port; + if (base::StringToInt(port_str, &port) && port > 0 && port < 65535) { + devtools_delegate_ = + new CefDevToolsDelegate(static_cast(port)); + } else { + LOG(WARNING) << "Invalid http debugger port number " << port; + } + } + + // Spell checking support and possibly other subsystems retrieve the + // PrefService associated with a BrowserContext via UserPrefs::Get(). + user_prefs::UserPrefs::Set(browser_context(), pref_service()); +} + +void CefBrowserMainParts::PostMainMessageLoopRun() { + if (devtools_delegate_) { + devtools_delegate_->Stop(); + devtools_delegate_ = NULL; + } + pref_proxy_config_tracker_->DetachFromPrefService(); + + // Only the global browser context should still exist. + DCHECK(browser_contexts_.empty()); + browser_contexts_.clear(); + + global_request_context_ = NULL; + global_browser_context_.reset(); +} + +void CefBrowserMainParts::PostDestroyThreads() { + pref_proxy_config_tracker_.reset(NULL); + +#if defined(USE_AURA) + aura::Env::DeleteInstance(); + delete views::ViewsDelegate::views_delegate; +#endif + + PlatformCleanup(); +} + +void CefBrowserMainParts::AddBrowserContext(CefBrowserContext* context) { + // Spell checking support and possibly other subsystems retrieve the + // PrefService associated with a BrowserContext via UserPrefs::Get(). + user_prefs::UserPrefs::Set(context, pref_service()); + + browser_contexts_.push_back(context); +} + +void CefBrowserMainParts::RemoveBrowserContext(CefBrowserContext* context) { + ScopedVector::iterator it = browser_contexts_.begin(); + for (; it != browser_contexts_.end(); ++it) { + if (*it == context) { + browser_contexts_.erase(it); + return; + } + } + + NOTREACHED(); +} diff --git a/libcef/browser/browser_main.h b/libcef/browser/browser_main.h new file mode 100644 index 000000000..a3d905520 --- /dev/null +++ b/libcef/browser/browser_main.h @@ -0,0 +1,81 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_MAIN_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_MAIN_H_ +#pragma once + +#include "libcef/browser/browser_pref_store.h" + +#include "base/basictypes.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/scoped_vector.h" +#include "base/prefs/pref_service.h" +#include "base/strings/string_piece.h" +#include "chrome/browser/net/pref_proxy_config_tracker.h" +#include "content/public/browser/browser_main_parts.h" +#include "net/proxy/proxy_config_service.h" +#include "net/url_request/url_request_context_getter.h" + +namespace base { +class MessageLoop; +class Thread; +} + +namespace content { +struct MainFunctionParams; +} + +class CefBrowserContext; +class CefDevToolsDelegate; + +class CefBrowserMainParts : public content::BrowserMainParts { + public: + explicit CefBrowserMainParts(const content::MainFunctionParams& parameters); + ~CefBrowserMainParts() override; + + void PreMainMessageLoopStart() override; + void PostMainMessageLoopStart() override; + void PreEarlyInitialization() override; + void ToolkitInitialized() override; + int PreCreateThreads() override; + void PreMainMessageLoopRun() override; + void PostMainMessageLoopRun() override; + void PostDestroyThreads() override; + + CefBrowserContext* browser_context() const { + return global_browser_context_.get(); + } + scoped_refptr request_context() const { + return global_request_context_; + } + CefDevToolsDelegate* devtools_delegate() const { + return devtools_delegate_; + } + PrefService* pref_service() const { return pref_service_.get(); } + scoped_ptr proxy_config_service() { + return proxy_config_service_.Pass(); + } + + void AddBrowserContext(CefBrowserContext* context); + void RemoveBrowserContext(CefBrowserContext* context); + + private: + void PlatformInitialize(); + void PlatformCleanup(); + + scoped_ptr global_browser_context_; + scoped_refptr global_request_context_; + ScopedVector browser_contexts_; + CefDevToolsDelegate* devtools_delegate_; // Deletes itself. + scoped_ptr message_loop_; + scoped_ptr pref_proxy_config_tracker_; + scoped_ptr proxy_config_service_; + scoped_refptr pref_store_; + scoped_ptr pref_service_; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserMainParts); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_MAIN_H_ diff --git a/libcef/browser/browser_main_linux.cc b/libcef/browser/browser_main_linux.cc new file mode 100644 index 000000000..d9b14a323 --- /dev/null +++ b/libcef/browser/browser_main_linux.cc @@ -0,0 +1,11 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_main.h" + +void CefBrowserMainParts::PlatformInitialize() { +} + +void CefBrowserMainParts::PlatformCleanup() { +} diff --git a/libcef/browser/browser_main_mac.mm b/libcef/browser/browser_main_mac.mm new file mode 100644 index 000000000..d9b14a323 --- /dev/null +++ b/libcef/browser/browser_main_mac.mm @@ -0,0 +1,11 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_main.h" + +void CefBrowserMainParts::PlatformInitialize() { +} + +void CefBrowserMainParts::PlatformCleanup() { +} diff --git a/libcef/browser/browser_main_win.cc b/libcef/browser/browser_main_win.cc new file mode 100644 index 000000000..094f2202f --- /dev/null +++ b/libcef/browser/browser_main_win.cc @@ -0,0 +1,32 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include +#include + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/browser_main.h" + +void CefBrowserMainParts::PlatformInitialize() { + HRESULT res; + + // Initialize common controls. + res = CoInitialize(NULL); + DCHECK(SUCCEEDED(res)); + INITCOMMONCONTROLSEX InitCtrlEx; + InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); + InitCtrlEx.dwICC = ICC_STANDARD_CLASSES; + InitCommonControlsEx(&InitCtrlEx); + + // Start COM stuff. + res = OleInitialize(NULL); + DCHECK(SUCCEEDED(res)); + + // Register the browser window class. + CefBrowserHostImpl::RegisterWindowClass(); +} + +void CefBrowserMainParts::PlatformCleanup() { +} diff --git a/libcef/browser/browser_message_filter.cc b/libcef/browser/browser_message_filter.cc new file mode 100644 index 000000000..e66aded8a --- /dev/null +++ b/libcef/browser/browser_message_filter.cc @@ -0,0 +1,132 @@ +/// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/browser_message_filter.h" + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/browser_info.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/origin_whitelist_impl.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/cef_messages.h" +#include "libcef/common/content_client.h" +#include "libcef/common/values_impl.h" + +#include "base/compiler_specific.h" +#include "base/bind.h" +#include "content/common/frame_messages.h" +#include "content/common/view_messages.h" +#include "content/public/browser/render_process_host.h" + +CefBrowserMessageFilter::CefBrowserMessageFilter( + content::RenderProcessHost* host) + : host_(host), + sender_(NULL) { +} + +CefBrowserMessageFilter::~CefBrowserMessageFilter() { +} + +void CefBrowserMessageFilter::OnFilterAdded(IPC::Sender* sender) { + sender_ = sender; +} + +void CefBrowserMessageFilter::OnFilterRemoved() { +} + +bool CefBrowserMessageFilter::OnMessageReceived(const IPC::Message& message) { + if (message.type() == FrameHostMsg_FrameFocused::ID) { + // Observe but don't handle this message. + OnFrameFocused(message.routing_id()); + return false; + } + + bool handled = true; + if (message.type() == ViewHostMsg_CreateWindow::ID) { + // Observe but don't handle this message. + handled = false; + } + + IPC_BEGIN_MESSAGE_MAP(CefBrowserMessageFilter, message) + IPC_MESSAGE_HANDLER(CefProcessHostMsg_GetNewRenderThreadInfo, + OnGetNewRenderThreadInfo) + IPC_MESSAGE_HANDLER(CefProcessHostMsg_GetNewBrowserInfo, + OnGetNewBrowserInfo) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_CreateWindow, OnCreateWindow) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +bool CefBrowserMessageFilter::Send(IPC::Message* message) { + return host_->Send(message); +} + +void CefBrowserMessageFilter::OnGetNewRenderThreadInfo( + CefProcessHostMsg_GetNewRenderThreadInfo_Params* params) { + GetCrossOriginWhitelistEntries(¶ms->cross_origin_whitelist_entries); + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetBrowserProcessHandler(); + if (handler.get()) { + CefRefPtr listValuePtr( + new CefListValueImpl(¶ms->extra_info, false, false)); + handler->OnRenderProcessThreadCreated(listValuePtr.get()); + listValuePtr->Detach(NULL); + } + } +} + +void CefBrowserMessageFilter::OnGetNewBrowserInfo( + int render_view_routing_id, + int render_frame_routing_id, + CefProcessHostMsg_GetNewBrowserInfo_Params* params) { + DCHECK_GT(render_view_routing_id, 0); + DCHECK_GT(render_frame_routing_id, 0); + + // Popup windows may not have info yet. + scoped_refptr info = + CefContentBrowserClient::Get()->GetOrCreateBrowserInfo( + host_->GetID(), + render_view_routing_id, + host_->GetID(), + render_frame_routing_id); + params->browser_id = info->browser_id(); + params->is_popup = info->is_popup(); + params->is_windowless = info->is_windowless(); +} + +void CefBrowserMessageFilter::OnCreateWindow( + const ViewHostMsg_CreateWindow_Params& params, + IPC::Message* reply_msg) { + CefContentBrowserClient::LastCreateWindowParams lcwp; + lcwp.opener_process_id = host_->GetID(); + lcwp.opener_view_id = params.opener_id; + lcwp.opener_frame_id = params.opener_render_frame_id; + lcwp.target_url = params.target_url; + lcwp.target_frame_name = params.frame_name; + CefContentBrowserClient::Get()->set_last_create_window_params(lcwp); + + // Reply message is not used. + delete reply_msg; +} + +void CefBrowserMessageFilter::OnFrameFocused(int32 render_frame_routing_id) { + if (!CEF_CURRENTLY_ON_UIT()) { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserMessageFilter::OnFrameFocused, this, + render_frame_routing_id)); + return; + } + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForFrame(host_->GetID(), + render_frame_routing_id); + if (browser.get()) + browser->SetFocusedFrame(render_frame_routing_id); +} diff --git a/libcef/browser/browser_message_filter.h b/libcef/browser/browser_message_filter.h new file mode 100644 index 000000000..be0e64e74 --- /dev/null +++ b/libcef/browser/browser_message_filter.h @@ -0,0 +1,53 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_MESSAGE_FILTER_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_MESSAGE_FILTER_H_ + +#include +#include "ipc/ipc_channel_proxy.h" +#include "ipc/message_filter.h" + +namespace content { +class RenderProcessHost; +} + +struct CefProcessHostMsg_GetNewBrowserInfo_Params; +struct CefProcessHostMsg_GetNewRenderThreadInfo_Params; +struct ViewHostMsg_CreateWindow_Params; + +// This class sends and receives control messages on the browser process. +class CefBrowserMessageFilter : public IPC::MessageFilter { + public: + explicit CefBrowserMessageFilter(content::RenderProcessHost* host); + ~CefBrowserMessageFilter() override; + + // IPC::ChannelProxy::MessageFilter implementation. + void OnFilterAdded(IPC::Sender* sender) override; + void OnFilterRemoved() override; + bool OnMessageReceived(const IPC::Message& message) override; + + bool Send(IPC::Message* message); + + private: + // Message handlers. + void OnGetNewRenderThreadInfo( + CefProcessHostMsg_GetNewRenderThreadInfo_Params* params); + void OnGetNewBrowserInfo( + int render_view_routing_id, + int render_frame_routing_id, + CefProcessHostMsg_GetNewBrowserInfo_Params* params); + void OnCreateWindow(const ViewHostMsg_CreateWindow_Params& params, + IPC::Message* reply_msg); + void OnFrameFocused(int32 render_frame_routing_id); + + content::RenderProcessHost* host_; + IPC::Sender* sender_; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserMessageFilter); +}; + + +#endif // CEF_LIBCEF_BROWSER_BROWSER_MESSAGE_FILTER_H_ diff --git a/libcef/browser/browser_message_loop.cc b/libcef/browser/browser_message_loop.cc new file mode 100644 index 000000000..246d3f29c --- /dev/null +++ b/libcef/browser/browser_message_loop.cc @@ -0,0 +1,28 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/browser_message_loop.h" +#include "base/run_loop.h" + +CefBrowserMessageLoop::CefBrowserMessageLoop() { +} + +CefBrowserMessageLoop::~CefBrowserMessageLoop() { +} + +// static +CefBrowserMessageLoop* CefBrowserMessageLoop::current() { + base::MessageLoop* loop = base::MessageLoop::current(); + DCHECK_EQ(base::MessageLoop::TYPE_UI, loop->type()); + return static_cast(loop); +} + +void CefBrowserMessageLoop::DoMessageLoopIteration() { + base::RunLoop run_loop; + run_loop.RunUntilIdle(); +} + +void CefBrowserMessageLoop::RunMessageLoop() { + Run(); +} diff --git a/libcef/browser/browser_message_loop.h b/libcef/browser/browser_message_loop.h new file mode 100644 index 000000000..23cfcc429 --- /dev/null +++ b/libcef/browser/browser_message_loop.h @@ -0,0 +1,33 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_MESSAGE_LOOP_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_MESSAGE_LOOP_H_ +#pragma once + +#include "base/basictypes.h" +#include "base/message_loop/message_loop.h" + +// Class used to process events on the current message loop. +class CefBrowserMessageLoop : public base::MessageLoopForUI { + typedef base::MessageLoopForUI inherited; + + public: + CefBrowserMessageLoop(); + ~CefBrowserMessageLoop() override; + + // Returns the MessageLoopForUI of the current thread. + static CefBrowserMessageLoop* current(); + + // Do a single interation of the UI message loop. + void DoMessageLoopIteration(); + + // Run the UI message loop. + void RunMessageLoop(); + + private: + DISALLOW_COPY_AND_ASSIGN(CefBrowserMessageLoop); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_MESSAGE_LOOP_H_ diff --git a/libcef/browser/browser_pref_store.cc b/libcef/browser/browser_pref_store.cc new file mode 100644 index 000000000..3a5834fe7 --- /dev/null +++ b/libcef/browser/browser_pref_store.cc @@ -0,0 +1,117 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/browser_pref_store.h" + +#include "libcef/browser/media_capture_devices_dispatcher.h" +#include "libcef/common/cef_switches.h" + +#include "base/command_line.h" +#include "base/prefs/pref_service.h" +#include "base/prefs/pref_service_factory.h" +#include "base/prefs/pref_registry_simple.h" +#include "base/strings/string_number_conversions.h" +#include "base/values.h" +#include "chrome/browser/net/pref_proxy_config_tracker_impl.h" +#include "chrome/browser/prefs/command_line_pref_store.h" +#include "chrome/browser/prefs/proxy_config_dictionary.h" +#include "chrome/common/chrome_switches.h" +#include "chrome/common/pref_names.h" +#include "grit/cef_strings.h" +#include "ui/base/l10n/l10n_util.h" + +namespace { + +// A helper function for registering localized values. +// Based on CreateLocaleDefaultValue from +// components/pref_registry/pref_registry_syncable.cc. +void RegisterLocalizedValue(PrefRegistrySimple* registry, + const char* path, + base::Value::Type type, + int message_id) { + const std::string resource_string = l10n_util::GetStringUTF8(message_id); + DCHECK(!resource_string.empty()); + switch (type) { + case base::Value::TYPE_BOOLEAN: { + if ("true" == resource_string) + registry->RegisterBooleanPref(path, true); + else if ("false" == resource_string) + registry->RegisterBooleanPref(path, false); + return; + } + + case base::Value::TYPE_INTEGER: { + int val; + base::StringToInt(resource_string, &val); + registry->RegisterIntegerPref(path, val); + return; + } + + case base::Value::TYPE_DOUBLE: { + double val; + base::StringToDouble(resource_string, &val); + registry->RegisterDoublePref(path, val); + return; + } + + case base::Value::TYPE_STRING: { + registry->RegisterStringPref(path, resource_string); + return; + } + + default: { + NOTREACHED() << + "list and dictionary types cannot have default locale values"; + } + } + NOTREACHED(); +} + +} // namespace + +CefBrowserPrefStore::CefBrowserPrefStore() { +} + +scoped_ptr CefBrowserPrefStore::CreateService() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + base::PrefServiceFactory factory; + factory.set_command_line_prefs( + new CommandLinePrefStore(command_line)); + factory.set_user_prefs(this); + + scoped_refptr registry(new PrefRegistrySimple()); + + // Default settings. + CefMediaCaptureDevicesDispatcher::RegisterPrefs(registry.get()); + PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get()); + + // Print settings. + registry->RegisterBooleanPref(prefs::kPrintingEnabled, true); + + // Spell checking settings. + std::string spellcheck_lang = + command_line->GetSwitchValueASCII(switches::kOverrideSpellCheckLang); + if (!spellcheck_lang.empty()) { + registry->RegisterStringPref(prefs::kSpellCheckDictionary, spellcheck_lang); + } else { + RegisterLocalizedValue(registry.get(), + prefs::kSpellCheckDictionary, + base::Value::TYPE_STRING, + IDS_SPELLCHECK_DICTIONARY); + } + registry->RegisterBooleanPref(prefs::kSpellCheckUseSpellingService, + command_line->HasSwitch(switches::kEnableSpellingService)); + registry->RegisterBooleanPref(prefs::kEnableContinuousSpellcheck, true); + // The kEnableSpellingAutoCorrect command-line value is also checked in + // SpellCheckProvider::autoCorrectWord. + registry->RegisterBooleanPref(prefs::kEnableAutoSpellCorrect, + command_line->HasSwitch(switches::kEnableSpellingAutoCorrect)); + + return factory.Create(registry.get()); +} + +CefBrowserPrefStore::~CefBrowserPrefStore() { +} diff --git a/libcef/browser/browser_pref_store.h b/libcef/browser/browser_pref_store.h new file mode 100644 index 000000000..70c6c02dc --- /dev/null +++ b/libcef/browser/browser_pref_store.h @@ -0,0 +1,25 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_PREF_STORE_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_PREF_STORE_H_ + +#include "base/memory/scoped_ptr.h" +#include "base/prefs/testing_pref_store.h" + +class PrefService; + +class CefBrowserPrefStore : public TestingPrefStore { + public: + CefBrowserPrefStore(); + + scoped_ptr CreateService(); + + protected: + ~CefBrowserPrefStore() override; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserPrefStore); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_PREF_STORE_H_ diff --git a/libcef/browser/browser_settings.cc b/libcef/browser/browser_settings.cc new file mode 100644 index 000000000..55022836e --- /dev/null +++ b/libcef/browser/browser_settings.cc @@ -0,0 +1,129 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/browser_settings.h" + +#include + +#include "include/internal/cef_types_wrappers.h" +#include "libcef/common/cef_switches.h" + +#include "base/command_line.h" +#include "content/public/common/web_preferences.h" + +// Set default preferences based on CEF command-line flags. Chromium command- +// line flags should not exist for these preferences. +void SetDefaults(content::WebPreferences& web) { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + if (command_line->HasSwitch(switches::kDefaultEncoding)) { + web.default_encoding = + command_line->GetSwitchValueASCII(switches::kDefaultEncoding); + } + + web.javascript_can_open_windows_automatically = + !command_line->HasSwitch(switches::kDisableJavascriptOpenWindows); + web.allow_scripts_to_close_windows = + !command_line->HasSwitch(switches::kDisableJavascriptCloseWindows); + web.javascript_can_access_clipboard = + !command_line->HasSwitch(switches::kDisableJavascriptAccessClipboard); + web.dom_paste_enabled = + !command_line->HasSwitch(switches::kDisableJavascriptDomPaste); + web.caret_browsing_enabled = + command_line->HasSwitch(switches::kEnableCaretBrowsing); + web.allow_universal_access_from_file_urls = + command_line->HasSwitch(switches::kAllowUniversalAccessFromFileUrls); + web.loads_images_automatically = + !command_line->HasSwitch(switches::kDisableImageLoading); + web.shrinks_standalone_images_to_fit = + command_line->HasSwitch(switches::kImageShrinkStandaloneToFit); + web.text_areas_are_resizable = + !command_line->HasSwitch(switches::kDisableTextAreaResize); + web.tabs_to_links = + !command_line->HasSwitch(switches::kDisableTabToLinks); +} + +// Helper macro for setting a WebPreferences variable based on the value of a +// CefBrowserSettings variable. +#define SET_STATE(cef_var, web_var) \ + if (cef_var == STATE_ENABLED) \ + web_var = true; \ + else if (cef_var == STATE_DISABLED) \ + web_var = false; + +// Use the preferences from WebContentsImpl::GetWebkitPrefs and the +// WebPreferences constructor by default. Only override features that are +// explicitly enabled or disabled. +void BrowserToWebSettings(const CefBrowserSettings& cef, + content::WebPreferences& web) { + SetDefaults(web); + + if (cef.standard_font_family.length > 0) { + web.standard_font_family_map[content::kCommonScript] = + CefString(&cef.standard_font_family); + } + if (cef.fixed_font_family.length > 0) { + web.fixed_font_family_map[content::kCommonScript] = + CefString(&cef.fixed_font_family); + } + if (cef.serif_font_family.length > 0) { + web.serif_font_family_map[content::kCommonScript] = + CefString(&cef.serif_font_family); + } + if (cef.sans_serif_font_family.length > 0) { + web.sans_serif_font_family_map[content::kCommonScript] = + CefString(&cef.sans_serif_font_family); + } + if (cef.cursive_font_family.length > 0) { + web.cursive_font_family_map[content::kCommonScript] = + CefString(&cef.cursive_font_family); + } + if (cef.fantasy_font_family.length > 0) { + web.fantasy_font_family_map[content::kCommonScript] = + CefString(&cef.fantasy_font_family); + } + + if (cef.default_font_size > 0) + web.default_font_size = cef.default_font_size; + if (cef.default_fixed_font_size > 0) + web.default_fixed_font_size = cef.default_fixed_font_size; + if (cef.minimum_font_size > 0) + web.minimum_font_size = cef.minimum_font_size; + if (cef.minimum_logical_font_size > 0) + web.minimum_logical_font_size = cef.minimum_logical_font_size; + + if (cef.default_encoding.length > 0) + web.default_encoding = CefString(&cef.default_encoding); + + SET_STATE(cef.remote_fonts, web.remote_fonts_enabled); + SET_STATE(cef.javascript, web.javascript_enabled); + SET_STATE(cef.javascript_open_windows, + web.javascript_can_open_windows_automatically); + SET_STATE(cef.javascript_close_windows, web.allow_scripts_to_close_windows); + SET_STATE(cef.javascript_access_clipboard, + web.javascript_can_access_clipboard); + SET_STATE(cef.javascript_dom_paste, web.dom_paste_enabled); + SET_STATE(cef.caret_browsing, web.caret_browsing_enabled); + SET_STATE(cef.java, web.java_enabled); + SET_STATE(cef.plugins, web.plugins_enabled); + SET_STATE(cef.universal_access_from_file_urls, + web.allow_universal_access_from_file_urls); + SET_STATE(cef.file_access_from_file_urls, + web.allow_file_access_from_file_urls); + SET_STATE(cef.web_security, web.web_security_enabled); + SET_STATE(cef.image_loading, web.loads_images_automatically); + SET_STATE(cef.image_shrink_standalone_to_fit, + web.shrinks_standalone_images_to_fit); + SET_STATE(cef.text_area_resize, web.text_areas_are_resizable); + SET_STATE(cef.tab_to_links, web.tabs_to_links); + SET_STATE(cef.local_storage, web.local_storage_enabled); + SET_STATE(cef.databases, web.databases_enabled); + SET_STATE(cef.application_cache, web.application_cache_enabled); + + // Never explicitly enable GPU-related functions in this method because the + // GPU blacklist is not being checked here. + if (cef.webgl == STATE_DISABLED) + web.experimental_webgl_enabled = false; +} diff --git a/libcef/browser/browser_settings.h b/libcef/browser/browser_settings.h new file mode 100644 index 000000000..13972bb8c --- /dev/null +++ b/libcef/browser/browser_settings.h @@ -0,0 +1,18 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_SETTINGS_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_SETTINGS_H_ +#pragma once + +#include "include/internal/cef_types_wrappers.h" + +namespace content { +struct WebPreferences; +} + +void BrowserToWebSettings(const CefBrowserSettings& cef, + content::WebPreferences& web); + +#endif // CEF_LIBCEF_BROWSER_BROWSER_SETTINGS_H_ diff --git a/libcef/browser/browser_urlrequest_impl.cc b/libcef/browser/browser_urlrequest_impl.cc new file mode 100644 index 000000000..100564674 --- /dev/null +++ b/libcef/browser/browser_urlrequest_impl.cc @@ -0,0 +1,536 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/browser_urlrequest_impl.h" + +#include + +#include "libcef/browser/browser_context.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_user_data.h" +#include "libcef/common/http_header_utils.h" +#include "libcef/common/request_impl.h" +#include "libcef/common/response_impl.h" + +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "base/strings/string_util.h" +#include "content/public/common/url_fetcher.h" +#include "net/base/io_buffer.h" +#include "net/base/load_flags.h" +#include "net/base/net_errors.h" +#include "net/http/http_request_headers.h" +#include "net/http/http_response_headers.h" +#include "net/url_request/url_fetcher.h" +#include "net/url_request/url_fetcher_delegate.h" +#include "net/url_request/url_fetcher_response_writer.h" +#include "net/url_request/url_request_status.h" + + +namespace { + +class CefURLFetcherDelegate : public net::URLFetcherDelegate { + public: + CefURLFetcherDelegate(CefBrowserURLRequest::Context* context, + int request_flags); + ~CefURLFetcherDelegate() override; + + // net::URLFetcherDelegate methods. + void OnURLFetchComplete(const net::URLFetcher* source) override; + void OnURLFetchDownloadProgress(const net::URLFetcher* source, + int64 current, int64 total) override; + void OnURLFetchUploadProgress(const net::URLFetcher* source, + int64 current, int64 total) override; + + private: + // The context_ pointer will outlive this object. + CefBrowserURLRequest::Context* context_; + int request_flags_; +}; + +class NET_EXPORT CefURLFetcherResponseWriter : + public net::URLFetcherResponseWriter { + public: + CefURLFetcherResponseWriter( + CefRefPtr url_request, + scoped_refptr message_loop_proxy) + : url_request_(url_request), + message_loop_proxy_(message_loop_proxy) { + } + + // net::URLFetcherResponseWriter methods. + int Initialize(const net::CompletionCallback& callback) override { + return net::OK; + } + + int Write(net::IOBuffer* buffer, + int num_bytes, + const net::CompletionCallback& callback) override { + if (url_request_.get()) { + message_loop_proxy_->PostTask(FROM_HERE, + base::Bind(&CefURLFetcherResponseWriter::WriteOnClientThread, + url_request_, scoped_refptr(buffer), + num_bytes, callback, + base::MessageLoop::current()->message_loop_proxy())); + return net::ERR_IO_PENDING; + } + return num_bytes; + } + + int Finish(const net::CompletionCallback& callback) override { + if (url_request_.get()) + url_request_ = NULL; + return net::OK; + } + + private: + static void WriteOnClientThread( + CefRefPtr url_request, + scoped_refptr buffer, + int num_bytes, + const net::CompletionCallback& callback, + scoped_refptr source_message_loop_proxy) { + CefRefPtr client = url_request->GetClient(); + if (client.get()) + client->OnDownloadData(url_request.get(), buffer->data(), num_bytes); + + source_message_loop_proxy->PostTask(FROM_HERE, + base::Bind(&CefURLFetcherResponseWriter::ContinueOnSourceThread, + num_bytes, callback)); + } + + static void ContinueOnSourceThread( + int num_bytes, + const net::CompletionCallback& callback) { + callback.Run(num_bytes); + } + + CefRefPtr url_request_; + scoped_refptr message_loop_proxy_; + + DISALLOW_COPY_AND_ASSIGN(CefURLFetcherResponseWriter); +}; + +base::SupportsUserData::Data* CreateURLRequestUserData( + CefRefPtr client) { + return new CefURLRequestUserData(client); +} + +} // namespace + + +// CefBrowserURLRequest::Context ---------------------------------------------- + +class CefBrowserURLRequest::Context + : public base::RefCountedThreadSafe { + public: + Context(CefRefPtr url_request, + CefRefPtr request, + CefRefPtr client) + : url_request_(url_request), + request_(request), + client_(client), + message_loop_proxy_(base::MessageLoop::current()->message_loop_proxy()), + status_(UR_IO_PENDING), + error_code_(ERR_NONE), + upload_data_size_(0), + got_upload_progress_complete_(false) { + // Mark the request as read-only. + static_cast(request_.get())->SetReadOnly(true); + } + + inline bool CalledOnValidThread() { + return message_loop_proxy_->BelongsToCurrentThread(); + } + + bool Start() { + DCHECK(CalledOnValidThread()); + + GURL url = GURL(request_->GetURL().ToString()); + if (!url.is_valid()) + return false; + + std::string method = request_->GetMethod(); + base::StringToLowerASCII(&method); + net::URLFetcher::RequestType request_type = net::URLFetcher::GET; + if (LowerCaseEqualsASCII(method, "get")) { + } else if (LowerCaseEqualsASCII(method, "post")) { + request_type = net::URLFetcher::POST; + } else if (LowerCaseEqualsASCII(method, "head")) { + request_type = net::URLFetcher::HEAD; + } else if (LowerCaseEqualsASCII(method, "delete")) { + request_type = net::URLFetcher::DELETE_REQUEST; + } else if (LowerCaseEqualsASCII(method, "put")) { + request_type = net::URLFetcher::PUT; + } else { + NOTREACHED() << "invalid request type"; + return false; + } + + fetcher_delegate_.reset( + new CefURLFetcherDelegate(this, request_->GetFlags())); + + fetcher_.reset(net::URLFetcher::Create(url, request_type, + fetcher_delegate_.get())); + fetcher_->SetRequestContext( + CefContentBrowserClient::Get()->request_context().get()); + + CefRequest::HeaderMap headerMap; + request_->GetHeaderMap(headerMap); + + // Extract the Referer header value. + { + CefString referrerStr; + referrerStr.FromASCII(net::HttpRequestHeaders::kReferer); + CefRequest::HeaderMap::iterator it = headerMap.find(referrerStr); + if (it == headerMap.end()) { + fetcher_->SetReferrer(""); + } else { + fetcher_->SetReferrer(it->second); + headerMap.erase(it); + } + } + + std::string content_type; + + // Extract the Content-Type header value. + { + CefString contentTypeStr; + contentTypeStr.FromASCII(net::HttpRequestHeaders::kContentType); + CefRequest::HeaderMap::iterator it = headerMap.find(contentTypeStr); + if (it != headerMap.end()) { + content_type = it->second; + headerMap.erase(it); + } + } + + int64 upload_data_size = 0; + + CefRefPtr post_data = request_->GetPostData(); + if (post_data.get()) { + CefPostData::ElementVector elements; + post_data->GetElements(elements); + if (elements.size() == 1) { + // Default to URL encoding if not specified. + if (content_type.empty()) + content_type = "application/x-www-form-urlencoded"; + + CefPostDataElementImpl* impl = + static_cast(elements[0].get()); + + switch (elements[0]->GetType()) + case PDE_TYPE_BYTES: { + upload_data_size = impl->GetBytesCount(); + fetcher_->SetUploadData(content_type, + std::string(static_cast(impl->GetBytes()), + upload_data_size)); + break; + case PDE_TYPE_FILE: + fetcher_->SetUploadFilePath( + content_type, + base::FilePath(impl->GetFile()), + 0, kuint64max, + content::BrowserThread::GetMessageLoopProxyForThread( + content::BrowserThread::FILE).get()); + break; + case PDE_TYPE_EMPTY: + break; + } + } else if (elements.size() > 1) { + NOTIMPLEMENTED() << " multi-part form data is not supported"; + } + } + + std::string first_party_for_cookies = request_->GetFirstPartyForCookies(); + if (!first_party_for_cookies.empty()) + fetcher_->SetFirstPartyForCookies(GURL(first_party_for_cookies)); + + int cef_flags = request_->GetFlags(); + + if (cef_flags & UR_FLAG_NO_RETRY_ON_5XX) + fetcher_->SetAutomaticallyRetryOn5xx(false); + + int load_flags = 0; + + if (cef_flags & UR_FLAG_SKIP_CACHE) + load_flags |= net::LOAD_BYPASS_CACHE; + + if (!(cef_flags & UR_FLAG_ALLOW_CACHED_CREDENTIALS)) { + load_flags |= net::LOAD_DO_NOT_SEND_AUTH_DATA; + load_flags |= net::LOAD_DO_NOT_SEND_COOKIES; + load_flags |= net::LOAD_DO_NOT_SAVE_COOKIES; + } + + if (cef_flags & UR_FLAG_REPORT_UPLOAD_PROGRESS) { + upload_data_size_ = upload_data_size; + } + + if (cef_flags & UR_FLAG_REPORT_RAW_HEADERS) + load_flags |= net::LOAD_REPORT_RAW_HEADERS; + + fetcher_->SetLoadFlags(load_flags); + + fetcher_->SetExtraRequestHeaders( + HttpHeaderUtils::GenerateHeaders(headerMap)); + + fetcher_->SetURLRequestUserData( + CefURLRequestUserData::kUserDataKey, + base::Bind(&CreateURLRequestUserData, client_)); + + scoped_ptr response_writer; + if (cef_flags & UR_FLAG_NO_DOWNLOAD_DATA) { + response_writer.reset(new CefURLFetcherResponseWriter(NULL, NULL)); + } else { + response_writer.reset( + new CefURLFetcherResponseWriter(url_request_, message_loop_proxy_)); + } + fetcher_->SaveResponseWithWriter(response_writer.Pass()); + + fetcher_->Start(); + + return true; + } + + void Cancel() { + DCHECK(CalledOnValidThread()); + + // The request may already be complete. + if (!fetcher_.get()) + return; + + // Cancel the fetch by deleting the fetcher. + fetcher_.reset(NULL); + + status_ = UR_CANCELED; + error_code_ = ERR_ABORTED; + OnComplete(); + } + + void OnComplete() { + DCHECK(CalledOnValidThread()); + + if (fetcher_.get()) { + const net::URLRequestStatus& status = fetcher_->GetStatus(); + + if (status.is_success()) + NotifyUploadProgressIfNecessary(); + + switch (status.status()) { + case net::URLRequestStatus::SUCCESS: + status_ = UR_SUCCESS; + break; + case net::URLRequestStatus::IO_PENDING: + status_ = UR_IO_PENDING; + break; + case net::URLRequestStatus::CANCELED: + status_ = UR_CANCELED; + break; + case net::URLRequestStatus::FAILED: + status_ = UR_FAILED; + break; + } + + error_code_ = static_cast(status.error()); + + if(!response_.get()) + OnResponse(); + } + + DCHECK(url_request_.get()); + client_->OnRequestComplete(url_request_.get()); + + if (fetcher_.get()) + fetcher_.reset(NULL); + + // This may result in the Context object being deleted. + url_request_ = NULL; + } + + void OnDownloadProgress(int64 current, int64 total) { + DCHECK(CalledOnValidThread()); + DCHECK(url_request_.get()); + + if(!response_.get()) + OnResponse(); + + NotifyUploadProgressIfNecessary(); + + client_->OnDownloadProgress(url_request_.get(), current, total); + } + + void OnDownloadData(scoped_ptr download_data) { + DCHECK(CalledOnValidThread()); + DCHECK(url_request_.get()); + + if(!response_.get()) + OnResponse(); + + client_->OnDownloadData(url_request_.get(), download_data->c_str(), + download_data->length()); + } + + void OnUploadProgress(int64 current, int64 total) { + DCHECK(CalledOnValidThread()); + DCHECK(url_request_.get()); + if (current == total) + got_upload_progress_complete_ = true; + client_->OnUploadProgress(url_request_.get(), current, total); + } + + CefRefPtr request() { return request_; } + CefRefPtr client() { return client_; } + CefURLRequest::Status status() { return status_; } + CefURLRequest::ErrorCode error_code() { return error_code_; } + CefRefPtr response() { return response_; } + + private: + friend class base::RefCountedThreadSafe; + + ~Context() { + if (fetcher_.get()) { + // Delete the fetcher object on the thread that created it. + message_loop_proxy_->DeleteSoon(FROM_HERE, fetcher_.release()); + } + } + + void NotifyUploadProgressIfNecessary() { + if (!got_upload_progress_complete_ && upload_data_size_ > 0) { + // URLFetcher sends upload notifications using a timer and will not send + // a notification if the request completes too quickly. We therefore + // send the notification here if necessary. + client_->OnUploadProgress(url_request_.get(), upload_data_size_, + upload_data_size_); + got_upload_progress_complete_ = true; + } + } + + void OnResponse() { + if (fetcher_.get()) { + response_ = new CefResponseImpl(); + CefResponseImpl* responseImpl = + static_cast(response_.get()); + + net::HttpResponseHeaders* headers = fetcher_->GetResponseHeaders(); + if (headers) + responseImpl->SetResponseHeaders(*headers); + + responseImpl->SetReadOnly(true); + } + } + + // Members only accessed on the initialization thread. + CefRefPtr url_request_; + CefRefPtr request_; + CefRefPtr client_; + scoped_refptr message_loop_proxy_; + scoped_ptr fetcher_; + scoped_ptr fetcher_delegate_; + CefURLRequest::Status status_; + CefURLRequest::ErrorCode error_code_; + CefRefPtr response_; + int64 upload_data_size_; + bool got_upload_progress_complete_; +}; + + +// CefURLFetcherDelegate ------------------------------------------------------ + +namespace { + +CefURLFetcherDelegate::CefURLFetcherDelegate( + CefBrowserURLRequest::Context* context, int request_flags) + : context_(context), + request_flags_(request_flags) { +} + +CefURLFetcherDelegate::~CefURLFetcherDelegate() { +} + +void CefURLFetcherDelegate::OnURLFetchComplete( + const net::URLFetcher* source) { + // Complete asynchronously so as not to delete the URLFetcher while it's still + // in the call stack. + base::MessageLoop::current()->PostTask(FROM_HERE, + base::Bind(&CefBrowserURLRequest::Context::OnComplete, context_)); +} + +void CefURLFetcherDelegate::OnURLFetchDownloadProgress( + const net::URLFetcher* source, + int64 current, int64 total) { + context_->OnDownloadProgress(current, total); +} + +void CefURLFetcherDelegate::OnURLFetchUploadProgress( + const net::URLFetcher* source, + int64 current, int64 total) { + if (request_flags_ & UR_FLAG_REPORT_UPLOAD_PROGRESS) + context_->OnUploadProgress(current, total); +} + +} // namespace + + +// CefBrowserURLRequest ------------------------------------------------------- + +CefBrowserURLRequest::CefBrowserURLRequest( + CefRefPtr request, + CefRefPtr client) { + context_ = new Context(this, request, client); +} + +CefBrowserURLRequest::~CefBrowserURLRequest() { +} + +bool CefBrowserURLRequest::Start() { + if (!VerifyContext()) + return false; + return context_->Start(); +} + +CefRefPtr CefBrowserURLRequest::GetRequest() { + if (!VerifyContext()) + return NULL; + return context_->request(); +} + +CefRefPtr CefBrowserURLRequest::GetClient() { + if (!VerifyContext()) + return NULL; + return context_->client(); +} + +CefURLRequest::Status CefBrowserURLRequest::GetRequestStatus() { + if (!VerifyContext()) + return UR_UNKNOWN; + return context_->status(); +} + +CefURLRequest::ErrorCode CefBrowserURLRequest::GetRequestError() { + if (!VerifyContext()) + return ERR_NONE; + return context_->error_code(); +} + +CefRefPtr CefBrowserURLRequest::GetResponse() { + if (!VerifyContext()) + return NULL; + return context_->response(); +} + +void CefBrowserURLRequest::Cancel() { + if (!VerifyContext()) + return; + return context_->Cancel(); +} + +bool CefBrowserURLRequest::VerifyContext() { + DCHECK(context_.get()); + if (!context_->CalledOnValidThread()) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + return true; +} diff --git a/libcef/browser/browser_urlrequest_impl.h b/libcef/browser/browser_urlrequest_impl.h new file mode 100644 index 000000000..b0055726e --- /dev/null +++ b/libcef/browser/browser_urlrequest_impl.h @@ -0,0 +1,37 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_BROWSER_URLREQUEST_IMPL_H_ +#define CEF_LIBCEF_BROWSER_BROWSER_URLREQUEST_IMPL_H_ + +#include "include/cef_urlrequest.h" +#include "base/memory/ref_counted.h" + +class CefBrowserURLRequest : public CefURLRequest { + public: + class Context; + + CefBrowserURLRequest(CefRefPtr request, + CefRefPtr client); + ~CefBrowserURLRequest() override; + + bool Start(); + + // CefURLRequest methods. + CefRefPtr GetRequest() override; + CefRefPtr GetClient() override; + Status GetRequestStatus() override; + ErrorCode GetRequestError() override; + CefRefPtr GetResponse() override; + void Cancel() override; + + private: + bool VerifyContext(); + + scoped_refptr context_; + + IMPLEMENT_REFCOUNTING(CefBrowserURLRequest); +}; + +#endif // CEF_LIBCEF_BROWSER_BROWSER_URLREQUEST_IMPL_H_ diff --git a/libcef/browser/chrome_browser_process_stub.cc b/libcef/browser/chrome_browser_process_stub.cc new file mode 100644 index 000000000..dcdd5409f --- /dev/null +++ b/libcef/browser/chrome_browser_process_stub.cc @@ -0,0 +1,269 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/chrome_browser_process_stub.h" +#include "libcef/browser/context.h" + +#include "base/memory/scoped_ptr.h" +#include "ui/message_center/message_center.h" + +ChromeBrowserProcessStub::ChromeBrowserProcessStub() + : locale_("en-US") { +} + +ChromeBrowserProcessStub::~ChromeBrowserProcessStub() { + g_browser_process = NULL; +} + +void ChromeBrowserProcessStub::ResourceDispatcherHostCreated() { + NOTIMPLEMENTED(); +}; + +void ChromeBrowserProcessStub::EndSession() { + NOTIMPLEMENTED(); +}; + +MetricsServicesManager* ChromeBrowserProcessStub::GetMetricsServicesManager() { + NOTIMPLEMENTED(); + return NULL; +} + +metrics::MetricsService* ChromeBrowserProcessStub::metrics_service() { + NOTIMPLEMENTED(); + return NULL; +} + +rappor::RapporService* ChromeBrowserProcessStub::rappor_service() { + NOTIMPLEMENTED(); + return NULL; +} + +IOThread* ChromeBrowserProcessStub::io_thread() { + NOTIMPLEMENTED(); + return NULL; +} + +WatchDogThread* ChromeBrowserProcessStub::watchdog_thread() { + NOTIMPLEMENTED(); + return NULL; +} + +ProfileManager* ChromeBrowserProcessStub::profile_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +PrefService* ChromeBrowserProcessStub::local_state() { + NOTIMPLEMENTED(); + return NULL; +} + +net::URLRequestContextGetter* + ChromeBrowserProcessStub::system_request_context() { + NOTIMPLEMENTED(); + return NULL; +} + +chrome_variations::VariationsService* + ChromeBrowserProcessStub::variations_service() { + NOTIMPLEMENTED(); + return NULL; +} + +BrowserProcessPlatformPart* ChromeBrowserProcessStub::platform_part() { + NOTIMPLEMENTED(); + return NULL; +} + +extensions::EventRouterForwarder* + ChromeBrowserProcessStub::extension_event_router_forwarder() { + NOTIMPLEMENTED(); + return NULL; +} + +NotificationUIManager* ChromeBrowserProcessStub::notification_ui_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +message_center::MessageCenter* ChromeBrowserProcessStub::message_center() { + NOTIMPLEMENTED(); + return NULL; +} + +policy::BrowserPolicyConnector* + ChromeBrowserProcessStub::browser_policy_connector() { + NOTIMPLEMENTED(); + return NULL; +} + +policy::PolicyService* ChromeBrowserProcessStub::policy_service() { + NOTIMPLEMENTED(); + return NULL; +} + +IconManager* ChromeBrowserProcessStub::icon_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +GLStringManager* ChromeBrowserProcessStub::gl_string_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +GpuModeManager* ChromeBrowserProcessStub::gpu_mode_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +void ChromeBrowserProcessStub::CreateDevToolsHttpProtocolHandler( + chrome::HostDesktopType host_desktop_type, + const std::string& ip, + uint16 port) { +} + +unsigned int ChromeBrowserProcessStub::AddRefModule() { + NOTIMPLEMENTED(); + return 0; +} + +unsigned int ChromeBrowserProcessStub::ReleaseModule() { + NOTIMPLEMENTED(); + return 0; +} + +bool ChromeBrowserProcessStub::IsShuttingDown() { + NOTIMPLEMENTED(); + return false; +} + +printing::PrintJobManager* ChromeBrowserProcessStub::print_job_manager() { + return CefContext::Get()->print_job_manager(); +} + +printing::PrintPreviewDialogController* + ChromeBrowserProcessStub::print_preview_dialog_controller() { + NOTIMPLEMENTED(); + return NULL; +} + +printing::BackgroundPrintingManager* + ChromeBrowserProcessStub::background_printing_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +IntranetRedirectDetector* + ChromeBrowserProcessStub::intranet_redirect_detector() { + NOTIMPLEMENTED(); + return NULL; +} + +const std::string &ChromeBrowserProcessStub::GetApplicationLocale() { + DCHECK(!locale_.empty()); + return locale_; +} + +void ChromeBrowserProcessStub::SetApplicationLocale(const std::string& locale) { + locale_ = locale; +} + +DownloadStatusUpdater* ChromeBrowserProcessStub::download_status_updater() { + NOTIMPLEMENTED(); + return NULL; +} + +DownloadRequestLimiter* ChromeBrowserProcessStub::download_request_limiter() { + NOTIMPLEMENTED(); + return NULL; +} + +BackgroundModeManager* ChromeBrowserProcessStub::background_mode_manager() { + NOTIMPLEMENTED(); + return NULL; +} + +void ChromeBrowserProcessStub::set_background_mode_manager_for_test( + scoped_ptr manager) { + NOTIMPLEMENTED(); +} + +StatusTray* ChromeBrowserProcessStub::status_tray() { + NOTIMPLEMENTED(); + return NULL; +} + +SafeBrowsingService* ChromeBrowserProcessStub::safe_browsing_service() { + NOTIMPLEMENTED(); + return NULL; +} + +safe_browsing::ClientSideDetectionService* + ChromeBrowserProcessStub::safe_browsing_detection_service() { + NOTIMPLEMENTED(); + return NULL; +} + +#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) +void ChromeBrowserProcessStub::StartAutoupdateTimer() { +} +#endif + +ChromeNetLog* ChromeBrowserProcessStub::net_log() { + NOTIMPLEMENTED(); + return NULL; +} + +prerender::PrerenderTracker* ChromeBrowserProcessStub::prerender_tracker() { + NOTIMPLEMENTED(); + return NULL; +} + +component_updater::ComponentUpdateService* + ChromeBrowserProcessStub::component_updater() { + NOTIMPLEMENTED(); + return NULL; +} + +CRLSetFetcher* ChromeBrowserProcessStub::crl_set_fetcher() { + NOTIMPLEMENTED(); + return NULL; +} + +component_updater::PnaclComponentInstaller* + ChromeBrowserProcessStub::pnacl_component_installer() { + NOTIMPLEMENTED(); + return NULL; +} + +MediaFileSystemRegistry* + ChromeBrowserProcessStub::media_file_system_registry() { + NOTIMPLEMENTED(); + return NULL; +} + +bool ChromeBrowserProcessStub::created_local_state() const { + NOTIMPLEMENTED(); + return false; +} + +#if defined(ENABLE_WEBRTC) +WebRtcLogUploader* ChromeBrowserProcessStub::webrtc_log_uploader() { + NOTIMPLEMENTED(); + return NULL; +} +#endif + +network_time::NetworkTimeTracker* + ChromeBrowserProcessStub::network_time_tracker() { + NOTIMPLEMENTED(); + return NULL; +} + +gcm::GCMDriver* ChromeBrowserProcessStub::gcm_driver() { + NOTIMPLEMENTED(); + return NULL; +} diff --git a/libcef/browser/chrome_browser_process_stub.h b/libcef/browser/chrome_browser_process_stub.h new file mode 100644 index 000000000..1309b05a4 --- /dev/null +++ b/libcef/browser/chrome_browser_process_stub.h @@ -0,0 +1,104 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_CHROME_BROWSER_PROCESS_STUB_H_ +#define CEF_LIBCEF_BROWSER_CHROME_BROWSER_PROCESS_STUB_H_ + +#include + +#include "chrome/browser/browser_process.h" +#include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" + +// This file provides a stub implementation of chrome::BrowserProcess so that +// PrintJobWorker can determine the current locale. + +class BackgroundModeManager { + public: + BackgroundModeManager(); + virtual ~BackgroundModeManager(); + private: + DISALLOW_COPY_AND_ASSIGN(BackgroundModeManager); +}; + +class ChromeBrowserProcessStub : public BrowserProcess { + public: + ChromeBrowserProcessStub(); + ~ChromeBrowserProcessStub() override; + + // BrowserProcess implementation. + void ResourceDispatcherHostCreated() override; + void EndSession() override; + MetricsServicesManager* GetMetricsServicesManager() override; + metrics::MetricsService* metrics_service() override; + rappor::RapporService* rappor_service() override; + IOThread* io_thread() override; + WatchDogThread* watchdog_thread() override; + ProfileManager* profile_manager() override; + PrefService* local_state() override; + net::URLRequestContextGetter* system_request_context() override; + chrome_variations::VariationsService* variations_service() override; + BrowserProcessPlatformPart* platform_part() override; + extensions::EventRouterForwarder* + extension_event_router_forwarder() override; + NotificationUIManager* notification_ui_manager() override; + message_center::MessageCenter* message_center() override; + policy::BrowserPolicyConnector* browser_policy_connector() override; + policy::PolicyService* policy_service() override; + IconManager* icon_manager() override; + GLStringManager* gl_string_manager() override; + GpuModeManager* gpu_mode_manager() override; + void CreateDevToolsHttpProtocolHandler( + chrome::HostDesktopType host_desktop_type, + const std::string& ip, + uint16 port) override; + unsigned int AddRefModule() override; + unsigned int ReleaseModule() override; + bool IsShuttingDown() override; + printing::PrintJobManager* print_job_manager() override; + printing::PrintPreviewDialogController* + print_preview_dialog_controller() override; + printing::BackgroundPrintingManager* + background_printing_manager() override; + IntranetRedirectDetector* intranet_redirect_detector() override; + const std::string& GetApplicationLocale() override; + void SetApplicationLocale(const std::string& locale) override; + DownloadStatusUpdater* download_status_updater() override; + DownloadRequestLimiter* download_request_limiter() override; + BackgroundModeManager* background_mode_manager() override; + void set_background_mode_manager_for_test( + scoped_ptr manager) override; + StatusTray* status_tray() override; + SafeBrowsingService* safe_browsing_service() override; + safe_browsing::ClientSideDetectionService* + safe_browsing_detection_service() override; + +#if (defined(OS_WIN) || defined(OS_LINUX)) && !defined(OS_CHROMEOS) + void StartAutoupdateTimer() override; +#endif + + ChromeNetLog* net_log() override; + prerender::PrerenderTracker* prerender_tracker() override; + component_updater::ComponentUpdateService* + component_updater() override; + CRLSetFetcher* crl_set_fetcher() override; + component_updater::PnaclComponentInstaller* + pnacl_component_installer() override; + MediaFileSystemRegistry* + media_file_system_registry() override; + bool created_local_state() const override; +#if defined(ENABLE_WEBRTC) + WebRtcLogUploader* webrtc_log_uploader() override; +#endif + network_time::NetworkTimeTracker* network_time_tracker() override; + gcm::GCMDriver* gcm_driver() override; + + private: + std::string locale_; + + DISALLOW_COPY_AND_ASSIGN(ChromeBrowserProcessStub); +}; + +#endif // CEF_LIBCEF_BROWSER_CHROME_BROWSER_PROCESS_STUB_H_ diff --git a/libcef/browser/chrome_scheme_handler.cc b/libcef/browser/chrome_scheme_handler.cc new file mode 100644 index 000000000..d141f423e --- /dev/null +++ b/libcef/browser/chrome_scheme_handler.cc @@ -0,0 +1,403 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/chrome_scheme_handler.h" + +#include +#include + +#include "include/cef_version.h" +#include "include/cef_web_plugin.h" +#include "libcef/browser/context.h" +#include "libcef/browser/frame_host_impl.h" +#include "libcef/browser/internal_scheme_handler.h" +#include "libcef/browser/scheme_impl.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/content_client.h" + +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "content/browser/net/view_http_cache_job_factory.h" +#include "content/browser/net/view_blob_internals_job_factory.h" +#include "content/public/common/url_constants.h" +#include "content/public/common/user_agent.h" +#include "grit/cef_resources.h" +#include "ipc/ipc_channel.h" +#include "net/url_request/url_request.h" +#include "v8/include/v8.h" + +namespace scheme { + +const char kChromeURL[] = "chrome://"; + +namespace { + +const char kChromeCreditsDomain[] = "credits"; +const char kChromeLicenseDomain[] = "license"; +const char kChromeVersionDomain[] = "version"; + +enum ChromeDomain { + CHROME_UNKNOWN = 0, + CHROME_CREDITS, + CHROME_LICENSE, + CHROME_VERSION, +}; + +ChromeDomain GetChromeDomain(const std::string& domain_name) { + static struct { + const char* name; + ChromeDomain domain; + } domains[] = { + { kChromeCreditsDomain, CHROME_CREDITS }, + { kChromeLicenseDomain, CHROME_LICENSE }, + { kChromeVersionDomain, CHROME_VERSION }, + }; + + for (size_t i = 0; i < sizeof(domains) / sizeof(domains[0]); ++i) { + if (base::strcasecmp(domains[i].name, domain_name.c_str()) == 0) + return domains[i].domain; + } + + return CHROME_UNKNOWN; +} + +std::string GetOSType() { +#if defined(OS_WIN) + return "Windows"; +#elif defined(OS_MACOSX) + return "Mac OS X"; +#elif defined(OS_CHROMEOS) + return "Chromium OS"; +#elif defined(OS_ANDROID) + return "Android"; +#elif defined(OS_LINUX) + return "Linux"; +#elif defined(OS_FREEBSD) + return "FreeBSD"; +#elif defined(OS_OPENBSD) + return "OpenBSD"; +#elif defined(OS_SOLARIS) + return "Solaris"; +#else + return "Unknown"; +#endif +} + +std::string GetCommandLine() { +#if defined(OS_WIN) + return base::WideToUTF8( + base::CommandLine::ForCurrentProcess()->GetCommandLineString()); +#elif defined(OS_POSIX) + std::string command_line = ""; + typedef std::vector ArgvList; + const ArgvList& argv = base::CommandLine::ForCurrentProcess()->argv(); + for (ArgvList::const_iterator iter = argv.begin(); iter != argv.end(); iter++) + command_line += " " + *iter; + // TODO(viettrungluu): |command_line| could really have any encoding, whereas + // below we assumes it's UTF-8. + return command_line; +#endif +} + +std::string GetModulePath() { + base::FilePath path; + if (PathService::Get(base::FILE_MODULE, &path)) + return CefString(path.value()); + return std::string(); +} + +class TemplateParser { + public: + TemplateParser() + : ident_start_("$$"), + ident_end_("$$") { + } + + TemplateParser(const std::string& ident_start, + const std::string& ident_end) + : ident_start_(ident_start), + ident_end_(ident_end) { + } + + void Add(const std::string& key, const std::string& value) { + values_.insert(std::make_pair(key, value)); + } + + void Parse(std::string* tmpl) { + int start_pos, end_pos = 0; + int ident_start_len = ident_start_.length(); + int ident_end_len = ident_end_.length(); + + while(true) { + start_pos = tmpl->find(ident_start_, end_pos); + if (start_pos >= 0) { + end_pos = tmpl->find(ident_end_, start_pos + ident_start_len); + if (end_pos >= 0) { + // Found an identifier. Check if a substitution exists. + std::string key = tmpl->substr(start_pos + ident_start_len, + end_pos - start_pos - ident_start_len); + KeyMap::const_iterator it = values_.find(key); + if (it != values_.end()) { + // Peform the substitution. + tmpl->replace(start_pos, end_pos + ident_end_len - start_pos, + it->second); + end_pos = start_pos + it->second.length(); + } else { + // Leave the unknown identifier in place. + end_pos += ident_end_len; + } + + if (end_pos >= static_cast(tmpl->length()) - ident_start_len - + ident_end_len) { + // Not enough room remaining for more identifiers. + break; + } + } else { + // No end identifier found. + break; + } + } else { + // No start identifier found. + break; + } + } + } + + private: + typedef std::map KeyMap; + KeyMap values_; + std::string ident_start_; + std::string ident_end_; +}; + +class Delegate : public InternalHandlerDelegate { + public: + Delegate() {} + + bool OnRequest(CefRefPtr request, + Action* action) override { + GURL url = GURL(request->GetURL().ToString()); + std::string path = url.path(); + if (path.length() > 0) + path = path.substr(1); + + bool handled = false; + + ChromeDomain domain = GetChromeDomain(url.host()); + switch (domain) { + case CHROME_CREDITS: + handled = OnCredits(path, action); + break; + case CHROME_LICENSE: + handled = OnLicense(action); + break; + case CHROME_VERSION: + handled = OnVersion(action); + break; + default: + break; + } + + if (!handled && domain != CHROME_VERSION) { + LOG(INFO) << "Reguest for unknown chrome resource: " << + url.spec().c_str(); + action->redirect_url = + GURL(std::string(kChromeURL) + kChromeVersionDomain); + } + + return true; + } + + bool OnCredits(const std::string& path, Action* action) { + if (path == "credits.js") { + action->resource_id = IDR_CEF_CREDITS_JS; + } else { + action->mime_type = "text/html"; + action->resource_id = IDR_CEF_CREDITS_HTML; + } + return true; + } + + bool OnLicense(Action* action) { + base::StringPiece piece = CefContentClient::Get()->GetDataResource( + IDR_CEF_LICENSE_TXT, ui::SCALE_FACTOR_NONE); + if (piece.empty()) { + NOTREACHED() << "Failed to load license txt resource."; + return false; + } + + std::string html = "License
" +
+                       piece.as_string() + "
"; + + action->mime_type = "text/html"; + action->stream = CefStreamReader::CreateForData( + const_cast(html.c_str()), html.length()); + action->stream_size = html.length(); + + return true; + } + + bool OnVersion(Action* action) { + base::StringPiece piece = CefContentClient::Get()->GetDataResource( + IDR_CEF_VERSION_HTML, ui::SCALE_FACTOR_NONE); + if (piece.empty()) { + NOTREACHED() << "Failed to load version html resource."; + return false; + } + + TemplateParser parser; + parser.Add("YEAR", MAKE_STRING(COPYRIGHT_YEAR)); + parser.Add("CEF", + base::StringPrintf("%d.%d.%d", + CEF_VERSION_MAJOR, + CHROME_VERSION_BUILD, + CEF_REVISION)); + parser.Add("CHROMIUM", + base::StringPrintf("%d.%d.%d.%d", + CHROME_VERSION_MAJOR, + CHROME_VERSION_MINOR, + CHROME_VERSION_BUILD, + CHROME_VERSION_PATCH)); + parser.Add("OS", GetOSType()); + parser.Add("WEBKIT", + base::StringPrintf("%d.%d", + content::GetWebKitMajorVersion(), + content::GetWebKitMinorVersion())); + parser.Add("JAVASCRIPT", v8::V8::GetVersion()); + parser.Add("FLASH", std::string()); // Value populated asynchronously. + parser.Add("USERAGENT", CefContentClient::Get()->GetUserAgent()); + parser.Add("COMMANDLINE", GetCommandLine()); + parser.Add("MODULEPATH", GetModulePath()); + parser.Add("CACHEPATH", CefString(CefContext::Get()->cache_path().value())); + + std::string tmpl = piece.as_string(); + parser.Parse(&tmpl); + + action->mime_type = "text/html"; + action->stream = CefStreamReader::CreateForData( + const_cast(tmpl.c_str()), tmpl.length()); + action->stream_size = tmpl.length(); + + return true; + } +}; + +void DidFinishChromeVersionLoad(CefRefPtr frame) { + // Retieve Flash version information and update asynchronously. + class Visitor : public CefWebPluginInfoVisitor { + public: + Visitor(CefRefPtr frame) + : frame_(frame) { + } + + bool Visit(CefRefPtr info, + int count, int total) override { + std::string name = info->GetName(); + if (name == "Shockwave Flash") { + if (frame_->IsValid()) { + std::string version = info->GetVersion(); + frame_->ExecuteJavaScript( + "document.getElementById('flash').innerText = '" + version + "';", + std::string(), 0); + } + return false; + } + + return true; + } + + private: + CefRefPtr frame_; + + IMPLEMENT_REFCOUNTING(Visitor); + }; + + CefVisitWebPluginInfo(new Visitor(frame)); +} + +// Wrapper for a ChromeProtocolHandler instance from +// content/browser/webui/url_data_manager_backend.cc. +class ChromeProtocolHandlerWrapper : + public net::URLRequestJobFactory::ProtocolHandler { + public: + explicit ChromeProtocolHandlerWrapper( + scoped_ptr chrome_protocol_handler) + : chrome_protocol_handler_(chrome_protocol_handler.Pass()) { + } + + net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const override { + // Keep synchronized with the checks in ChromeProtocolHandler::MaybeCreateJob. + if (content::ViewHttpCacheJobFactory::IsSupportedURL(request->url()) || + (request->url().SchemeIs(content::kChromeUIScheme) && + request->url().host() == content::kChromeUIAppCacheInternalsHost) || + content::ViewBlobInternalsJobFactory::IsSupportedURL(request->url()) || +#if defined(USE_TCMALLOC) + (request->url().SchemeIs(content::kChromeUIScheme) && + request->url().host() == content::kChromeUITcmallocHost) || +#endif + (request->url().SchemeIs(content::kChromeUIScheme) && + request->url().host() == content::kChromeUIHistogramHost)) { + return chrome_protocol_handler_->MaybeCreateJob(request, network_delegate); + } + + // Use the protocol handler registered with CEF. + return scheme::GetRequestJob(request, network_delegate); + } + + private: + scoped_ptr chrome_protocol_handler_; +}; + +} // namespace + +void RegisterChromeHandler() { + CefRegisterSchemeHandlerFactory( + content::kChromeUIScheme, + std::string(), + CreateInternalHandlerFactory( + make_scoped_ptr(new Delegate()))); +} + +bool WillHandleBrowserAboutURL(GURL* url, + content::BrowserContext* browser_context) { + std::string text = url->possibly_invalid_spec(); + if (text.find("about:") == 0 && text != "about:blank" && text.length() > 6) { + // Redirect about: URLs to chrome:// + *url = GURL(kChromeURL + text.substr(6)); + } + + // Allow the redirection to proceed. + return false; +} + +void DidFinishChromeLoad(CefRefPtr frame, + const GURL& validated_url) { + ChromeDomain domain = GetChromeDomain(validated_url.host()); + switch (domain) { + case CHROME_VERSION: + DidFinishChromeVersionLoad(frame); + default: + break; + } +} + +scoped_ptr +WrapChromeProtocolHandler( + scoped_ptr + chrome_protocol_handler) { + scoped_ptr ret( + new ChromeProtocolHandlerWrapper(chrome_protocol_handler.Pass())); + return ret.Pass(); +} + +} // namespace scheme diff --git a/libcef/browser/chrome_scheme_handler.h b/libcef/browser/chrome_scheme_handler.h new file mode 100644 index 000000000..f5b35f40e --- /dev/null +++ b/libcef/browser/chrome_scheme_handler.h @@ -0,0 +1,51 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_CHROME_SCHEME_HANDLER_H_ +#define CEF_LIBCEF_BROWSER_CHROME_SCHEME_HANDLER_H_ +#pragma once + +#include + +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_process_message.h" + +#include "base/memory/scoped_ptr.h" +#include "net/url_request/url_request_job_factory.h" +#include "url/gurl.h" + +namespace base { +class ListValue; +} + +namespace content { +class BrowserContext; +} + +namespace scheme { + +extern const char kChromeURL[]; + +// Register the chrome scheme handler. +void RegisterChromeHandler(); + +// Used to redirect about: URLs to chrome: URLs. +bool WillHandleBrowserAboutURL(GURL* url, + content::BrowserContext* browser_context); + +// Used to fire any asynchronous content updates. +void DidFinishChromeLoad(CefRefPtr frame, + const GURL& validated_url); + +// Create a new ProtocolHandler that will filter the URLs passed to the default +// "chrome" protocol handler and forward the rest to CEF's handler. +scoped_ptr +WrapChromeProtocolHandler( + scoped_ptr + chrome_protocol_handler); + +} // namespace scheme + +#endif // CEF_LIBCEF_BROWSER_CHROME_SCHEME_HANDLER_H_ diff --git a/libcef/browser/content_browser_client.cc b/libcef/browser/content_browser_client.cc new file mode 100644 index 000000000..356e49fbc --- /dev/null +++ b/libcef/browser/content_browser_client.cc @@ -0,0 +1,1094 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/content_browser_client.h" + +#include + +#include "libcef/browser/browser_context.h" +#include "libcef/browser/browser_context_proxy.h" +#include "libcef/browser/browser_info.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/browser_main.h" +#include "libcef/browser/browser_message_filter.h" +#include "libcef/browser/browser_settings.h" +#include "libcef/browser/chrome_scheme_handler.h" +#include "libcef/browser/context.h" +#include "libcef/browser/devtools_delegate.h" +#include "libcef/browser/media_capture_devices_dispatcher.h" +#include "libcef/browser/printing/printing_message_filter.h" +#include "libcef/browser/resource_dispatcher_host_delegate.h" +#include "libcef/browser/speech_recognition_manager_delegate.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/web_plugin_impl.h" +#include "libcef/common/cef_switches.h" +#include "libcef/common/command_line_impl.h" +#include "libcef/common/content_client.h" +#include "libcef/common/scheme_registration.h" + +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/path_service.h" +#include "chrome/browser/spellchecker/spellcheck_message_filter.h" +#include "chrome/common/chrome_switches.h" +#include "content/browser/plugin_service_impl.h" +#include "content/public/browser/access_token_store.h" +#include "content/public/browser/browser_url_handler.h" +#include "content/public/browser/child_process_security_policy.h" +#include "content/public/browser/geolocation_provider.h" +#include "content/public/browser/plugin_service_filter.h" +#include "content/public/browser/quota_permission_context.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/resource_dispatcher_host.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/storage_quota_params.h" +#include "content/public/common/web_preferences.h" +#include "third_party/WebKit/public/web/WebWindowFeatures.h" +#include "ui/base/ui_base_switches.h" +#include "url/gurl.h" + +#if defined(OS_MACOSX) +#include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h" +#endif + +#if defined(OS_POSIX) && !defined(OS_MACOSX) +#include "base/debug/leak_annotations.h" +#include "components/crash/app/breakpad_linux.h" +#include "components/crash/browser/crash_handler_host_linux.h" +#include "content/public/common/content_descriptors.h" +#endif + +namespace { + +// In-memory store for access tokens used by geolocation. +class CefAccessTokenStore : public content::AccessTokenStore { + public: + CefAccessTokenStore() {} + + void LoadAccessTokens( + const LoadAccessTokensCallbackType& callback) override { + callback.Run(access_token_set_, + CefContentBrowserClient::Get()->request_context().get()); + } + + void SaveAccessToken( + const GURL& server_url, const base::string16& access_token) override { + access_token_set_[server_url] = access_token; + } + + private: + AccessTokenSet access_token_set_; + + DISALLOW_COPY_AND_ASSIGN(CefAccessTokenStore); +}; + +class CefQuotaCallbackImpl : public CefQuotaCallback { + public: + explicit CefQuotaCallbackImpl( + const content::QuotaPermissionContext::PermissionCallback& callback) + : callback_(callback) { + } + + ~CefQuotaCallbackImpl() { + if (!callback_.is_null()) { + // The callback is still pending. Cancel it now. + if (CEF_CURRENTLY_ON_IOT()) { + CancelNow(callback_); + } else { + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefQuotaCallbackImpl::CancelNow, callback_)); + } + } + } + + void Continue(bool allow) override { + if (CEF_CURRENTLY_ON_IOT()) { + if (!callback_.is_null()) { + callback_.Run(allow ? + content::QuotaPermissionContext::QUOTA_PERMISSION_RESPONSE_ALLOW : + content::QuotaPermissionContext::QUOTA_PERMISSION_RESPONSE_DISALLOW); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefQuotaCallbackImpl::Continue, this, allow)); + } + } + + void Cancel() override { + if (CEF_CURRENTLY_ON_IOT()) { + if (!callback_.is_null()) { + CancelNow(callback_); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_IOT, base::Bind(&CefQuotaCallbackImpl::Cancel, this)); + } + } + + void Disconnect() { + callback_.Reset(); + } + + private: + static void CancelNow( + const content::QuotaPermissionContext::PermissionCallback& callback) { + CEF_REQUIRE_IOT(); + callback.Run( + content::QuotaPermissionContext::QUOTA_PERMISSION_RESPONSE_CANCELLED); + } + + content::QuotaPermissionContext::PermissionCallback callback_; + + IMPLEMENT_REFCOUNTING(CefQuotaCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefQuotaCallbackImpl); +}; + +class CefAllowCertificateErrorCallbackImpl + : public CefAllowCertificateErrorCallback { + public: + typedef base::Callback // NOLINT(readability/function) + CallbackType; + + explicit CefAllowCertificateErrorCallbackImpl(const CallbackType& callback) + : callback_(callback) { + } + + void Continue(bool allow) override { + if (CEF_CURRENTLY_ON_UIT()) { + if (!callback_.is_null()) { + callback_.Run(allow); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefAllowCertificateErrorCallbackImpl::Continue, + this, allow)); + } + } + + void Disconnect() { + callback_.Reset(); + } + + private: + CallbackType callback_; + + IMPLEMENT_REFCOUNTING(CefAllowCertificateErrorCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefAllowCertificateErrorCallbackImpl); +}; + +class CefGeolocationCallbackImpl : public CefGeolocationCallback { + public: + typedef base::Callback // NOLINT(readability/function) + CallbackType; + + explicit CefGeolocationCallbackImpl(const CallbackType& callback) + : callback_(callback) {} + + void Continue(bool allow) override { + if (CEF_CURRENTLY_ON_UIT()) { + if (!callback_.is_null()) { + if (allow) { + content::GeolocationProvider::GetInstance()-> + UserDidOptIntoLocationServices(); + } + + callback_.Run(allow); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefGeolocationCallbackImpl::Continue, this, allow)); + } + } + + void Disconnect() { + callback_.Reset(); + } + + private: + static void Run(const CallbackType& callback, bool allow) { + CEF_REQUIRE_UIT(); + callback.Run(allow); + } + + CallbackType callback_; + + IMPLEMENT_REFCOUNTING(CefGeolocationCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefGeolocationCallbackImpl); +}; + +class CefQuotaPermissionContext : public content::QuotaPermissionContext { + public: + CefQuotaPermissionContext() { + } + + // The callback will be dispatched on the IO thread. + void RequestQuotaPermission( + const content::StorageQuotaParams& params, + int render_process_id, + const PermissionCallback& callback) override { + if (params.storage_type != storage::kStorageTypePersistent) { + // To match Chrome behavior we only support requesting quota with this + // interface for Persistent storage type. + callback.Run(QUOTA_PERMISSION_RESPONSE_DISALLOW); + return; + } + + bool handled = false; + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForView(render_process_id, + params.render_view_id); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr callbackImpl( + new CefQuotaCallbackImpl(callback)); + handled = handler->OnQuotaRequest(browser.get(), + params.origin_url.spec(), + params.requested_size, + callbackImpl.get()); + if (!handled) + callbackImpl->Disconnect(); + } + } + } + + if (!handled) { + // Disallow the request by default. + callback.Run(QUOTA_PERMISSION_RESPONSE_DISALLOW); + } + } + + private: + ~CefQuotaPermissionContext() override {} + + DISALLOW_COPY_AND_ASSIGN(CefQuotaPermissionContext); +}; + +class CefPluginServiceFilter : public content::PluginServiceFilter { + public: + CefPluginServiceFilter() {} + + bool IsPluginAvailable(int render_process_id, + int render_frame_id, + const void* context, + const GURL& url, + const GURL& policy_url, + content::WebPluginInfo* plugin) override { + bool allowed = true; + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForFrame(render_process_id, + render_frame_id); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr pluginInfo( + new CefWebPluginInfoImpl(*plugin)); + allowed = + !handler->OnBeforePluginLoad(browser.get(), + url.possibly_invalid_spec(), + policy_url.possibly_invalid_spec(), + pluginInfo.get()); + } + } + } + + return allowed; + } + + bool CanLoadPlugin(int render_process_id, + const base::FilePath& path) override { + return true; + } + + DISALLOW_COPY_AND_ASSIGN(CefPluginServiceFilter); +}; + +void TranslatePopupFeatures(const blink::WebWindowFeatures& webKitFeatures, + CefPopupFeatures& features) { + features.x = static_cast(webKitFeatures.x); + features.xSet = webKitFeatures.xSet; + features.y = static_cast(webKitFeatures.y); + features.ySet = webKitFeatures.ySet; + features.width = static_cast(webKitFeatures.width); + features.widthSet = webKitFeatures.widthSet; + features.height = static_cast(webKitFeatures.height); + features.heightSet = webKitFeatures.heightSet; + + features.menuBarVisible = webKitFeatures.menuBarVisible; + features.statusBarVisible = webKitFeatures.statusBarVisible; + features.toolBarVisible = webKitFeatures.toolBarVisible; + features.locationBarVisible = webKitFeatures.locationBarVisible; + features.scrollbarsVisible = webKitFeatures.scrollbarsVisible; + features.resizable = webKitFeatures.resizable; + + features.fullscreen = webKitFeatures.fullscreen; + features.dialog = webKitFeatures.dialog; + features.additionalFeatures = NULL; + if (webKitFeatures.additionalFeatures.size() > 0) + features.additionalFeatures = cef_string_list_alloc(); + + CefString str; + for (unsigned int i = 0; i < webKitFeatures.additionalFeatures.size(); ++i) { + str = base::string16(webKitFeatures.additionalFeatures[i]); + cef_string_list_append(features.additionalFeatures, str.GetStruct()); + } +} + +#if defined(OS_POSIX) && !defined(OS_MACOSX) +breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( + const std::string& process_type) { + base::FilePath dumps_path = + base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( + switches::kCrashDumpsDir); + { + ANNOTATE_SCOPED_MEMORY_LEAK; + breakpad::CrashHandlerHostLinux* crash_handler = + new breakpad::CrashHandlerHostLinux( + process_type, dumps_path, false); + crash_handler->StartUploaderThread(); + return crash_handler; + } +} + +int GetCrashSignalFD(const base::CommandLine& command_line) { + if (!breakpad::IsCrashReporterEnabled()) + return -1; + + std::string process_type = + command_line.GetSwitchValueASCII(switches::kProcessType); + + if (process_type == switches::kRendererProcess) { + static breakpad::CrashHandlerHostLinux* crash_handler = NULL; + if (!crash_handler) + crash_handler = CreateCrashHandlerHost(process_type); + return crash_handler->GetDeathSignalSocket(); + } + + if (process_type == switches::kPluginProcess) { + static breakpad::CrashHandlerHostLinux* crash_handler = NULL; + if (!crash_handler) + crash_handler = CreateCrashHandlerHost(process_type); + return crash_handler->GetDeathSignalSocket(); + } + + if (process_type == switches::kPpapiPluginProcess) { + static breakpad::CrashHandlerHostLinux* crash_handler = NULL; + if (!crash_handler) + crash_handler = CreateCrashHandlerHost(process_type); + return crash_handler->GetDeathSignalSocket(); + } + + if (process_type == switches::kGpuProcess) { + static breakpad::CrashHandlerHostLinux* crash_handler = NULL; + if (!crash_handler) + crash_handler = CreateCrashHandlerHost(process_type); + return crash_handler->GetDeathSignalSocket(); + } + + return -1; +} +#endif // defined(OS_POSIX) && !defined(OS_MACOSX) + +} // namespace + + +CefContentBrowserClient::CefContentBrowserClient() + : browser_main_parts_(NULL), + next_browser_id_(0) { + plugin_service_filter_.reset(new CefPluginServiceFilter); + content::PluginServiceImpl::GetInstance()->SetFilter( + plugin_service_filter_.get()); + + last_create_window_params_.opener_process_id = MSG_ROUTING_NONE; +} + +CefContentBrowserClient::~CefContentBrowserClient() { +} + +// static +CefContentBrowserClient* CefContentBrowserClient::Get() { + return static_cast( + CefContentClient::Get()->browser()); +} + +scoped_refptr CefContentBrowserClient::CreateBrowserInfo( + bool is_popup) { + base::AutoLock lock_scope(browser_info_lock_); + + scoped_refptr browser_info = + new CefBrowserInfo(++next_browser_id_, is_popup); + browser_info_list_.push_back(browser_info); + return browser_info; +} + +scoped_refptr + CefContentBrowserClient::GetOrCreateBrowserInfo( + int render_view_process_id, + int render_view_routing_id, + int render_frame_process_id, + int render_frame_routing_id) { + base::AutoLock lock_scope(browser_info_lock_); + + BrowserInfoList::const_iterator it = browser_info_list_.begin(); + for (; it != browser_info_list_.end(); ++it) { + const scoped_refptr& browser_info = *it; + if (browser_info->is_render_view_id_match(render_view_process_id, + render_view_routing_id)) { + // Make sure the frame id is also registered. + browser_info->add_render_frame_id(render_frame_process_id, + render_frame_routing_id); + return browser_info; + } else if (browser_info->is_render_frame_id_match( + render_frame_process_id, + render_frame_routing_id)) { + // Make sure the view id is also registered. + browser_info->add_render_view_id(render_view_process_id, + render_view_routing_id); + return browser_info; + } + } + + // Must be a popup if it hasn't already been created. + scoped_refptr browser_info = + new CefBrowserInfo(++next_browser_id_, true); + browser_info->add_render_view_id(render_view_process_id, + render_view_routing_id); + browser_info->add_render_frame_id(render_frame_process_id, + render_frame_routing_id); + browser_info_list_.push_back(browser_info); + return browser_info; +} + +void CefContentBrowserClient::RemoveBrowserInfo( + scoped_refptr browser_info) { + base::AutoLock lock_scope(browser_info_lock_); + + BrowserInfoList::iterator it = browser_info_list_.begin(); + for (; it != browser_info_list_.end(); ++it) { + if (*it == browser_info) { + browser_info_list_.erase(it); + return; + } + } + + NOTREACHED(); +} + +void CefContentBrowserClient::DestroyAllBrowsers() { + BrowserInfoList list; + + { + base::AutoLock lock_scope(browser_info_lock_); + list = browser_info_list_; + } + + // Destroy any remaining browser windows. + if (!list.empty()) { + BrowserInfoList::iterator it = list.begin(); + for (; it != list.end(); ++it) { + CefRefPtr browser = (*it)->browser(); + if (browser.get()) { + // DestroyBrowser will call RemoveBrowserInfo. + browser->DestroyBrowser(); + } else { + // Canceled popup windows may have browser info but no browser because + // CefBrowserMessageFilter::OnGetNewBrowserInfo is still called. + DCHECK((*it)->is_popup()); + RemoveBrowserInfo(*it); + } + } + } + +#ifndef NDEBUG + { + // Verify that all browser windows have been destroyed. + base::AutoLock lock_scope(browser_info_lock_); + DCHECK(browser_info_list_.empty()); + } +#endif +} + +scoped_refptr CefContentBrowserClient::GetBrowserInfoForView( + int render_process_id, int render_routing_id) { + base::AutoLock lock_scope(browser_info_lock_); + + BrowserInfoList::const_iterator it = browser_info_list_.begin(); + for (; it != browser_info_list_.end(); ++it) { + const scoped_refptr& browser_info = *it; + if (browser_info->is_render_view_id_match( + render_process_id, render_routing_id)) { + return browser_info; + } + } + + LOG(WARNING) << "No browser info matching view process id " << + render_process_id << " and routing id " << render_routing_id; + + return scoped_refptr(); +} + +scoped_refptr CefContentBrowserClient::GetBrowserInfoForFrame( + int render_process_id, int render_routing_id) { + base::AutoLock lock_scope(browser_info_lock_); + + BrowserInfoList::const_iterator it = browser_info_list_.begin(); + for (; it != browser_info_list_.end(); ++it) { + const scoped_refptr& browser_info = *it; + if (browser_info->is_render_frame_id_match( + render_process_id, render_routing_id)) { + return browser_info; + } + } + + LOG(WARNING) << "No browser info matching frame process id " << + render_process_id << " and routing id " << render_routing_id; + + return scoped_refptr(); +} + +CefBrowserContext* CefContentBrowserClient::CreateBrowserContextProxy( + CefRefPtr handler) { + CEF_REQUIRE_UIT(); + CefBrowserContextProxy* context = + new CefBrowserContextProxy(handler, browser_context()); + browser_main_parts_->AddBrowserContext(context); + context->AddRef(); + return context; +} + +void CefContentBrowserClient::AddBrowserContextReference( + CefBrowserContext* context) { + CEF_REQUIRE_UIT(); + // Skip the global browser context. + if (context == browser_context()) + return; + + CefBrowserContextProxy* proxy = static_cast(context); + proxy->AddRef(); +} + +void CefContentBrowserClient::RemoveBrowserContextReference( + CefBrowserContext* context) { + CEF_REQUIRE_UIT(); + // Skip the global browser context. + if (context == browser_context()) + return; + + CefBrowserContextProxy* proxy = static_cast(context); + if (proxy->Release()) + browser_main_parts_->RemoveBrowserContext(proxy); +} + +content::BrowserMainParts* CefContentBrowserClient::CreateBrowserMainParts( + const content::MainFunctionParams& parameters) { + browser_main_parts_ = new CefBrowserMainParts(parameters); + return browser_main_parts_; +} + +void CefContentBrowserClient::RenderProcessWillLaunch( + content::RenderProcessHost* host) { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + const int id = host->GetID(); + + host->GetChannel()->AddFilter(new CefBrowserMessageFilter(host)); + host->AddFilter(new printing::PrintingMessageFilter(id)); + + if (!command_line->HasSwitch(switches::kDisableSpellChecking)) { + host->AddFilter(new SpellCheckMessageFilter(id)); +#if defined(OS_MACOSX) + host->AddFilter(new SpellCheckMessageFilterMac(id)); +#endif + } + + AddBrowserContextReference( + static_cast(host->GetBrowserContext())); +} + +net::URLRequestContextGetter* CefContentBrowserClient::CreateRequestContext( + content::BrowserContext* content_browser_context, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) { + CefBrowserContext* cef_browser_context = + static_cast(content_browser_context); + return cef_browser_context->CreateRequestContext( + protocol_handlers, + request_interceptors.Pass()); +} + +net::URLRequestContextGetter* +CefContentBrowserClient::CreateRequestContextForStoragePartition( + content::BrowserContext* content_browser_context, + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) { + CefBrowserContext* cef_browser_context = + static_cast(content_browser_context); + return cef_browser_context->CreateRequestContextForStoragePartition( + partition_path, + in_memory, + protocol_handlers, + request_interceptors.Pass()); +} + +bool CefContentBrowserClient::IsHandledURL(const GURL& url) { + if (!url.is_valid()) + return false; + const std::string& scheme = url.scheme(); + DCHECK_EQ(scheme, base::StringToLowerASCII(scheme)); + + if (scheme::IsInternalHandledScheme(scheme)) + return true; + + return CefContentClient::Get()->HasCustomScheme(scheme); +} + +void CefContentBrowserClient::AppendExtraCommandLineSwitches( + base::CommandLine* command_line, int child_process_id) { + const base::CommandLine* browser_cmd = + base::CommandLine::ForCurrentProcess(); + + { + // Propagate the following switches to all command lines (along with any + // associated values) if present in the browser command line. + static const char* const kSwitchNames[] = { +#if !defined(OS_WIN) + switches::kCrashDumpsDir, +#endif + switches::kDisablePackLoading, + switches::kEnableCrashReporter, + switches::kLang, + switches::kLocalesDirPath, + switches::kLogFile, + switches::kLogSeverity, + switches::kProductVersion, + switches::kResourcesDirPath, + switches::kUserAgent, + }; + command_line->CopySwitchesFrom(*browser_cmd, kSwitchNames, + arraysize(kSwitchNames)); + } + + const std::string& process_type = + command_line->GetSwitchValueASCII(switches::kProcessType); + if (process_type == switches::kRendererProcess) { + // Propagate the following switches to the renderer command line (along with + // any associated values) if present in the browser command line. + static const char* const kSwitchNames[] = { + switches::kContextSafetyImplementation, + switches::kDisableSpellChecking, + switches::kEnableSpeechInput, + switches::kEnableSpellingAutoCorrect, + switches::kUncaughtExceptionStackSize, + }; + command_line->CopySwitchesFrom(*browser_cmd, kSwitchNames, + arraysize(kSwitchNames)); + } + +#if defined(OS_LINUX) + if (process_type == switches::kZygoteProcess && + browser_cmd->HasSwitch(switches::kBrowserSubprocessPath)) { + // Force use of the sub-process executable path for the zygote process. + const base::FilePath& subprocess_path = + browser_cmd->GetSwitchValuePath(switches::kBrowserSubprocessPath); + if (!subprocess_path.empty()) + command_line->SetProgram(subprocess_path); + } +#endif // defined(OS_LINUX) + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetBrowserProcessHandler(); + if (handler.get()) { + CefRefPtr commandLinePtr( + new CefCommandLineImpl(command_line, false, false)); + handler->OnBeforeChildProcessLaunch(commandLinePtr.get()); + commandLinePtr->Detach(NULL); + } + } +} + +content::QuotaPermissionContext* + CefContentBrowserClient::CreateQuotaPermissionContext() { + return new CefQuotaPermissionContext(); +} + +content::MediaObserver* CefContentBrowserClient::GetMediaObserver() { + return CefMediaCaptureDevicesDispatcher::GetInstance(); +} + +content::SpeechRecognitionManagerDelegate* + CefContentBrowserClient::CreateSpeechRecognitionManagerDelegate() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kEnableSpeechInput)) + return new CefSpeechRecognitionManagerDelegate(); + + return NULL; +} + +void CefContentBrowserClient::AllowCertificateError( + int render_process_id, + int render_frame_id, + int cert_error, + const net::SSLInfo& ssl_info, + const GURL& request_url, + content::ResourceType resource_type, + bool overridable, + bool strict_enforcement, + bool expired_previous_decision, + const base::Callback& callback, + content::CertificateRequestResultType* result) { + CEF_REQUIRE_UIT(); + + if (resource_type != content::ResourceType::RESOURCE_TYPE_MAIN_FRAME) { + // A sub-resource has a certificate error. The user doesn't really + // have a context for making the right decision, so block the request + // hard. + *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL; + return; + } + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForFrame(render_process_id, + render_frame_id); + if (!browser.get()) + return; + CefRefPtr client = browser->GetClient(); + if (!client.get()) + return; + CefRefPtr handler = client->GetRequestHandler(); + if (!handler.get()) + return; + + CefRefPtr callbackImpl; + if (overridable && !strict_enforcement) + callbackImpl = new CefAllowCertificateErrorCallbackImpl(callback); + + bool proceed = handler->OnCertificateError( + static_cast(cert_error), request_url.spec(), + callbackImpl.get()); + if (!proceed && callbackImpl.get()) + callbackImpl->Disconnect(); + + *result = proceed ? content::CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE : + content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL; +} + +content::AccessTokenStore* CefContentBrowserClient::CreateAccessTokenStore() { + return new CefAccessTokenStore; +} + +void CefContentBrowserClient::RequestPermission( + content::PermissionType permission, + content::WebContents* web_contents, + int bridge_id, + const GURL& requesting_frame, + bool user_gesture, + const base::Callback& result_callback) { + CEF_REQUIRE_UIT(); + + if (permission != content::PermissionType::PERMISSION_GEOLOCATION) { + result_callback.Run(false); + return; + } + + bool proceed = false; + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForContents(web_contents); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = + client->GetGeolocationHandler(); + if (handler.get()) { + CefRefPtr callbackImpl( + new CefGeolocationCallbackImpl(result_callback)); + + // Notify the handler. + proceed = handler->OnRequestGeolocationPermission( + browser.get(), requesting_frame.spec(), bridge_id, + callbackImpl.get()); + if (!proceed) + callbackImpl->Disconnect(); + } + } + } + + if (!proceed) { + // Disallow geolocation access by default. + result_callback.Run(false); + } +} + +void CefContentBrowserClient::CancelPermissionRequest( + content::PermissionType permission, + content::WebContents* web_contents, + int bridge_id, + const GURL& requesting_frame) { + CEF_REQUIRE_UIT(); + + if (permission != content::PermissionType::PERMISSION_GEOLOCATION) + return; + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForContents(web_contents); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = + client->GetGeolocationHandler(); + if (handler.get()) { + handler->OnCancelGeolocationPermission(browser.get(), + requesting_frame.spec(), + bridge_id); + } + } + } +} + +bool CefContentBrowserClient::CanCreateWindow( + const GURL& opener_url, + const GURL& opener_top_level_frame_url, + const GURL& source_origin, + WindowContainerType container_type, + const GURL& target_url, + const content::Referrer& referrer, + WindowOpenDisposition disposition, + const blink::WebWindowFeatures& features, + bool user_gesture, + bool opener_suppressed, + content::ResourceContext* context, + int render_process_id, + int opener_id, + bool* no_javascript_access) { + CEF_REQUIRE_IOT(); + *no_javascript_access = false; + + DCHECK_NE(last_create_window_params_.opener_process_id, MSG_ROUTING_NONE); + if (last_create_window_params_.opener_process_id == MSG_ROUTING_NONE) + return false; + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForView( + last_create_window_params_.opener_process_id, + last_create_window_params_.opener_view_id); + DCHECK(browser.get()); + if (!browser.get()) { + LOG(WARNING) << "CanCreateWindow called before browser was created"; + return false; + } + + CefRefPtr client = browser->GetClient(); + bool allow = true; + + scoped_ptr pending_info; + pending_info.reset(new CefBrowserHostImpl::PendingPopupInfo); + +#if defined(OS_WIN) + pending_info->window_info.SetAsPopup(NULL, CefString()); +#endif + + // Start with the current browser's settings. + pending_info->client = client; + pending_info->settings = browser->settings(); + + if (client.get()) { + CefRefPtr handler = client->GetLifeSpanHandler(); + if (handler.get()) { + CefRefPtr frame = + browser->GetFrame(last_create_window_params_.opener_frame_id); + + CefPopupFeatures cef_features; + TranslatePopupFeatures(features, cef_features); + +#if (defined(OS_WIN) || defined(OS_MACOSX)) + // Default to the size from the popup features. + if (cef_features.xSet) + pending_info->window_info.x = cef_features.x; + if (cef_features.ySet) + pending_info->window_info.y = cef_features.y; + if (cef_features.widthSet) + pending_info->window_info.width = cef_features.width; + if (cef_features.heightSet) + pending_info->window_info.height = cef_features.height; +#endif + + allow = !handler->OnBeforePopup(browser.get(), + frame, + last_create_window_params_.target_url.spec(), + last_create_window_params_.target_frame_name, + cef_features, + pending_info->window_info, + pending_info->client, + pending_info->settings, + no_javascript_access); + } + } + + if (allow) { + CefRefPtr pending_client = pending_info->client; + allow = browser->SetPendingPopupInfo(pending_info.Pass()); + if (!allow) { + LOG(WARNING) << "Creation of popup window denied because one is already " + "pending."; + } + } + + last_create_window_params_.opener_process_id = MSG_ROUTING_NONE; + + return allow; +} + +void CefContentBrowserClient::ResourceDispatcherHostCreated() { + resource_dispatcher_host_delegate_.reset( + new CefResourceDispatcherHostDelegate()); + content::ResourceDispatcherHost::Get()->SetDelegate( + resource_dispatcher_host_delegate_.get()); +} + +void CefContentBrowserClient::OverrideWebkitPrefs( + content::RenderViewHost* rvh, + const GURL& url, + content::WebPreferences* prefs) { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForHost(rvh); + DCHECK(browser.get()); + + // Populate WebPreferences based on CefBrowserSettings. + BrowserToWebSettings(browser->settings(), *prefs); + + prefs->base_background_color = GetBaseBackgroundColor(rvh); + + prefs->asynchronous_spell_checking_enabled = true; + // Auto-correct does not work in combination with the unified text checker. + prefs->unified_textchecker_enabled = + !command_line->HasSwitch(switches::kEnableSpellingAutoCorrect); +} + +SkColor CefContentBrowserClient::GetBaseBackgroundColor( + content::RenderViewHost* rvh) { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForHost(rvh); + DCHECK(browser.get()); + + const CefBrowserSettings& browser_settings = browser->settings(); + if (CefColorGetA(browser_settings.background_color) > 0) { + return SkColorSetRGB( + CefColorGetR(browser_settings.background_color), + CefColorGetG(browser_settings.background_color), + CefColorGetB(browser_settings.background_color)); + } else { + const CefSettings& settings = CefContext::Get()->settings(); + if (CefColorGetA(settings.background_color) > 0) { + return SkColorSetRGB( + CefColorGetR(settings.background_color), + CefColorGetG(settings.background_color), + CefColorGetB(settings.background_color)); + } + } + + return SK_ColorWHITE; +} + +void CefContentBrowserClient::BrowserURLHandlerCreated( + content::BrowserURLHandler* handler) { + // Used to redirect about: URLs to chrome: URLs. + handler->AddHandlerPair(&scheme::WillHandleBrowserAboutURL, + content::BrowserURLHandler::null_handler()); +} + +std::string CefContentBrowserClient::GetDefaultDownloadName() { + return "download"; +} + +content::DevToolsManagerDelegate* + CefContentBrowserClient::GetDevToolsManagerDelegate() { + return new CefDevToolsManagerDelegate(browser_context()); +} + +#if defined(OS_POSIX) && !defined(OS_MACOSX) +void CefContentBrowserClient::GetAdditionalMappedFilesForChildProcess( + const base::CommandLine& command_line, + int child_process_id, + content::FileDescriptorInfo* mappings) { + int crash_signal_fd = GetCrashSignalFD(command_line); + if (crash_signal_fd >= 0) { + mappings->Share(kCrashDumpSignal, crash_signal_fd); + } +} +#endif // defined(OS_POSIX) && !defined(OS_MACOSX) + + +#if defined(OS_WIN) +const wchar_t* CefContentBrowserClient::GetResourceDllName() { + static wchar_t file_path[MAX_PATH+1] = {0}; + + if (file_path[0] == 0) { + // Retrieve the module path (usually libcef.dll). + base::FilePath module; + PathService::Get(base::FILE_MODULE, &module); + const std::wstring wstr = module.value(); + size_t count = std::min(static_cast(MAX_PATH), wstr.size()); + wcsncpy(file_path, wstr.c_str(), count); + file_path[count] = 0; + } + + return file_path; +} +#endif // defined(OS_WIN) + +void CefContentBrowserClient::RegisterCustomScheme(const std::string& scheme) { + // Register as a Web-safe scheme so that requests for the scheme from a + // render process will be allowed in resource_dispatcher_host_impl.cc + // ShouldServiceRequest. + content::ChildProcessSecurityPolicy* policy = + content::ChildProcessSecurityPolicy::GetInstance(); + if (!policy->IsWebSafeScheme(scheme)) + policy->RegisterWebSafeScheme(scheme); +} + +void CefContentBrowserClient::set_last_create_window_params( + const LastCreateWindowParams& params) { + CEF_REQUIRE_IOT(); + last_create_window_params_ = params; +} + +CefBrowserContext* CefContentBrowserClient::browser_context() const { + return browser_main_parts_->browser_context(); +} + +scoped_refptr +CefContentBrowserClient::request_context() const { + return browser_main_parts_->request_context(); +} + +CefDevToolsDelegate* CefContentBrowserClient::devtools_delegate() const { + return browser_main_parts_->devtools_delegate(); +} + +PrefService* CefContentBrowserClient::pref_service() const { + return browser_main_parts_->pref_service(); +} + +scoped_ptr +CefContentBrowserClient::proxy_config_service() const { + return browser_main_parts_->proxy_config_service(); +} diff --git a/libcef/browser/content_browser_client.h b/libcef/browser/content_browser_client.h new file mode 100644 index 000000000..4108dabc0 --- /dev/null +++ b/libcef/browser/content_browser_client.h @@ -0,0 +1,206 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_CONTENT_BROWSER_CLIENT_H_ +#define CEF_LIBCEF_BROWSER_CONTENT_BROWSER_CLIENT_H_ +#pragma once + +#include +#include +#include +#include +#include + +#include "include/cef_request_context_handler.h" + +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/synchronization/lock.h" +#include "content/public/browser/content_browser_client.h" +#include "net/proxy/proxy_config_service.h" +#include "net/url_request/url_request_context_getter.h" +#include "url/gurl.h" + +class CefBrowserContext; +class CefBrowserInfo; +class CefBrowserMainParts; +class CefDevToolsDelegate; +class CefResourceDispatcherHostDelegate; +class PrefService; + +namespace content { +class PluginServiceFilter; +class SiteInstance; +} + +class CefContentBrowserClient : public content::ContentBrowserClient { + public: + CefContentBrowserClient(); + ~CefContentBrowserClient() override; + + // Returns the singleton CefContentBrowserClient instance. + static CefContentBrowserClient* Get(); + + // Methods for managing CefBrowserInfo life span. Do not add new callers of + // these methods. + // During popup window creation there is a race between the call to + // CefBrowserMessageFilter::OnGetNewBrowserInfo on the IO thread and the call + // to CefBrowserHostImpl::ShouldCreateWebContents on the UI thread. To resolve + // this race CefBrowserInfo may be created when requested for the first time + // and before the associated CefBrowserHostImpl is created. + scoped_refptr CreateBrowserInfo(bool is_popup); + scoped_refptr GetOrCreateBrowserInfo( + int render_view_process_id, + int render_view_routing_id, + int render_frame_process_id, + int render_frame_routing_id); + void RemoveBrowserInfo(scoped_refptr browser_info); + void DestroyAllBrowsers(); + + // Retrieves the CefBrowserInfo matching the specified IDs or an empty + // pointer if no match is found. It is allowed to add new callers of this + // method but consider using CefBrowserHostImpl::GetBrowserFor[View|Frame]() + // instead. + scoped_refptr GetBrowserInfoForView(int render_process_id, + int render_routing_id); + scoped_refptr GetBrowserInfoForFrame(int render_process_id, + int render_routing_id); + + // Create and return a new CefBrowserContextProxy object. + CefBrowserContext* CreateBrowserContextProxy( + CefRefPtr handler); + + // BrowserContexts are nominally owned by RenderViewHosts and + // CefRequestContextImpls. Keep track of how many objects reference a given + // context and delete the context when the reference count reaches zero. + void AddBrowserContextReference(CefBrowserContext* context); + void RemoveBrowserContextReference(CefBrowserContext* context); + + // ContentBrowserClient implementation. + content::BrowserMainParts* CreateBrowserMainParts( + const content::MainFunctionParams& parameters) override; + void RenderProcessWillLaunch( + content::RenderProcessHost* host) override; + net::URLRequestContextGetter* CreateRequestContext( + content::BrowserContext* browser_context, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + override; + net::URLRequestContextGetter* CreateRequestContextForStoragePartition( + content::BrowserContext* browser_context, + const base::FilePath& partition_path, + bool in_memory, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + override; + bool IsHandledURL(const GURL& url) override; + void AppendExtraCommandLineSwitches(base::CommandLine* command_line, + int child_process_id) override; + content::QuotaPermissionContext* + CreateQuotaPermissionContext() override; + content::MediaObserver* GetMediaObserver() override; + content::SpeechRecognitionManagerDelegate* + CreateSpeechRecognitionManagerDelegate() override; + void AllowCertificateError( + int render_process_id, + int render_frame_id, + int cert_error, + const net::SSLInfo& ssl_info, + const GURL& request_url, + content::ResourceType resource_type, + bool overridable, + bool strict_enforcement, + bool expired_previous_decision, + const base::Callback& callback, + content::CertificateRequestResultType* result) override; + content::AccessTokenStore* CreateAccessTokenStore() override; + void RequestPermission( + content::PermissionType permission, + content::WebContents* web_contents, + int bridge_id, + const GURL& requesting_frame, + bool user_gesture, + const base::Callback& result_callback) override; + void CancelPermissionRequest(content::PermissionType permission, + content::WebContents* web_contents, + int bridge_id, + const GURL& requesting_frame) override; + bool CanCreateWindow(const GURL& opener_url, + const GURL& opener_top_level_frame_url, + const GURL& source_origin, + WindowContainerType container_type, + const GURL& target_url, + const content::Referrer& referrer, + WindowOpenDisposition disposition, + const blink::WebWindowFeatures& features, + bool user_gesture, + bool opener_suppressed, + content::ResourceContext* context, + int render_process_id, + int opener_id, + bool* no_javascript_access) override; + void ResourceDispatcherHostCreated() override; + void OverrideWebkitPrefs(content::RenderViewHost* rvh, + const GURL& url, + content::WebPreferences* prefs) override; + SkColor GetBaseBackgroundColor(content::RenderViewHost* rvh) override; + void BrowserURLHandlerCreated( + content::BrowserURLHandler* handler) override; + std::string GetDefaultDownloadName() override; + content::DevToolsManagerDelegate* GetDevToolsManagerDelegate() + override; + +#if defined(OS_POSIX) && !defined(OS_MACOSX) + void GetAdditionalMappedFilesForChildProcess( + const base::CommandLine& command_line, + int child_process_id, + content::FileDescriptorInfo* mappings) override; +#endif + +#if defined(OS_WIN) + const wchar_t* GetResourceDllName() override; +#endif + + // Perform browser process registration for the custom scheme. + void RegisterCustomScheme(const std::string& scheme); + + // Store additional state from the ViewHostMsg_CreateWindow message that will + // be used when CanCreateWindow() is called. + struct LastCreateWindowParams { + int opener_process_id; + int opener_view_id; + int64 opener_frame_id; + GURL target_url; + base::string16 target_frame_name; + }; + void set_last_create_window_params(const LastCreateWindowParams& params); + + CefBrowserContext* browser_context() const; + scoped_refptr request_context() const; + CefDevToolsDelegate* devtools_delegate() const; + PrefService* pref_service() const; + + // Passes ownership. + scoped_ptr proxy_config_service() const; + + private: + CefBrowserMainParts* browser_main_parts_; + + scoped_ptr plugin_service_filter_; + scoped_ptr + resource_dispatcher_host_delegate_; + + base::Lock browser_info_lock_; + + // Access must be protected by |browser_info_lock_|. + typedef std::list > BrowserInfoList; + BrowserInfoList browser_info_list_; + int next_browser_id_; + + // Only accessed on the IO thread. + LastCreateWindowParams last_create_window_params_; +}; + +#endif // CEF_LIBCEF_BROWSER_CONTENT_BROWSER_CLIENT_H_ diff --git a/libcef/browser/context.cc b/libcef/browser/context.cc new file mode 100644 index 000000000..e71c704b8 --- /dev/null +++ b/libcef/browser/context.cc @@ -0,0 +1,423 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/context.h" +#include "libcef/browser/browser_context.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/browser_info.h" +#include "libcef/browser/browser_main.h" +#include "libcef/browser/browser_message_loop.h" +#include "libcef/browser/chrome_browser_process_stub.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/scheme_handler.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/trace_subscriber.h" +#include "libcef/common/main_delegate.h" +#include "libcef/renderer/content_renderer_client.h" + +#include "base/base_switches.h" +#include "base/bind.h" +#include "base/command_line.h" +#include "base/debug/debugger.h" +#include "base/files/file_util.h" +#include "base/synchronization/waitable_event.h" +#include "chrome/browser/printing/print_job_manager.h" +#include "content/public/app/content_main.h" +#include "content/public/app/content_main_runner.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_types.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/common/content_switches.h" +#include "ui/base/ui_base_switches.h" + +#if defined(OS_WIN) +#include "content/public/app/startup_helper_win.h" +#include "sandbox/win/src/sandbox_types.h" +#endif + +namespace { + +CefContext* g_context = NULL; + +// Force shutdown when the process terminates if a context currently exists and +// CefShutdown() has not been explicitly called. +class CefForceShutdown { + public: + ~CefForceShutdown() { + if (g_context) { + g_context->Shutdown(); + delete g_context; + g_context = NULL; + } + } +} g_force_shutdown; + +} // namespace + +int CefExecuteProcess(const CefMainArgs& args, + CefRefPtr application, + void* windows_sandbox_info) { + base::CommandLine command_line(base::CommandLine::NO_PROGRAM); +#if defined(OS_WIN) + command_line.ParseFromString(::GetCommandLineW()); +#else + command_line.InitFromArgv(args.argc, args.argv); +#endif + + // Wait for the debugger as early in process initialization as possible. + if (command_line.HasSwitch(switches::kWaitForDebugger)) + base::debug::WaitForDebugger(60, true); + + // If no process type is specified then it represents the browser process and + // we do nothing. + std::string process_type = + command_line.GetSwitchValueASCII(switches::kProcessType); + if (process_type.empty()) + return -1; + + CefMainDelegate main_delegate(application); + + // Execute the secondary process. +#if defined(OS_WIN) + sandbox::SandboxInterfaceInfo sandbox_info = {0}; + if (windows_sandbox_info == NULL) { + content::InitializeSandboxInfo(&sandbox_info); + windows_sandbox_info = &sandbox_info; + } + + content::ContentMainParams params(&main_delegate); + params.instance = args.instance; + params.sandbox_info = + static_cast(windows_sandbox_info); + + return content::ContentMain(params); +#else + content::ContentMainParams params(&main_delegate); + params.argc = args.argc; + params.argv = const_cast(args.argv); + + return content::ContentMain(params); +#endif +} + +bool CefInitialize(const CefMainArgs& args, + const CefSettings& settings, + CefRefPtr application, + void* windows_sandbox_info) { + // Return true if the global context already exists. + if (g_context) + return true; + + if (settings.size != sizeof(cef_settings_t)) { + NOTREACHED() << "invalid CefSettings structure size"; + return false; + } + + g_browser_process = new ChromeBrowserProcessStub(); + + // Create the new global context object. + g_context = new CefContext(); + + // Initialize the global context. + return g_context->Initialize(args, settings, application, + windows_sandbox_info); +} + +void CefShutdown() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + // Must always be called on the same thread as Initialize. + if (!g_context->OnInitThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + // Shut down the global context. This will block until shutdown is complete. + g_context->Shutdown(); + + // Delete the global context object. + delete g_context; + g_context = NULL; +} + +void CefDoMessageLoopWork() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + // Must always be called on the same thread as Initialize. + if (!g_context->OnInitThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + CefBrowserMessageLoop::current()->DoMessageLoopIteration(); +} + +void CefRunMessageLoop() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + // Must always be called on the same thread as Initialize. + if (!g_context->OnInitThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + CefBrowserMessageLoop::current()->RunMessageLoop(); +} + +void CefQuitMessageLoop() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + // Must always be called on the same thread as Initialize. + if (!g_context->OnInitThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + CefBrowserMessageLoop::current()->Quit(); +} + +void CefSetOSModalLoop(bool osModalLoop) { +#if defined(OS_WIN) + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (CEF_CURRENTLY_ON_UIT()) + base::MessageLoop::current()->set_os_modal_loop(osModalLoop); + else + CEF_POST_TASK(CEF_UIT, base::Bind(CefSetOSModalLoop, osModalLoop)); +#endif // defined(OS_WIN) +} + + +// CefContext + +CefContext::CefContext() + : initialized_(false), + shutting_down_(false), + init_thread_id_(0) { +} + +CefContext::~CefContext() { +} + +// static +CefContext* CefContext::Get() { + return g_context; +} + +bool CefContext::Initialize(const CefMainArgs& args, + const CefSettings& settings, + CefRefPtr application, + void* windows_sandbox_info) { + init_thread_id_ = base::PlatformThread::CurrentId(); + settings_ = settings; + + cache_path_ = base::FilePath(CefString(&settings.cache_path)); + if (!cache_path_.empty() && + !base::DirectoryExists(cache_path_) && + !base::CreateDirectory(cache_path_)) { + NOTREACHED() << "The cache_path directory could not be created"; + cache_path_ = base::FilePath(); + } + if (cache_path_.empty()) { + // Create and use a temporary directory. + if (cache_temp_dir_.CreateUniqueTempDir()) { + cache_path_ = cache_temp_dir_.path(); + } else { + NOTREACHED() << "Failed to create temporary cache_path directory"; + } + } + +#if !defined(OS_WIN) + if (settings.multi_threaded_message_loop) { + NOTIMPLEMENTED() << "multi_threaded_message_loop is not supported."; + return false; + } +#endif + + main_delegate_.reset(new CefMainDelegate(application)); + main_runner_.reset(content::ContentMainRunner::Create()); + + int exit_code; + + // Initialize the content runner. +#if defined(OS_WIN) + sandbox::SandboxInterfaceInfo sandbox_info = {0}; + if (windows_sandbox_info == NULL) { + content::InitializeSandboxInfo(&sandbox_info); + windows_sandbox_info = &sandbox_info; + settings_.no_sandbox = true; + } + + content::ContentMainParams params(main_delegate_.get()); + params.instance = args.instance; + params.sandbox_info = + static_cast(windows_sandbox_info); + + exit_code = main_runner_->Initialize(params); +#else + content::ContentMainParams params(main_delegate_.get()); + params.argc = args.argc; + params.argv = const_cast(args.argv); + + exit_code = main_runner_->Initialize(params); +#endif + + DCHECK_LT(exit_code, 0); + if (exit_code >= 0) + return false; + + // Run the process. Results in a call to CefMainDelegate::RunProcess() which + // will create the browser runner and message loop without blocking. + exit_code = main_runner_->Run(); + + initialized_ = true; + + if (CEF_CURRENTLY_ON_UIT()) { + OnContextInitialized(); + } else { + // Continue initialization on the UI thread. + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefContext::OnContextInitialized, base::Unretained(this))); + } + + return true; +} + +void CefContext::Shutdown() { + // Must always be called on the same thread as Initialize. + DCHECK(OnInitThread()); + + shutting_down_ = true; + + if (settings_.multi_threaded_message_loop) { + // Events that will be used to signal when shutdown is complete. Start in + // non-signaled mode so that the event will block. + base::WaitableEvent uithread_shutdown_event(false, false); + + // Finish shutdown on the UI thread. + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefContext::FinishShutdownOnUIThread, + base::Unretained(this), + &uithread_shutdown_event)); + + /// Block until UI thread shutdown is complete. + uithread_shutdown_event.Wait(); + + FinalizeShutdown(); + } else { + // Finish shutdown on the current thread, which should be the UI thread. + FinishShutdownOnUIThread(NULL); + + FinalizeShutdown(); + } +} + +bool CefContext::OnInitThread() { + return (base::PlatformThread::CurrentId() == init_thread_id_); +} + +CefTraceSubscriber* CefContext::GetTraceSubscriber() { + CEF_REQUIRE_UIT(); + if (shutting_down_) + return NULL; + if (!trace_subscriber_.get()) + trace_subscriber_.reset(new CefTraceSubscriber()); + return trace_subscriber_.get(); +} + +void CefContext::OnContextInitialized() { + CEF_REQUIRE_UIT(); + + // Register internal scheme handlers. + scheme::RegisterInternalHandlers(); + + // Register for notifications. + registrar_.reset(new content::NotificationRegistrar()); + registrar_->Add(this, content::NOTIFICATION_RENDERER_PROCESS_TERMINATED, + content::NotificationService::AllBrowserContextsAndSources()); + registrar_->Add(this, content::NOTIFICATION_RENDERER_PROCESS_CLOSED, + content::NotificationService::AllBrowserContextsAndSources()); + + // Must be created after the NotificationService. + print_job_manager_.reset(new printing::PrintJobManager()); + + // Notify the handler. + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetBrowserProcessHandler(); + if (handler.get()) + handler->OnContextInitialized(); + } +} + +void CefContext::FinishShutdownOnUIThread( + base::WaitableEvent* uithread_shutdown_event) { + CEF_REQUIRE_UIT(); + + // Wait for the pending print jobs to finish. Don't do this later, since + // this might cause a nested message loop to run, and we don't want pending + // tasks to run once teardown has started. + print_job_manager_->Shutdown(); + print_job_manager_.reset(NULL); + + CefContentBrowserClient::Get()->DestroyAllBrowsers(); + + registrar_.reset(); + + if (trace_subscriber_.get()) + trace_subscriber_.reset(NULL); + + if (uithread_shutdown_event) + uithread_shutdown_event->Signal(); +} + +void CefContext::FinalizeShutdown() { + if (content::RenderProcessHost::run_renderer_in_process()) { + // Blocks until RenderProcess cleanup is complete. + CefContentRendererClient::Get()->RunSingleProcessCleanup(); + } + + // Shut down the browser runner or UI thread. + main_delegate_->ShutdownBrowser(); + + // Shut down the content runner. + main_runner_->Shutdown(); + + main_runner_.reset(NULL); + main_delegate_.reset(NULL); +} + +void CefContext::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + DCHECK(type == content::NOTIFICATION_RENDERER_PROCESS_TERMINATED || + type == content::NOTIFICATION_RENDERER_PROCESS_CLOSED); + content::RenderProcessHost* rph = + content::Source(source).ptr(); + DCHECK(rph); + CefContentBrowserClient::Get()->RemoveBrowserContextReference( + static_cast(rph->GetBrowserContext())); +} diff --git a/libcef/browser/context.h b/libcef/browser/context.h new file mode 100644 index 000000000..e47dd6169 --- /dev/null +++ b/libcef/browser/context.h @@ -0,0 +1,115 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_CONTEXT_H_ +#define CEF_LIBCEF_BROWSER_CONTEXT_H_ +#pragma once + +#include +#include +#include + +#include "include/cef_app.h" + +#include "base/files/file_path.h" +#include "base/files/scoped_temp_dir.h" +#include "base/memory/scoped_ptr.h" +#include "base/threading/platform_thread.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" + +namespace base { +class WaitableEvent; +} + +namespace content { +class ContentMainRunner; +} + +namespace printing { +class PrintJobManager; +} + +class CefBrowserHostImpl; +class CefMainDelegate; +class CefTraceSubscriber; + +class CefContext : public content::NotificationObserver { + public: + typedef std::list > BrowserList; + + CefContext(); + ~CefContext() override; + + // Returns the singleton CefContext instance. + static CefContext* Get(); + + // These methods will be called on the main application thread. + bool Initialize(const CefMainArgs& args, + const CefSettings& settings, + CefRefPtr application, + void* windows_sandbox_info); + void Shutdown(); + + // Returns true if the current thread is the initialization thread. + bool OnInitThread(); + + // Returns true if the context is initialized. + bool initialized() { return initialized_; } + + // Returns true if the context is shutting down. + bool shutting_down() { return shutting_down_; } + + // Retrieve the path at which cache data will be stored on disk. + const base::FilePath& cache_path() const { return cache_path_; } + + const CefSettings& settings() const { return settings_; } + + printing::PrintJobManager* print_job_manager() const { + return print_job_manager_.get(); + } + + CefTraceSubscriber* GetTraceSubscriber(); + + private: + void OnContextInitialized(); + + // Performs shutdown actions that need to occur on the UI thread before any + // threads are destroyed. + void FinishShutdownOnUIThread(base::WaitableEvent* uithread_shutdown_event); + + // Destroys the main runner and related objects. + void FinalizeShutdown(); + + // NotificationObserver implementation. + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; + + // Track context state. + bool initialized_; + bool shutting_down_; + + // The thread on which the context was initialized. + base::PlatformThreadId init_thread_id_; + + CefSettings settings_; + base::FilePath cache_path_; + base::ScopedTempDir cache_temp_dir_; + + scoped_ptr main_delegate_; + scoped_ptr main_runner_; + scoped_ptr trace_subscriber_; + + // Only accessed on the UI Thread. + scoped_ptr registrar_; + scoped_ptr print_job_manager_; +}; + +// Helper macro that returns true if the global context is in a valid state. +#define CONTEXT_STATE_VALID() \ + (CefContext::Get() && CefContext::Get()->initialized() && \ + !CefContext::Get()->shutting_down()) + +#endif // CEF_LIBCEF_BROWSER_CONTEXT_H_ diff --git a/libcef/browser/context_menu_params_impl.cc b/libcef/browser/context_menu_params_impl.cc new file mode 100644 index 000000000..57f8cf2ef --- /dev/null +++ b/libcef/browser/context_menu_params_impl.cc @@ -0,0 +1,140 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/context_menu_params_impl.h" + +#include "base/logging.h" + +CefContextMenuParamsImpl::CefContextMenuParamsImpl( + content::ContextMenuParams* value) + : CefValueBase( + value, NULL, kOwnerNoDelete, true, + new CefValueControllerNonThreadSafe()) { + // Indicate that this object owns the controller. + SetOwnsController(); +} + +int CefContextMenuParamsImpl::GetXCoord() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().x; +} + +int CefContextMenuParamsImpl::GetYCoord() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().y; +} + +CefContextMenuParamsImpl::TypeFlags CefContextMenuParamsImpl::GetTypeFlags() { + CEF_VALUE_VERIFY_RETURN(false, CM_TYPEFLAG_NONE); + const content::ContextMenuParams& params = const_value(); + int type_flags = CM_TYPEFLAG_NONE; + if (!params.page_url.is_empty()) + type_flags |= CM_TYPEFLAG_PAGE; + if (!params.frame_url.is_empty()) + type_flags |= CM_TYPEFLAG_FRAME; + if (!params.link_url.is_empty()) + type_flags |= CM_TYPEFLAG_LINK; + if (params.media_type != blink::WebContextMenuData::MediaTypeNone) + type_flags |= CM_TYPEFLAG_MEDIA; + if (!params.selection_text.empty()) + type_flags |= CM_TYPEFLAG_SELECTION; + if (params.is_editable) + type_flags |= CM_TYPEFLAG_EDITABLE; + return static_cast(type_flags); +} + +CefString CefContextMenuParamsImpl::GetLinkUrl() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().link_url.spec(); +} + +CefString CefContextMenuParamsImpl::GetUnfilteredLinkUrl() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().unfiltered_link_url.spec(); +} + +CefString CefContextMenuParamsImpl::GetSourceUrl() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().src_url.spec(); +} + +bool CefContextMenuParamsImpl::HasImageContents() { + CEF_VALUE_VERIFY_RETURN(false, true); + return const_value().has_image_contents; +} + +CefString CefContextMenuParamsImpl::GetPageUrl() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().page_url.spec(); +} + +CefString CefContextMenuParamsImpl::GetFrameUrl() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().frame_url.spec(); +} + +CefString CefContextMenuParamsImpl::GetFrameCharset() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().frame_charset; +} + +CefContextMenuParamsImpl::MediaType CefContextMenuParamsImpl::GetMediaType() { + CEF_VALUE_VERIFY_RETURN(false, CM_MEDIATYPE_NONE); + return static_cast(const_value().media_type); +} + +CefContextMenuParamsImpl::MediaStateFlags + CefContextMenuParamsImpl::GetMediaStateFlags() { + CEF_VALUE_VERIFY_RETURN(false, CM_MEDIAFLAG_NONE); + return static_cast(const_value().media_flags); +} + +CefString CefContextMenuParamsImpl::GetSelectionText() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().selection_text; +} + +CefString CefContextMenuParamsImpl::GetMisspelledWord() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().misspelled_word; +} + +int CefContextMenuParamsImpl::GetMisspellingHash() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().misspelling_hash; +} + +bool CefContextMenuParamsImpl::GetDictionarySuggestions( + std::vector& suggestions) { + CEF_VALUE_VERIFY_RETURN(false, false); + + if (!suggestions.empty()) + suggestions.clear(); + + if(const_value().dictionary_suggestions.empty()) + return false; + + std::vector::const_iterator it = + const_value().dictionary_suggestions.begin(); + for (; it != const_value().dictionary_suggestions.end(); ++it) + suggestions.push_back(*it); + + return true; +} + +bool CefContextMenuParamsImpl::IsEditable() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().is_editable; +} + +bool CefContextMenuParamsImpl::IsSpellCheckEnabled() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().spellcheck_enabled; +} + +CefContextMenuParamsImpl::EditStateFlags + CefContextMenuParamsImpl::GetEditStateFlags() { + CEF_VALUE_VERIFY_RETURN(false, CM_EDITFLAG_NONE); + return static_cast(const_value().edit_flags); +} diff --git a/libcef/browser/context_menu_params_impl.h b/libcef/browser/context_menu_params_impl.h new file mode 100644 index 000000000..c4da125ca --- /dev/null +++ b/libcef/browser/context_menu_params_impl.h @@ -0,0 +1,45 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_CONTEXT_MENU_PARAMS_IMPL_H_ +#define CEF_LIBCEF_BROWSER_CONTEXT_MENU_PARAMS_IMPL_H_ +#pragma once + +#include "include/cef_context_menu_handler.h" +#include "libcef/common/value_base.h" + +#include "content/public/common/context_menu_params.h" + +// CefContextMenuParams implementation. This class is not thread safe. +class CefContextMenuParamsImpl + : public CefValueBase { + public: + explicit CefContextMenuParamsImpl(content::ContextMenuParams* value); + + // CefContextMenuParams methods. + int GetXCoord() override; + int GetYCoord() override; + TypeFlags GetTypeFlags() override; + CefString GetLinkUrl() override; + CefString GetUnfilteredLinkUrl() override; + CefString GetSourceUrl() override; + bool HasImageContents() override; + CefString GetPageUrl() override; + CefString GetFrameUrl() override; + CefString GetFrameCharset() override; + MediaType GetMediaType() override; + MediaStateFlags GetMediaStateFlags() override; + CefString GetSelectionText() override; + CefString GetMisspelledWord() override; + int GetMisspellingHash() override; + bool GetDictionarySuggestions( + std::vector& suggestions) override; + bool IsEditable() override; + bool IsSpellCheckEnabled() override; + EditStateFlags GetEditStateFlags() override; + + DISALLOW_COPY_AND_ASSIGN(CefContextMenuParamsImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_CONTEXT_MENU_PARAMS_IMPL_H_ diff --git a/libcef/browser/cookie_manager_impl.cc b/libcef/browser/cookie_manager_impl.cc new file mode 100644 index 000000000..d580a0272 --- /dev/null +++ b/libcef/browser/cookie_manager_impl.cc @@ -0,0 +1,453 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/cookie_manager_impl.h" + +#include +#include +#include + +#include "libcef/browser/browser_context.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_context_getter.h" +#include "libcef/common/time_util.h" + +#include "base/bind.h" +#include "base/files/file_util.h" +#include "base/format_macros.h" +#include "base/logging.h" +#include "base/threading/thread_restrictions.h" +#include "content/browser/net/sqlite_persistent_cookie_store.h" +#include "content/public/browser/cookie_crypto_delegate.h" +#include "net/cookies/cookie_util.h" +#include "net/cookies/parsed_cookie.h" +#include "net/url_request/url_request_context.h" +#include "url/gurl.h" + +using content::BrowserThread; + +namespace { + +// Callback class for visiting cookies. +class VisitCookiesCallback : public base::RefCounted { + public: + explicit VisitCookiesCallback(net::CookieMonster* cookie_monster, + CefRefPtr visitor) + : cookie_monster_(cookie_monster), + visitor_(visitor) { + } + + void Run(const net::CookieList& list) { + CEF_REQUIRE_IOT(); + + int total = list.size(), count = 0; + + net::CookieList::const_iterator it = list.begin(); + for (; it != list.end(); ++it, ++count) { + CefCookie cookie; + const net::CanonicalCookie& cc = *(it); + CefCookieManagerImpl::GetCefCookie(cc, cookie); + + bool deleteCookie = false; + bool keepLooping = visitor_->Visit(cookie, count, total, deleteCookie); + if (deleteCookie) { + cookie_monster_->DeleteCanonicalCookieAsync(cc, + net::CookieMonster::DeleteCookieCallback()); + } + if (!keepLooping) + break; + } + } + + private: + friend class base::RefCounted; + + ~VisitCookiesCallback() {} + + scoped_refptr cookie_monster_; + CefRefPtr visitor_; +}; + + +// Methods extracted from net/cookies/cookie_monster.cc + +// Determine the cookie domain to use for setting the specified cookie. +bool GetCookieDomain(const GURL& url, + const net::ParsedCookie& pc, + std::string* result) { + std::string domain_string; + if (pc.HasDomain()) + domain_string = pc.Domain(); + return net::cookie_util::GetCookieDomainWithString(url, domain_string, + result); +} + +void RunCompletionOnIOThread(CefRefPtr callback) { + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefCompletionCallback::OnComplete, callback.get())); +} + +} // namespace + + +CefCookieManagerImpl::CefCookieManagerImpl(bool is_global) + : is_global_(is_global) { +} + +CefCookieManagerImpl::~CefCookieManagerImpl() { +} + +void CefCookieManagerImpl::Initialize( + const CefString& path, + bool persist_session_cookies) { + if (is_global_) + SetGlobal(); + else + SetStoragePath(path, persist_session_cookies); +} + +void CefCookieManagerImpl::SetSupportedSchemes( + const std::vector& schemes) { + if (CEF_CURRENTLY_ON_IOT()) { + if (!cookie_monster_.get()) + return; + + if (is_global_) { + // Global changes are handled by the request context. + scoped_refptr getter = + static_cast( + CefContentBrowserClient::Get()->request_context().get()); + + std::vector scheme_vec; + std::vector::const_iterator it = schemes.begin(); + for (; it != schemes.end(); ++it) + scheme_vec.push_back(it->ToString()); + + getter->SetCookieSupportedSchemes(scheme_vec); + return; + } + + supported_schemes_ = schemes; + + if (supported_schemes_.empty()) { + supported_schemes_.push_back("http"); + supported_schemes_.push_back("https"); + } + + std::set scheme_set; + std::vector::const_iterator it = supported_schemes_.begin(); + for (; it != supported_schemes_.end(); ++it) + scheme_set.insert(*it); + + const char** arr = new const char*[scheme_set.size()]; + std::set::const_iterator it2 = scheme_set.begin(); + for (int i = 0; it2 != scheme_set.end(); ++it2, ++i) + arr[i] = it2->c_str(); + + cookie_monster_->SetCookieableSchemes(arr, scheme_set.size()); + + delete [] arr; + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefCookieManagerImpl::SetSupportedSchemes, + this, schemes)); + } +} + +bool CefCookieManagerImpl::VisitAllCookies( + CefRefPtr visitor) { + if (CEF_CURRENTLY_ON_IOT()) { + if (!cookie_monster_.get()) + return false; + + scoped_refptr callback( + new VisitCookiesCallback(cookie_monster_.get(), visitor)); + + cookie_monster_->GetAllCookiesAsync( + base::Bind(&VisitCookiesCallback::Run, callback.get())); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitAllCookies), + this, visitor)); + } + + return true; +} + +bool CefCookieManagerImpl::VisitUrlCookies( + const CefString& url, bool includeHttpOnly, + CefRefPtr visitor) { + if (CEF_CURRENTLY_ON_IOT()) { + if (!cookie_monster_.get()) + return false; + + net::CookieOptions options; + if (includeHttpOnly) + options.set_include_httponly(); + + scoped_refptr callback( + new VisitCookiesCallback(cookie_monster_.get(), visitor)); + + GURL gurl = GURL(url.ToString()); + cookie_monster_->GetAllCookiesForURLWithOptionsAsync(gurl, options, + base::Bind(&VisitCookiesCallback::Run, callback.get())); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitUrlCookies), + this, url, includeHttpOnly, visitor)); + } + + return true; +} + +bool CefCookieManagerImpl::SetCookie(const CefString& url, + const CefCookie& cookie) { + CEF_REQUIRE_IOT_RETURN(false); + + if (!cookie_monster_.get()) + return false; + + GURL gurl = GURL(url.ToString()); + if (!gurl.is_valid()) + return false; + + std::string name = CefString(&cookie.name).ToString(); + std::string value = CefString(&cookie.value).ToString(); + std::string domain = CefString(&cookie.domain).ToString(); + std::string path = CefString(&cookie.path).ToString(); + + base::Time expiration_time; + if (cookie.has_expires) + cef_time_to_basetime(cookie.expires, expiration_time); + + cookie_monster_->SetCookieWithDetailsAsync( + gurl, name, value, domain, path, + expiration_time, + cookie.secure ? true : false, + cookie.httponly ? true : false, + net::COOKIE_PRIORITY_DEFAULT, + net::CookieStore::SetCookiesCallback()); + return true; +} + +bool CefCookieManagerImpl::DeleteCookies(const CefString& url, + const CefString& cookie_name) { + CEF_REQUIRE_IOT_RETURN(false); + + if (!cookie_monster_.get()) + return false; + + if (url.empty()) { + // Delete all cookies. + cookie_monster_->DeleteAllAsync(net::CookieMonster::DeleteCallback()); + return true; + } + + GURL gurl = GURL(url.ToString()); + if (!gurl.is_valid()) + return false; + + if (cookie_name.empty()) { + // Delete all matching host cookies. + cookie_monster_->DeleteAllForHostAsync(gurl, + net::CookieMonster::DeleteCallback()); + } else { + // Delete all matching host and domain cookies. + cookie_monster_->DeleteCookieAsync(gurl, cookie_name, base::Closure()); + } + return true; +} + +bool CefCookieManagerImpl::SetStoragePath( + const CefString& path, + bool persist_session_cookies) { + if (CEF_CURRENTLY_ON_IOT()) { + base::FilePath new_path; + if (!path.empty()) + new_path = base::FilePath(path); + + if (is_global_) { + // Global path changes are handled by the request context. + scoped_refptr getter = + static_cast( + CefContentBrowserClient::Get()->request_context().get()); + getter->SetCookieStoragePath(new_path, persist_session_cookies); + cookie_monster_ = getter->GetURLRequestContext()->cookie_store()-> + GetCookieMonster(); + return true; + } + + if (cookie_monster_.get() && ((storage_path_.empty() && path.empty()) || + storage_path_ == new_path)) { + // The path has not changed so don't do anything. + return true; + } + + scoped_refptr persistent_store; + if (!new_path.empty()) { + // TODO(cef): Move directory creation to the blocking pool instead of + // allowing file IO on this thread. + base::ThreadRestrictions::ScopedAllowIO allow_io; + if (base::DirectoryExists(new_path) || + base::CreateDirectory(new_path)) { + const base::FilePath& cookie_path = new_path.AppendASCII("Cookies"); + persistent_store = + new content::SQLitePersistentCookieStore( + cookie_path, + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB), + persist_session_cookies, + NULL, + NULL); + } else { + NOTREACHED() << "The cookie storage directory could not be created"; + storage_path_.clear(); + } + } + + // Set the new cookie store that will be used for all new requests. The old + // cookie store, if any, will be automatically flushed and closed when no + // longer referenced. + cookie_monster_ = new net::CookieMonster(persistent_store.get(), NULL); + if (persistent_store.get() && persist_session_cookies) + cookie_monster_->SetPersistSessionCookies(true); + storage_path_ = new_path; + + // Restore the previously supported schemes. + SetSupportedSchemes(supported_schemes_); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::SetStoragePath), + this, path, persist_session_cookies)); + } + + return true; +} + +bool CefCookieManagerImpl::FlushStore( + CefRefPtr callback) { + if (CEF_CURRENTLY_ON_IOT()) { + if (!cookie_monster_.get()) { + if (callback.get()) + RunCompletionOnIOThread(callback); + return true; + } + + base::Closure flush_callback; + if (callback.get()) + flush_callback = base::Bind(RunCompletionOnIOThread, callback); + else + flush_callback = base::Bind(&base::DoNothing); + + cookie_monster_->FlushStore(flush_callback); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::FlushStore), + this, callback)); + } + + return true; +} + +void CefCookieManagerImpl::SetGlobal() { + if (CEF_CURRENTLY_ON_IOT()) { + if (CefContentBrowserClient::Get()->request_context().get()) { + cookie_monster_ = CefContentBrowserClient::Get()->request_context()-> + GetURLRequestContext()->cookie_store()->GetCookieMonster(); + DCHECK(cookie_monster_.get()); + } + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, base::Bind(&CefCookieManagerImpl::SetGlobal, this)); + } +} + +// static +bool CefCookieManagerImpl::GetCefCookie(const net::CanonicalCookie& cc, + CefCookie& cookie) { + CefString(&cookie.name).FromString(cc.Name()); + CefString(&cookie.value).FromString(cc.Value()); + CefString(&cookie.domain).FromString(cc.Domain()); + CefString(&cookie.path).FromString(cc.Path()); + cookie.secure = cc.IsSecure(); + cookie.httponly = cc.IsHttpOnly(); + cef_time_from_basetime(cc.CreationDate(), cookie.creation); + cef_time_from_basetime(cc.LastAccessDate(), cookie.last_access); + cookie.has_expires = cc.IsPersistent(); + if (cookie.has_expires) + cef_time_from_basetime(cc.ExpiryDate(), cookie.expires); + + return true; +} + +// static +bool CefCookieManagerImpl::GetCefCookie(const GURL& url, + const std::string& cookie_line, + CefCookie& cookie) { + // Parse the cookie. + net::ParsedCookie pc(cookie_line); + if (!pc.IsValid()) + return false; + + std::string cookie_domain; + if (!GetCookieDomain(url, pc, &cookie_domain)) + return false; + + std::string cookie_path = net::CanonicalCookie::CanonPath(url, pc); + base::Time creation_time = base::Time::Now(); + base::Time cookie_expires = + net::CanonicalCookie::CanonExpiration(pc, creation_time, creation_time); + + CefString(&cookie.name).FromString(pc.Name()); + CefString(&cookie.value).FromString(pc.Value()); + CefString(&cookie.domain).FromString(cookie_domain); + CefString(&cookie.path).FromString(cookie_path); + cookie.secure = pc.IsSecure(); + cookie.httponly = pc.IsHttpOnly(); + cef_time_from_basetime(creation_time, cookie.creation); + cef_time_from_basetime(creation_time, cookie.last_access); + cookie.has_expires = !cookie_expires.is_null(); + if (cookie.has_expires) + cef_time_from_basetime(cookie_expires, cookie.expires); + + return true; +} + + +// CefCookieManager methods ---------------------------------------------------- + +// static +CefRefPtr CefCookieManager::GetGlobalManager() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return NULL; + } + + CefRefPtr manager(new CefCookieManagerImpl(true)); + manager->Initialize(CefString(), false); + return manager.get(); +} + +// static +CefRefPtr CefCookieManager::CreateManager( + const CefString& path, + bool persist_session_cookies) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return NULL; + } + + CefRefPtr manager(new CefCookieManagerImpl(false)); + manager->Initialize(path, persist_session_cookies); + return manager.get(); +} diff --git a/libcef/browser/cookie_manager_impl.h b/libcef/browser/cookie_manager_impl.h new file mode 100644 index 000000000..4c9a3d118 --- /dev/null +++ b/libcef/browser/cookie_manager_impl.h @@ -0,0 +1,52 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_COOKIE_MANAGER_IMPL_H_ +#define CEF_LIBCEF_BROWSER_COOKIE_MANAGER_IMPL_H_ + +#include "include/cef_cookie.h" +#include "base/files/file_path.h" +#include "net/cookies/cookie_monster.h" + +// Implementation of the CefCookieManager interface. +class CefCookieManagerImpl : public CefCookieManager { + public: + CefCookieManagerImpl(bool is_global); + ~CefCookieManagerImpl() override; + + // Initialize the cookie manager. + void Initialize(const CefString& path, + bool persist_session_cookies); + + // CefCookieManager methods. + void SetSupportedSchemes(const std::vector& schemes) override; + bool VisitAllCookies(CefRefPtr visitor) override; + bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, + CefRefPtr visitor) override; + bool SetCookie(const CefString& url, + const CefCookie& cookie) override; + bool DeleteCookies(const CefString& url, + const CefString& cookie_name) override; + bool SetStoragePath(const CefString& path, + bool persist_session_cookies) override; + bool FlushStore(CefRefPtr callback) override; + + net::CookieMonster* cookie_monster() { return cookie_monster_.get(); } + + static bool GetCefCookie(const net::CanonicalCookie& cc, CefCookie& cookie); + static bool GetCefCookie(const GURL& url, const std::string& cookie_line, + CefCookie& cookie); + + private: + void SetGlobal(); + + scoped_refptr cookie_monster_; + bool is_global_; + base::FilePath storage_path_; + std::vector supported_schemes_; + + IMPLEMENT_REFCOUNTING(CefCookieManagerImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_COOKIE_MANAGER_IMPL_H_ diff --git a/libcef/browser/devtools_delegate.cc b/libcef/browser/devtools_delegate.cc new file mode 100644 index 000000000..89b635e5c --- /dev/null +++ b/libcef/browser/devtools_delegate.cc @@ -0,0 +1,204 @@ +// Copyright 2013 the Chromium Embedded Framework Authors. Portions Copyright +// 2012 The Chromium Authors. All rights reserved. Use of this source code is +// governed by a BSD-style license that can be found in the LICENSE file. + +#include "libcef/browser/devtools_delegate.h" +#include "libcef/browser/devtools_scheme_handler.h" +#include "libcef/common/content_client.h" + +#include +#include + +#include "base/command_line.h" +#include "base/md5.h" +#include "base/rand_util.h" +#include "base/strings/stringprintf.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/public/browser/devtools_agent_host.h" +#include "base/time/time.h" +#include "content/public/browser/devtools_http_handler.h" +#include "content/public/browser/devtools_target.h" +#include "content/public/browser/favicon_status.h" +#include "content/public/browser/navigation_entry.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host_iterator.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_contents_delegate.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/url_constants.h" +#include "grit/cef_resources.h" +#include "net/socket/tcp_server_socket.h" +#include "ui/base/layout.h" +#include "ui/base/resource/resource_bundle.h" + +namespace { + +const char kTargetTypePage[] = "page"; +const char kTargetTypeServiceWorker[] = "service_worker"; +const char kTargetTypeOther[] = "other"; + +class TCPServerSocketFactory + : public content::DevToolsHttpHandler::ServerSocketFactory { + public: + TCPServerSocketFactory(const std::string& address, uint16 port, int backlog) + : content::DevToolsHttpHandler::ServerSocketFactory( + address, port, backlog) {} + + private: + // content::DevToolsHttpHandler::ServerSocketFactory. + scoped_ptr Create() const override { + return scoped_ptr( + new net::TCPServerSocket(NULL, net::NetLog::Source())); + } + + DISALLOW_COPY_AND_ASSIGN(TCPServerSocketFactory); +}; + +scoped_ptr + CreateSocketFactory(uint16 port) { + return scoped_ptr( + new TCPServerSocketFactory("127.0.0.1", port, 1)); +} + +class Target : public content::DevToolsTarget { + public: + explicit Target(scoped_refptr agent_host); + + std::string GetId() const override { return agent_host_->GetId(); } + std::string GetParentId() const override { return std::string(); } + std::string GetType() const override { + switch (agent_host_->GetType()) { + case content::DevToolsAgentHost::TYPE_WEB_CONTENTS: + return kTargetTypePage; + case content::DevToolsAgentHost::TYPE_SERVICE_WORKER: + return kTargetTypeServiceWorker; + default: + break; + } + return kTargetTypeOther; + } + std::string GetTitle() const override { + return agent_host_->GetTitle(); + } + std::string GetDescription() const override { return std::string(); } + GURL GetURL() const override { return agent_host_->GetURL(); } + GURL GetFaviconURL() const override { return favicon_url_; } + base::TimeTicks GetLastActivityTime() const override { + return last_activity_time_; + } + bool IsAttached() const override { + return agent_host_->IsAttached(); + } + scoped_refptr GetAgentHost() const + override { + return agent_host_; + } + bool Activate() const override; + bool Close() const override; + + private: + scoped_refptr agent_host_; + GURL favicon_url_; + base::TimeTicks last_activity_time_; +}; + +Target::Target(scoped_refptr agent_host) + : agent_host_(agent_host) { + if (content::WebContents* web_contents = agent_host_->GetWebContents()) { + content::NavigationController& controller = web_contents->GetController(); + content::NavigationEntry* entry = controller.GetActiveEntry(); + if (entry != NULL && entry->GetURL().is_valid()) + favicon_url_ = entry->GetFavicon().url; + last_activity_time_ = web_contents->GetLastActiveTime(); + } +} + +bool Target::Activate() const { + return agent_host_->Activate(); +} + +bool Target::Close() const { + return agent_host_->Close(); +} + +} // namespace + +// CefDevToolsDelegate + +CefDevToolsDelegate::CefDevToolsDelegate(uint16 port) { + devtools_http_handler_.reset(content::DevToolsHttpHandler::Start( + CreateSocketFactory(port), + std::string(), + this, + base::FilePath())); +} + +CefDevToolsDelegate::~CefDevToolsDelegate() { + DCHECK(!devtools_http_handler_.get()); +} + +void CefDevToolsDelegate::Stop() { + // The call below deletes |this|. + devtools_http_handler_.reset(); +} + +std::string CefDevToolsDelegate::GetDiscoveryPageHTML() { + return CefContentClient::Get()->GetDataResource( + IDR_CEF_DEVTOOLS_DISCOVERY_PAGE, ui::SCALE_FACTOR_NONE).as_string(); +} + +bool CefDevToolsDelegate::BundlesFrontendResources() { + return true; +} + +base::FilePath CefDevToolsDelegate::GetDebugFrontendDir() { + return base::FilePath(); +} + +scoped_ptr + CefDevToolsDelegate::CreateSocketForTethering(std::string* name) { + return scoped_ptr(); +} + +std::string CefDevToolsDelegate::GetChromeDevToolsURL() { + return base::StringPrintf("%s://%s/devtools.html", + content::kChromeDevToolsScheme, scheme::kChromeDevToolsHost); +} + +// CefDevToolsManagerDelegate + +CefDevToolsManagerDelegate::CefDevToolsManagerDelegate( + content::BrowserContext* browser_context) + : browser_context_(browser_context) { +} + +CefDevToolsManagerDelegate::~CefDevToolsManagerDelegate() { +} + +base::DictionaryValue* CefDevToolsManagerDelegate::HandleCommand( + content::DevToolsAgentHost* agent_host, + base::DictionaryValue* command) { + return NULL; +} + +std::string CefDevToolsManagerDelegate::GetPageThumbnailData( + const GURL& url) { + return std::string(); +} + +scoped_ptr +CefDevToolsManagerDelegate::CreateNewTarget(const GURL& url) { + return scoped_ptr(); +} + +void CefDevToolsManagerDelegate::EnumerateTargets(TargetCallback callback) { + TargetList targets; + content::DevToolsAgentHost::List agents = + content::DevToolsAgentHost::GetOrCreateAll(); + for (content::DevToolsAgentHost::List::iterator it = agents.begin(); + it != agents.end(); ++it) { + targets.push_back(new Target(*it)); + } + callback.Run(targets); +} diff --git a/libcef/browser/devtools_delegate.h b/libcef/browser/devtools_delegate.h new file mode 100644 index 000000000..5981421e4 --- /dev/null +++ b/libcef/browser/devtools_delegate.h @@ -0,0 +1,73 @@ +// Copyright 2013 the Chromium Embedded Framework Authors. Portions Copyright +// 2012 The Chromium Authors. All rights reserved. Use of this source code is +// governed by a BSD-style license that can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_DEVTOOLS_DELEGATE_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_DELEGATE_H_ +#pragma once + +#include +#include + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" +#include "content/public/browser/devtools_agent_host.h" +#include "content/public/browser/devtools_http_handler.h" +#include "content/public/browser/devtools_http_handler_delegate.h" +#include "content/public/browser/devtools_manager_delegate.h" + +namespace content { +class RenderViewHost; +} + +class CefDevToolsDelegate : public content::DevToolsHttpHandlerDelegate { + public: + explicit CefDevToolsDelegate(uint16 port); + ~CefDevToolsDelegate() override; + + // Stops http server. + void Stop(); + + // DevToolsHttpHandlerDelegate overrides. + std::string GetDiscoveryPageHTML() override; + bool BundlesFrontendResources() override; + base::FilePath GetDebugFrontendDir() override; + scoped_ptr CreateSocketForTethering( + std::string* name) override; + + // Returns the chrome-devtools URL. + std::string GetChromeDevToolsURL(); + + private: + scoped_ptr devtools_http_handler_; + + DISALLOW_COPY_AND_ASSIGN(CefDevToolsDelegate); +}; + +class CefDevToolsManagerDelegate : public content::DevToolsManagerDelegate { + public: + explicit CefDevToolsManagerDelegate( + content::BrowserContext* browser_context); + ~CefDevToolsManagerDelegate() override; + + // DevToolsManagerDelegate implementation. + void Inspect(content::BrowserContext* browser_context, + content::DevToolsAgentHost* agent_host) override {} + void DevToolsAgentStateChanged(content::DevToolsAgentHost* agent_host, + bool attached) override {} + base::DictionaryValue* HandleCommand( + content::DevToolsAgentHost* agent_host, + base::DictionaryValue* command) override; + scoped_ptr CreateNewTarget( + const GURL& url) override; + void EnumerateTargets(TargetCallback callback) override; + std::string GetPageThumbnailData(const GURL& url) override; + + private: + content::BrowserContext* browser_context_; + + DISALLOW_COPY_AND_ASSIGN(CefDevToolsManagerDelegate); +}; + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_DELEGATE_H_ diff --git a/libcef/browser/devtools_frontend.cc b/libcef/browser/devtools_frontend.cc new file mode 100644 index 000000000..2c14a5d2d --- /dev/null +++ b/libcef/browser/devtools_frontend.cc @@ -0,0 +1,182 @@ +// Copyright 2013 the Chromium Embedded Framework Authors. Portions Copyright +// 2012 The Chromium Authors. All rights reserved. Use of this source code is +// governed by a BSD-style license that can be found in the LICENSE file. + +#include "libcef/browser/devtools_frontend.h" + +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/devtools_delegate.h" +#include "libcef/browser/request_context_impl.h" +#include "libcef/browser/thread_util.h" + +#include "base/command_line.h" +#include "base/json/json_reader.h" +#include "base/json/json_writer.h" +#include "base/path_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/public/browser/devtools_http_handler.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/content_client.h" +#include "net/base/net_util.h" +#include "third_party/skia/include/core/SkColor.h" + +namespace { + +// This constant should be in sync with +// the constant at devtools_ui_bindings.cc. +const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; + +} // namespace + +// static +CefDevToolsFrontend* CefDevToolsFrontend::Show( + CefRefPtr inspected_browser, + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) { + CefBrowserSettings new_settings = settings; + if (CefColorGetA(new_settings.background_color) == 0) { + // Use white as the default background color for DevTools instead of the + // CefSettings.background_color value. + new_settings.background_color = SK_ColorWHITE; + } + + CefRefPtr frontend_browser = + CefBrowserHostImpl::Create(windowInfo, client, CefString(), + new_settings, + inspected_browser->GetWindowHandle(), true, + inspected_browser->GetRequestContext()); + + scoped_refptr agent_host = + content::DevToolsAgentHost::GetOrCreateFor( + inspected_browser->GetWebContents()); + if (!inspect_element_at.IsEmpty()) + agent_host->InspectElement(inspect_element_at.x, inspect_element_at.y); + + // CefDevToolsFrontend will delete itself when the frontend WebContents is + // destroyed. + CefDevToolsFrontend* devtools_frontend = new CefDevToolsFrontend( + static_cast(frontend_browser.get()), + agent_host.get()); + + // Need to load the URL after creating the DevTools objects. + CefDevToolsDelegate* delegate = + CefContentBrowserClient::Get()->devtools_delegate(); + frontend_browser->GetMainFrame()->LoadURL(delegate->GetChromeDevToolsURL()); + + devtools_frontend->Activate(); + devtools_frontend->Focus(); + + return devtools_frontend; +} + +void CefDevToolsFrontend::Activate() { + frontend_browser_->ActivateContents(web_contents()); +} + +void CefDevToolsFrontend::Focus() { + web_contents()->Focus(); +} + +void CefDevToolsFrontend::Close() { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBrowserHostImpl::CloseBrowser, frontend_browser_.get(), + true)); +} + +CefDevToolsFrontend::CefDevToolsFrontend( + CefRefPtr frontend_browser, + content::DevToolsAgentHost* agent_host) + : WebContentsObserver(frontend_browser->GetWebContents()), + frontend_browser_(frontend_browser), + agent_host_(agent_host) { +} + +CefDevToolsFrontend::~CefDevToolsFrontend() { +} + +void CefDevToolsFrontend::RenderViewCreated( + content::RenderViewHost* render_view_host) { + if (!frontend_host_) { + frontend_host_.reset( + content::DevToolsFrontendHost::Create( + web_contents()->GetMainFrame(), this)); + agent_host_->AttachClient(this); + } +} + +void CefDevToolsFrontend::WebContentsDestroyed() { + agent_host_->DetachClient(); + delete this; +} + +void CefDevToolsFrontend::HandleMessageFromDevToolsFrontend( + const std::string& message) { + std::string method; + int id = 0; + base::ListValue* params = NULL; + base::DictionaryValue* dict = NULL; + scoped_ptr parsed_message(base::JSONReader::Read(message)); + if (!parsed_message || + !parsed_message->GetAsDictionary(&dict) || + !dict->GetString("method", &method)) { + return; + } + dict->GetList("params", ¶ms); + + std::string browser_message; + if (method == "sendMessageToBrowser" && params && + params->GetSize() == 1 && params->GetString(0, &browser_message)) { + agent_host_->DispatchProtocolMessage(browser_message); + } else if (method == "loadCompleted") { + web_contents()->GetMainFrame()->ExecuteJavaScript( + base::ASCIIToUTF16("DevToolsAPI.setUseSoftMenu(true);")); + } else { + return; + } + + dict->GetInteger("id", &id); + if (id) { + std::string code = "DevToolsAPI.embedderMessageAck(" + + base::IntToString(id) + ",\"\");"; + base::string16 javascript = base::UTF8ToUTF16(code); + web_contents()->GetMainFrame()->ExecuteJavaScript(javascript); + } +} + +void CefDevToolsFrontend::HandleMessageFromDevToolsFrontendToBackend( + const std::string& message) { + agent_host_->DispatchProtocolMessage(message); +} + +void CefDevToolsFrontend::DispatchProtocolMessage( + content::DevToolsAgentHost* agent_host, + const std::string& message) { + if (message.length() < kMaxMessageChunkSize) { + base::string16 javascript = base::UTF8ToUTF16( + "DevToolsAPI.dispatchMessage(" + message + ");"); + web_contents()->GetMainFrame()->ExecuteJavaScript(javascript); + return; + } + + base::FundamentalValue total_size(static_cast(message.length())); + for (size_t pos = 0; pos < message.length(); pos += kMaxMessageChunkSize) { + base::StringValue message_value(message.substr(pos, kMaxMessageChunkSize)); + std::string param; + base::JSONWriter::Write(&message_value, ¶m); + std::string code = "DevToolsAPI.dispatchMessageChunk(" + param + ");"; + base::string16 javascript = base::UTF8ToUTF16(code); + web_contents()->GetMainFrame()->ExecuteJavaScript(javascript); + } +} + +void CefDevToolsFrontend::AgentHostClosed( + content::DevToolsAgentHost* agent_host, + bool replaced) { + DCHECK(agent_host == agent_host_.get()); + Close(); +} diff --git a/libcef/browser/devtools_frontend.h b/libcef/browser/devtools_frontend.h new file mode 100644 index 000000000..2155f3bf9 --- /dev/null +++ b/libcef/browser/devtools_frontend.h @@ -0,0 +1,73 @@ +// Copyright 2013 the Chromium Embedded Framework Authors. Portions Copyright +// 2012 The Chromium Authors. All rights reserved. Use of this source code is +// governed by a BSD-style license that can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_DEVTOOLS_FRONTEND_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_FRONTEND_H_ + +#include "libcef/browser/browser_host_impl.h" + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "content/public/browser/devtools_agent_host.h" +#include "content/public/browser/devtools_frontend_host.h" +#include "content/public/browser/web_contents_observer.h" + +namespace content { +class RenderViewHost; +class WebContents; +} + +class CefDevToolsFrontend : public content::WebContentsObserver, + public content::DevToolsFrontendHost::Delegate, + public content::DevToolsAgentHostClient { + public: + static CefDevToolsFrontend* Show( + CefRefPtr inspected_browser, + const CefWindowInfo& windowInfo, + CefRefPtr client, + const CefBrowserSettings& settings, + const CefPoint& inspect_element_at); + + void Activate(); + void Focus(); + void Close(); + + CefRefPtr frontend_browser() const { + return frontend_browser_; + } + + private: + CefDevToolsFrontend(CefRefPtr frontend_browser, + content::DevToolsAgentHost* agent_host); + ~CefDevToolsFrontend() override; + + // WebContentsObserver overrides. + void RenderViewCreated( + content::RenderViewHost* render_view_host) override; + void WebContentsDestroyed() override; + + // content::DevToolsFrontendHost::Delegate implementation. + void HandleMessageFromDevToolsFrontend( + const std::string& message) override; + void HandleMessageFromDevToolsFrontendToBackend( + const std::string& message) override; + + // content::DevToolsAgentHostClient implementation. + void DispatchProtocolMessage( + content::DevToolsAgentHost* agent_host, + const std::string& message) override; + void AgentHostClosed( + content::DevToolsAgentHost* agent_host, + bool replaced) override; + + CefRefPtr frontend_browser_; + scoped_refptr agent_host_; + scoped_ptr frontend_host_; + + DISALLOW_COPY_AND_ASSIGN(CefDevToolsFrontend); +}; + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_FRONTEND_H_ diff --git a/libcef/browser/devtools_scheme_handler.cc b/libcef/browser/devtools_scheme_handler.cc new file mode 100644 index 000000000..1573c8985 --- /dev/null +++ b/libcef/browser/devtools_scheme_handler.cc @@ -0,0 +1,54 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/devtools_scheme_handler.h" + +#include + +#include "libcef/browser/internal_scheme_handler.h" + +#include "base/strings/string_util.h" +#include "content/public/common/url_constants.h" +#include "grit/devtools_resources_map.h" + +namespace scheme { + +const char kChromeDevToolsHost[] = "devtools"; + +namespace { + +class Delegate : public InternalHandlerDelegate { + public: + Delegate() {} + + bool OnRequest(CefRefPtr request, + Action* action) override { + GURL url = GURL(request->GetURL().ToString()); + std::string path = url.path(); + if (path.length() > 0) + path = path.substr(1); + + for (size_t i = 0; i < kDevtoolsResourcesSize; ++i) { + if (base::strcasecmp(kDevtoolsResources[i].name, + path.c_str()) == 0) { + action->resource_id = kDevtoolsResources[i].value; + return true; + } + } + + return false; + } +}; + +} // namespace + +void RegisterChromeDevToolsHandler() { + CefRegisterSchemeHandlerFactory( + content::kChromeDevToolsScheme, + kChromeDevToolsHost, + CreateInternalHandlerFactory( + make_scoped_ptr(new Delegate()))); +} + +} // namespace scheme diff --git a/libcef/browser/devtools_scheme_handler.h b/libcef/browser/devtools_scheme_handler.h new file mode 100644 index 000000000..57168b17b --- /dev/null +++ b/libcef/browser/devtools_scheme_handler.h @@ -0,0 +1,18 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_DEVTOOLS_SCHEME_HANDLER_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_SCHEME_HANDLER_H_ +#pragma once + +namespace scheme { + +extern const char kChromeDevToolsHost[]; + +// Register the chrome-devtools scheme handler. +void RegisterChromeDevToolsHandler(); + +} // namespace scheme + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_SCHEME_HANDLER_H_ diff --git a/libcef/browser/download_item_impl.cc b/libcef/browser/download_item_impl.cc new file mode 100644 index 000000000..f0f340d67 --- /dev/null +++ b/libcef/browser/download_item_impl.cc @@ -0,0 +1,107 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/download_item_impl.h" + +#include "libcef/common/time_util.h" + +#include "content/public/browser/download_item.h" +#include "url/gurl.h" + + +CefDownloadItemImpl::CefDownloadItemImpl(content::DownloadItem* value) + : CefValueBase( + value, NULL, kOwnerNoDelete, true, + new CefValueControllerNonThreadSafe()) { + // Indicate that this object owns the controller. + SetOwnsController(); +} + +bool CefDownloadItemImpl::IsValid() { + return !detached(); +} + +bool CefDownloadItemImpl::IsInProgress() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().GetState() == content::DownloadItem::IN_PROGRESS; +} + +bool CefDownloadItemImpl::IsComplete() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().GetState() == content::DownloadItem::COMPLETE; +} + +bool CefDownloadItemImpl::IsCanceled() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().GetState() == content::DownloadItem::CANCELLED; +} + +int64 CefDownloadItemImpl::GetCurrentSpeed() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().CurrentSpeed(); +} + +int CefDownloadItemImpl::GetPercentComplete() { + CEF_VALUE_VERIFY_RETURN(false, -1); + return const_value().PercentComplete(); +} + +int64 CefDownloadItemImpl::GetTotalBytes() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().GetTotalBytes(); +} + +int64 CefDownloadItemImpl::GetReceivedBytes() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().GetReceivedBytes(); +} + +CefTime CefDownloadItemImpl::GetStartTime() { + CefTime time; + CEF_VALUE_VERIFY_RETURN(false, time); + cef_time_from_basetime(const_value().GetStartTime(), time); + return time; +} + +CefTime CefDownloadItemImpl::GetEndTime() { + CefTime time; + CEF_VALUE_VERIFY_RETURN(false, time); + cef_time_from_basetime(const_value().GetEndTime(), time); + return time; +} + +CefString CefDownloadItemImpl::GetFullPath() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetFullPath().value(); +} + +uint32 CefDownloadItemImpl::GetId() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().GetId(); +} + +CefString CefDownloadItemImpl::GetURL() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetURL().spec(); +} + +CefString CefDownloadItemImpl::GetOriginalUrl() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetOriginalUrl().spec(); +} + +CefString CefDownloadItemImpl::GetSuggestedFileName() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetSuggestedFilename(); +} + +CefString CefDownloadItemImpl::GetContentDisposition() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetContentDisposition(); +} + +CefString CefDownloadItemImpl::GetMimeType() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetMimeType(); +} diff --git a/libcef/browser/download_item_impl.h b/libcef/browser/download_item_impl.h new file mode 100644 index 000000000..adc3d01c8 --- /dev/null +++ b/libcef/browser/download_item_impl.h @@ -0,0 +1,45 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_DOWNLOAD_ITEM_IMPL_H_ +#define CEF_LIBCEF_BROWSER_DOWNLOAD_ITEM_IMPL_H_ +#pragma once + +#include "include/cef_download_item.h" +#include "libcef/common/value_base.h" + +namespace content { +class DownloadItem; +} + +// CefDownloadItem implementation +class CefDownloadItemImpl + : public CefValueBase { + public: + explicit CefDownloadItemImpl(content::DownloadItem* value); + + // CefDownloadItem methods. + bool IsValid() override; + bool IsInProgress() override; + bool IsComplete() override; + bool IsCanceled() override; + int64 GetCurrentSpeed() override; + int GetPercentComplete() override; + int64 GetTotalBytes() override; + int64 GetReceivedBytes() override; + CefTime GetStartTime() override; + CefTime GetEndTime() override; + CefString GetFullPath() override; + uint32 GetId() override; + CefString GetURL() override; + CefString GetOriginalUrl() override; + CefString GetSuggestedFileName() override; + CefString GetContentDisposition() override; + CefString GetMimeType() override; + + private: + DISALLOW_COPY_AND_ASSIGN(CefDownloadItemImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_DOWNLOAD_ITEM_IMPL_H_ diff --git a/libcef/browser/download_manager_delegate.cc b/libcef/browser/download_manager_delegate.cc new file mode 100644 index 000000000..8a8656cd8 --- /dev/null +++ b/libcef/browser/download_manager_delegate.cc @@ -0,0 +1,381 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/download_manager_delegate.h" + +#include "include/cef_download_handler.h" +#include "libcef/browser/browser_context.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/context.h" +#include "libcef/browser/download_item_impl.h" +#include "libcef/browser/thread_util.h" + +#include "base/bind.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/file_chooser_params.h" +#include "net/base/filename_util.h" + +using content::DownloadItem; +using content::DownloadManager; +using content::WebContents; + + +namespace { + +// Helper function to retrieve the CefBrowserHostImpl. +CefRefPtr GetBrowser(DownloadItem* item) { + content::WebContents* contents = item->GetWebContents(); + if (!contents) + return NULL; + + return CefBrowserHostImpl::GetBrowserForContents(contents).get(); +} + +// Helper function to retrieve the CefDownloadHandler. +CefRefPtr GetDownloadHandler( + CefRefPtr browser) { + CefRefPtr client = browser->GetClient(); + if (client.get()) + return client->GetDownloadHandler(); + return NULL; +} + + +// CefBeforeDownloadCallback implementation. +class CefBeforeDownloadCallbackImpl : public CefBeforeDownloadCallback { + public: + CefBeforeDownloadCallbackImpl( + const base::WeakPtr& manager, + uint32 download_id, + const base::FilePath& suggested_name, + const content::DownloadTargetCallback& callback) + : manager_(manager), + download_id_(download_id), + suggested_name_(suggested_name), + callback_(callback) { + } + + void Continue(const CefString& download_path, + bool show_dialog) override { + if (CEF_CURRENTLY_ON_UIT()) { + if (download_id_ <= 0) + return; + + if (manager_) { + base::FilePath path = base::FilePath(download_path); + CEF_POST_TASK(CEF_FILET, + base::Bind(&CefBeforeDownloadCallbackImpl::GenerateFilename, + manager_, download_id_, suggested_name_, path, + show_dialog, callback_)); + } + + download_id_ = 0; + callback_.Reset(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBeforeDownloadCallbackImpl::Continue, this, + download_path, show_dialog)); + } + } + + private: + static void GenerateFilename( + base::WeakPtr manager, + uint32 download_id, + const base::FilePath& suggested_name, + const base::FilePath& download_path, + bool show_dialog, + const content::DownloadTargetCallback& callback) { + base::FilePath suggested_path = download_path; + if (!suggested_path.empty()) { + // Create the directory if necessary. + base::FilePath dir_path = suggested_path.DirName(); + if (!base::DirectoryExists(dir_path) && + !base::CreateDirectory(dir_path)) { + NOTREACHED() << "failed to create the download directory"; + suggested_path.clear(); + } + } + + if (suggested_path.empty()) { + if (PathService::Get(base::DIR_TEMP, &suggested_path)) { + // Use the temp directory. + suggested_path = suggested_path.Append(suggested_name); + } else { + // Use the current working directory. + suggested_path = suggested_name; + } + } + + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefBeforeDownloadCallbackImpl::ChooseDownloadPath, + manager, download_id, suggested_path, show_dialog, + callback)); + } + + static void ChooseDownloadPath( + base::WeakPtr manager, + uint32 download_id, + const base::FilePath& suggested_path, + bool show_dialog, + const content::DownloadTargetCallback& callback) { + if (!manager) + return; + + DownloadItem* item = manager->GetDownload(download_id); + if (!item || item->GetState() != content::DownloadItem::IN_PROGRESS) + return; + + bool handled = false; + + if (show_dialog) { + WebContents* web_contents = item->GetWebContents(); + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForContents(web_contents); + if (browser.get()) { + handled = true; + + CefBrowserHostImpl::FileChooserParams params; + params.mode = content::FileChooserParams::Save; + if (!suggested_path.empty()) { + params.default_file_name = suggested_path; + if (!suggested_path.Extension().empty()) { + params.accept_types.push_back( + CefString(suggested_path.Extension())); + } + } + + browser->RunFileChooser(params, + base::Bind( + &CefBeforeDownloadCallbackImpl::ChooseDownloadPathCallback, + callback)); + } + } + + if (!handled) { + callback.Run(suggested_path, + DownloadItem::TARGET_DISPOSITION_OVERWRITE, + content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + suggested_path); + } + } + + static void ChooseDownloadPathCallback( + const content::DownloadTargetCallback& callback, + int selected_accept_filter, + const std::vector& file_paths) { + DCHECK_LE(file_paths.size(), (size_t) 1); + + base::FilePath path; + if (file_paths.size() > 0) + path = file_paths.front(); + + // The download will be cancelled if |path| is empty. + callback.Run(path, + DownloadItem::TARGET_DISPOSITION_OVERWRITE, + content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + path); + } + + base::WeakPtr manager_; + uint32 download_id_; + base::FilePath suggested_name_; + content::DownloadTargetCallback callback_; + + IMPLEMENT_REFCOUNTING(CefBeforeDownloadCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefBeforeDownloadCallbackImpl); +}; + + +// CefDownloadItemCallback implementation. +class CefDownloadItemCallbackImpl : public CefDownloadItemCallback { + public: + explicit CefDownloadItemCallbackImpl( + const base::WeakPtr& manager, + uint32 download_id) + : manager_(manager), + download_id_(download_id) { + } + + void Cancel() override { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefDownloadItemCallbackImpl::DoCancel, this)); + } + + void Pause() override { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefDownloadItemCallbackImpl::DoPause, this)); + } + + void Resume() override { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefDownloadItemCallbackImpl::DoResume, this)); + } + private: + void DoCancel() { + if (download_id_ <= 0) + return; + + if (manager_) { + DownloadItem* item = manager_->GetDownload(download_id_); + if (item && item->GetState() == content::DownloadItem::IN_PROGRESS) + item->Cancel(true); + } + + download_id_ = 0; + } + + void DoPause() { + if (download_id_ <= 0) + return; + + if (manager_) { + DownloadItem* item = manager_->GetDownload(download_id_); + if (item && item->GetState() == content::DownloadItem::IN_PROGRESS) + item->Pause(); + } + } + + void DoResume() { + if (download_id_ <= 0) + return; + + if (manager_) { + DownloadItem* item = manager_->GetDownload(download_id_); + if (item && item->CanResume()) + item->Resume(); + } + } + + base::WeakPtr manager_; + uint32 download_id_; + + IMPLEMENT_REFCOUNTING(CefDownloadItemCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefDownloadItemCallbackImpl); +}; + +} // namespace + + +CefDownloadManagerDelegate::CefDownloadManagerDelegate( + DownloadManager* manager) + : manager_(manager), + manager_ptr_factory_(manager) { + DCHECK(manager); + manager->AddObserver(this); + + DownloadManager::DownloadVector items; + manager->GetAllDownloads(&items); + DownloadManager::DownloadVector::const_iterator it = items.begin(); + for (; it != items.end(); ++it) { + (*it)->AddObserver(this); + observing_.insert(*it); + } +} + +CefDownloadManagerDelegate::~CefDownloadManagerDelegate() { + if (manager_) { + manager_->SetDelegate(NULL); + manager_->RemoveObserver(this); + } + + std::set::const_iterator it = observing_.begin(); + for (; it != observing_.end(); ++it) + (*it)->RemoveObserver(this); + observing_.clear(); +} + +void CefDownloadManagerDelegate::OnDownloadUpdated( + DownloadItem* download) { + CefRefPtr browser = GetBrowser(download); + CefRefPtr handler; + if (browser.get()) + handler = GetDownloadHandler(browser); + + if (handler.get()) { + CefRefPtr download_item( + new CefDownloadItemImpl(download)); + CefRefPtr callback( + new CefDownloadItemCallbackImpl(manager_ptr_factory_.GetWeakPtr(), + download->GetId())); + + handler->OnDownloadUpdated(browser.get(), download_item.get(), callback); + + download_item->Detach(NULL); + } +} + +void CefDownloadManagerDelegate::OnDownloadDestroyed( + DownloadItem* download) { + download->RemoveObserver(this); + observing_.erase(download); +} + +void CefDownloadManagerDelegate::OnDownloadCreated( + DownloadManager* manager, + DownloadItem* item) { + item->AddObserver(this); + observing_.insert(item); +} + +void CefDownloadManagerDelegate::ManagerGoingDown( + DownloadManager* manager) { + DCHECK_EQ(manager, manager_); + manager->SetDelegate(NULL); + manager->RemoveObserver(this); + manager_ptr_factory_.InvalidateWeakPtrs(); + manager_ = NULL; +} + +bool CefDownloadManagerDelegate::DetermineDownloadTarget( + DownloadItem* item, + const content::DownloadTargetCallback& callback) { + if (!item->GetForcedFilePath().empty()) { + callback.Run(item->GetForcedFilePath(), + DownloadItem::TARGET_DISPOSITION_OVERWRITE, + content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, + item->GetForcedFilePath()); + return true; + } + + CefRefPtr browser = GetBrowser(item); + CefRefPtr handler; + if (browser.get()) + handler = GetDownloadHandler(browser); + + if (handler.get()) { + base::FilePath suggested_name = net::GenerateFileName( + item->GetURL(), + item->GetContentDisposition(), + std::string(), + item->GetSuggestedFilename(), + item->GetMimeType(), + "download"); + + CefRefPtr download_item(new CefDownloadItemImpl(item)); + CefRefPtr callbackObj( + new CefBeforeDownloadCallbackImpl(manager_ptr_factory_.GetWeakPtr(), + item->GetId(), suggested_name, + callback)); + + handler->OnBeforeDownload(browser.get(), download_item.get(), + suggested_name.value(), callbackObj); + + download_item->Detach(NULL); + } + + return true; +} + +void CefDownloadManagerDelegate::GetNextId( + const content::DownloadIdCallback& callback) { + static uint32 next_id = DownloadItem::kInvalidId + 1; + callback.Run(next_id++); +} diff --git a/libcef/browser/download_manager_delegate.h b/libcef/browser/download_manager_delegate.h new file mode 100644 index 000000000..f878a8562 --- /dev/null +++ b/libcef/browser/download_manager_delegate.h @@ -0,0 +1,48 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_DOWNLOAD_MANAGER_DELEGATE_H_ +#define CEF_LIBCEF_BROWSER_DOWNLOAD_MANAGER_DELEGATE_H_ +#pragma once + +#include + +#include "base/compiler_specific.h" +#include "base/memory/weak_ptr.h" +#include "content/public/browser/download_item.h" +#include "content/public/browser/download_manager.h" +#include "content/public/browser/download_manager_delegate.h" + +class CefDownloadManagerDelegate + : public content::DownloadItem::Observer, + public content::DownloadManager::Observer, + public content::DownloadManagerDelegate { + public: + explicit CefDownloadManagerDelegate(content::DownloadManager* manager); + ~CefDownloadManagerDelegate() override; + + private: + // DownloadItem::Observer methods. + void OnDownloadUpdated(content::DownloadItem* download) override; + void OnDownloadDestroyed(content::DownloadItem* download) override; + + // DownloadManager::Observer methods. + void OnDownloadCreated(content::DownloadManager* manager, + content::DownloadItem* item) override; + void ManagerGoingDown(content::DownloadManager* manager) override; + + // DownloadManagerDelegate methods. + bool DetermineDownloadTarget( + content::DownloadItem* item, + const content::DownloadTargetCallback& callback) override; + void GetNextId(const content::DownloadIdCallback& callback) override; + + content::DownloadManager* manager_; + base::WeakPtrFactory manager_ptr_factory_; + std::set observing_; + + DISALLOW_COPY_AND_ASSIGN(CefDownloadManagerDelegate); +}; + +#endif // CEF_LIBCEF_BROWSER_DOWNLOAD_MANAGER_DELEGATE_H_ diff --git a/libcef/browser/frame_host_impl.cc b/libcef/browser/frame_host_impl.cc new file mode 100644 index 000000000..7d9531a40 --- /dev/null +++ b/libcef/browser/frame_host_impl.cc @@ -0,0 +1,279 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/frame_host_impl.h" +#include "include/cef_request.h" +#include "include/cef_stream.h" +#include "include/cef_v8.h" +#include "libcef/common/cef_messages.h" +#include "libcef/browser/browser_host_impl.h" + +namespace { + +// Implementation of CommandResponseHandler for calling a CefStringVisitor. +class StringVisitHandler : public CefResponseManager::Handler { + public: + explicit StringVisitHandler(CefRefPtr visitor) + : visitor_(visitor) { + } + void OnResponse(const Cef_Response_Params& params) override { + visitor_->Visit(params.response); + } + private: + CefRefPtr visitor_; + + IMPLEMENT_REFCOUNTING(StringVisitHandler); +}; + +// Implementation of CommandResponseHandler for calling ViewText(). +class ViewTextHandler : public CefResponseManager::Handler { + public: + explicit ViewTextHandler(CefRefPtr frame) + : frame_(frame) { + } + void OnResponse(const Cef_Response_Params& params) override { + CefRefPtr browser = frame_->GetBrowser(); + if (browser.get()) { + static_cast(browser.get())->ViewText( + params.response); + } + } + private: + CefRefPtr frame_; + + IMPLEMENT_REFCOUNTING(ViewTextHandler); +}; + +} // namespace + +CefFrameHostImpl::CefFrameHostImpl(CefBrowserHostImpl* browser, + int64 frame_id, + bool is_main_frame, + const CefString& url, + const CefString& name, + int64 parent_frame_id) + : frame_id_(frame_id), + is_main_frame_(is_main_frame), + browser_(browser), + is_focused_(is_main_frame_), // The main frame always starts focused. + url_(url), + name_(name), + parent_frame_id_(parent_frame_id == kUnspecifiedFrameId ? + kInvalidFrameId : parent_frame_id) { +} + +CefFrameHostImpl::~CefFrameHostImpl() { +} + +bool CefFrameHostImpl::IsValid() { + base::AutoLock lock_scope(state_lock_); + return (browser_ != NULL); +} + +void CefFrameHostImpl::Undo() { + SendCommand("Undo", NULL); +} + +void CefFrameHostImpl::Redo() { + SendCommand("Redo", NULL); +} + +void CefFrameHostImpl::Cut() { + SendCommand("Cut", NULL); +} + +void CefFrameHostImpl::Copy() { + SendCommand("Copy", NULL); +} + +void CefFrameHostImpl::Paste() { + SendCommand("Paste", NULL); +} + +void CefFrameHostImpl::Delete() { + SendCommand("Delete", NULL); +} + +void CefFrameHostImpl::SelectAll() { + SendCommand("SelectAll", NULL); +} + +void CefFrameHostImpl::ViewSource() { + SendCommand("GetSource", new ViewTextHandler(this)); +} + +void CefFrameHostImpl::GetSource(CefRefPtr visitor) { + SendCommand("GetSource", new StringVisitHandler(visitor)); +} + +void CefFrameHostImpl::GetText(CefRefPtr visitor) { + SendCommand("GetText", new StringVisitHandler(visitor)); +} + +void CefFrameHostImpl::LoadRequest(CefRefPtr request) { + CefRefPtr browser; + int64 frame_id; + + { + base::AutoLock lock_scope(state_lock_); + browser = browser_; + frame_id = (is_main_frame_ ? kMainFrameId : frame_id_); + } + + if (browser.get()) + browser->LoadRequest(frame_id, request); +} + +void CefFrameHostImpl::LoadURL(const CefString& url) { + CefRefPtr browser; + int64 frame_id; + + { + base::AutoLock lock_scope(state_lock_); + browser = browser_; + frame_id = (is_main_frame_ ? kMainFrameId : frame_id_); + } + + if (browser.get()) { + browser->LoadURL(frame_id, url, content::Referrer(), + ui::PAGE_TRANSITION_TYPED, std::string()); + } +} + +void CefFrameHostImpl::LoadString(const CefString& string, + const CefString& url) { + CefRefPtr browser; + int64 frame_id; + + { + base::AutoLock lock_scope(state_lock_); + browser = browser_; + frame_id = (is_main_frame_ ? kMainFrameId : frame_id_); + } + + if (browser.get()) + browser->LoadString(frame_id, string, url); +} + +void CefFrameHostImpl::ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, + int startLine) { + SendJavaScript(jsCode, scriptUrl, startLine); +} + +bool CefFrameHostImpl::IsMain() { + return is_main_frame_; +} + +bool CefFrameHostImpl::IsFocused() { + base::AutoLock lock_scope(state_lock_); + return is_focused_; +} + +CefString CefFrameHostImpl::GetName() { + base::AutoLock lock_scope(state_lock_); + return name_; +} + +int64 CefFrameHostImpl::GetIdentifier() { + return frame_id_; +} + +CefRefPtr CefFrameHostImpl::GetParent() { + CefRefPtr browser; + int64 parent_frame_id; + + { + base::AutoLock lock_scope(state_lock_); + if (is_main_frame_ || parent_frame_id_ == kInvalidFrameId) + return NULL; + browser = browser_; + parent_frame_id = parent_frame_id_; + } + + if (browser.get()) + return browser->GetFrame(parent_frame_id); + + return NULL; +} + +CefString CefFrameHostImpl::GetURL() { + base::AutoLock lock_scope(state_lock_); + return url_; +} + +CefRefPtr CefFrameHostImpl::GetBrowser() { + base::AutoLock lock_scope(state_lock_); + return browser_; +} + +void CefFrameHostImpl::SetFocused(bool focused) { + base::AutoLock lock_scope(state_lock_); + is_focused_ = focused; +} + +void CefFrameHostImpl::SetAttributes(const CefString& url, + const CefString& name, + int64 parent_frame_id) { + base::AutoLock lock_scope(state_lock_); + if (!url.empty() && url != url_) + url_ = url; + if (!name.empty() && name != name_) + name_ = name; + if (parent_frame_id != kUnspecifiedFrameId) + parent_frame_id_ = parent_frame_id; +} + +CefRefPtr CefFrameHostImpl::GetV8Context() { + NOTREACHED() << "GetV8Context cannot be called from the browser process"; + return NULL; +} + +void CefFrameHostImpl::VisitDOM(CefRefPtr visitor) { + NOTREACHED() << "VisitDOM cannot be called from the browser process"; +} + +void CefFrameHostImpl::SendJavaScript( + const std::string& jsCode, + const std::string& scriptUrl, + int startLine) { + if (jsCode.empty()) + return; + if (startLine < 0) + startLine = 0; + + CefRefPtr browser; + int64 frame_id; + + { + base::AutoLock lock_scope(state_lock_); + browser = browser_; + frame_id = (is_main_frame_ ? kMainFrameId : frame_id_); + } + + if (browser.get()) + browser->SendCode(frame_id, true, jsCode, scriptUrl, startLine, NULL); +} + +void CefFrameHostImpl::Detach() { + base::AutoLock lock_scope(state_lock_); + browser_ = NULL; +} + +void CefFrameHostImpl::SendCommand( + const std::string& command, + CefRefPtr responseHandler) { + CefRefPtr browser; + int64 frame_id; + + { + base::AutoLock lock_scope(state_lock_); + browser = browser_; + // Commands can only be sent to known frame ids. + frame_id = frame_id_; + } + + if (browser.get() && frame_id != kInvalidFrameId) + browser->SendCommand(frame_id, command, responseHandler); +} diff --git a/libcef/browser/frame_host_impl.h b/libcef/browser/frame_host_impl.h new file mode 100644 index 000000000..ec486a305 --- /dev/null +++ b/libcef/browser/frame_host_impl.h @@ -0,0 +1,96 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_FRAME_HOST_IMPL_H_ +#define CEF_LIBCEF_BROWSER_FRAME_HOST_IMPL_H_ +#pragma once + +#include +#include "include/cef_frame.h" +#include "libcef/common/response_manager.h" +#include "base/synchronization/lock.h" + +class CefBrowserHostImpl; + +// Implementation of CefFrame. CefFrameHostImpl objects are owned by the +// CefBrowerHostImpl and will be detached when the browser is notified that the +// associated renderer WebFrame will close. +class CefFrameHostImpl : public CefFrame { + public: + CefFrameHostImpl(CefBrowserHostImpl* browser, + int64 frame_id, + bool is_main_frame, + const CefString& url, + const CefString& name, + int64 parent_frame_id); + ~CefFrameHostImpl() override; + + // CefFrame methods + bool IsValid() override; + void Undo() override; + void Redo() override; + void Cut() override; + void Copy() override; + void Paste() override; + void Delete() override; + void SelectAll() override; + void ViewSource() override; + void GetSource(CefRefPtr visitor) override; + void GetText(CefRefPtr visitor) override; + void LoadRequest(CefRefPtr request) override; + void LoadURL(const CefString& url) override; + void LoadString(const CefString& string, + const CefString& url) override; + void ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, + int startLine) override; + bool IsMain() override; + bool IsFocused() override; + CefString GetName() override; + int64 GetIdentifier() override; + CefRefPtr GetParent() override; + CefString GetURL() override; + CefRefPtr GetBrowser() override; + CefRefPtr GetV8Context() override; + void VisitDOM(CefRefPtr visitor) override; + + void SetFocused(bool focused); + void SetAttributes(const CefString& url, + const CefString& name, + int64 parent_frame_id); + + // Avoids unnecessary string type conversions. + void SendJavaScript(const std::string& jsCode, + const std::string& scriptUrl, + int startLine); + + // Detach the frame from the browser. + void Detach(); + + // kMainFrameId must be -1 to align with renderer expectations. + static const int64 kMainFrameId = -1; + static const int64 kFocusedFrameId = -2; + static const int64 kUnspecifiedFrameId = -3; + static const int64 kInvalidFrameId = -4; + + protected: + void SendCommand(const std::string& command, + CefRefPtr responseHandler); + + int64 frame_id_; + bool is_main_frame_; + + // Volatile state information. All access must be protected by the state lock. + base::Lock state_lock_; + CefBrowserHostImpl* browser_; + bool is_focused_; + CefString url_; + CefString name_; + int64 parent_frame_id_; + + IMPLEMENT_REFCOUNTING(CefFrameHostImpl); + DISALLOW_EVIL_CONSTRUCTORS(CefFrameHostImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_FRAME_HOST_IMPL_H_ diff --git a/libcef/browser/geolocation_impl.cc b/libcef/browser/geolocation_impl.cc new file mode 100644 index 000000000..47c93c34c --- /dev/null +++ b/libcef/browser/geolocation_impl.cc @@ -0,0 +1,105 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "include/cef_geolocation.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/time_util.h" +#include "base/logging.h" +#include "content/public/browser/geolocation_provider.h" +#include "content/public/common/geoposition.h" + +namespace { + +class CefLocationRequest : + public base::RefCountedThreadSafe { + public: + explicit CefLocationRequest(CefRefPtr callback) + : callback_(callback) { + CEF_REQUIRE_UIT(); + geo_callback_ = base::Bind(&CefLocationRequest::OnLocationUpdate, this); + content::GeolocationProvider* provider = + content::GeolocationProvider::GetInstance(); + subscription_ = provider->AddLocationUpdateCallback(geo_callback_, true); + provider->UserDidOptIntoLocationServices(); + } + + private: + friend class base::RefCountedThreadSafe; + + ~CefLocationRequest() {} + + void OnLocationUpdate(const content::Geoposition& position) { + CEF_REQUIRE_UIT(); + if (callback_.get()) { + CefGeoposition cef_position; + SetPosition(position, cef_position); + callback_->OnLocationUpdate(cef_position); + callback_ = NULL; + } + subscription_.reset(); + geo_callback_.Reset(); + } + + void SetPosition(const content::Geoposition& source, CefGeoposition& target) { + target.latitude = source.latitude; + target.longitude = source.longitude; + target.altitude = source.altitude; + target.accuracy = source.accuracy; + target.altitude_accuracy = source.altitude_accuracy; + target.heading = source.heading; + target.speed = source.speed; + cef_time_from_basetime(source.timestamp, target.timestamp); + + switch (source.error_code) { + case content::Geoposition::ERROR_CODE_NONE: + target.error_code = GEOPOSITON_ERROR_NONE; + break; + case content::Geoposition::ERROR_CODE_PERMISSION_DENIED: + target.error_code = GEOPOSITON_ERROR_PERMISSION_DENIED; + break; + case content::Geoposition::ERROR_CODE_POSITION_UNAVAILABLE: + target.error_code = GEOPOSITON_ERROR_POSITION_UNAVAILABLE; + break; + case content::Geoposition::ERROR_CODE_TIMEOUT: + target.error_code = GEOPOSITON_ERROR_TIMEOUT; + break; + } + + CefString(&target.error_message) = source.error_message; + } + + CefRefPtr callback_; + content::GeolocationProvider::LocationUpdateCallback geo_callback_; + scoped_ptr subscription_; + + DISALLOW_COPY_AND_ASSIGN(CefLocationRequest); +}; + +} // namespace + +bool CefGetGeolocation(CefRefPtr callback) { + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return false; + } + + if (!callback.get()) { + NOTREACHED() << "invalid parameter"; + return false; + } + + if (CEF_CURRENTLY_ON_UIT()) { + if (content::GeolocationProvider::GetInstance()) { + // Will be released after the callback executes. + new CefLocationRequest(callback); + return true; + } + return false; + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(base::IgnoreResult(CefGetGeolocation), callback)); + return true; + } +} diff --git a/libcef/browser/internal_scheme_handler.cc b/libcef/browser/internal_scheme_handler.cc new file mode 100644 index 000000000..6a955ffb3 --- /dev/null +++ b/libcef/browser/internal_scheme_handler.cc @@ -0,0 +1,178 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/internal_scheme_handler.h" +#include +#include "libcef/common/content_client.h" +#include "base/strings/string_util.h" +#include "ui/base/resource/resource_bundle.h" + +namespace scheme { + +namespace { + +static std::string GetMimeType(const std::string& filename) { + if (EndsWith(filename, ".html", false)) { + return "text/html"; + } else if (EndsWith(filename, ".css", false)) { + return "text/css"; + } else if (EndsWith(filename, ".jpg", false)) { + return "image/jpeg"; + } else if (EndsWith(filename, ".js", false)) { + return "application/javascript"; + } else if (EndsWith(filename, ".png", false)) { + return "image/png"; + } else if (EndsWith(filename, ".gif", false)) { + return "image/gif"; + } + NOTREACHED() << "No known mime type for file: " << filename.c_str(); + return "text/plain"; +} + +class RedirectHandler : public CefResourceHandler { + public: + explicit RedirectHandler(const GURL& url) + : url_(url) { + } + + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override { + callback->Continue(); + return true; + } + + void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) override { + response_length = 0; + redirectUrl = url_.spec(); + } + + bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) override { + return false; + } + + void Cancel() override { + } + + private: + GURL url_; + + IMPLEMENT_REFCOUNTING(RedirectHandler); +}; + +class InternalHandler : public CefResourceHandler { + public: + InternalHandler(const std::string& mime_type, + CefRefPtr reader, + int size) + : mime_type_(mime_type), + reader_(reader), + size_(size) { + } + + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override { + callback->Continue(); + return true; + } + + void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) override { + response_length = size_; + + response->SetMimeType(mime_type_); + response->SetStatus(200); + } + + bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) override { + bytes_read = reader_->Read(data_out, 1, bytes_to_read); + return (bytes_read > 0); + } + + void Cancel() override { + } + + private: + std::string mime_type_; + CefRefPtr reader_; + int size_; + + IMPLEMENT_REFCOUNTING(InternalHandler); +}; + +class InternalHandlerFactory : public CefSchemeHandlerFactory { + public: + explicit InternalHandlerFactory( + scoped_ptr delegate) + : delegate_(delegate.Pass()) { + } + + CefRefPtr Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) override { + GURL url = GURL(request->GetURL().ToString()); + + InternalHandlerDelegate::Action action; + if (delegate_->OnRequest(request, &action)) { + if (!action.redirect_url.is_empty() && action.redirect_url.is_valid()) + return new RedirectHandler(action.redirect_url); + + if (action.mime_type.empty()) + action.mime_type = GetMimeType(url.path()); + + if (action.resource_id >= 0) { + base::StringPiece piece = CefContentClient::Get()->GetDataResource( + action.resource_id, ui::SCALE_FACTOR_NONE); + if (!piece.empty()) { + action.stream = + CefStreamReader::CreateForData(const_cast(piece.data()), + piece.size()); + action.stream_size = piece.size(); + } else { + NOTREACHED() << "Failed to load internal resource for id: " << + action.resource_id << " URL: " << url.spec().c_str(); + return NULL; + } + } + + if (action.stream.get()) { + return new InternalHandler(action.mime_type, action.stream, + action.stream_size); + } + } + + return NULL; + } + + private: + scoped_ptr delegate_; + + IMPLEMENT_REFCOUNTING(InternalHandlerFactory); +}; + +} // namespace + +InternalHandlerDelegate::Action::Action() + : stream_size(-1), + resource_id(-1) { +} + +CefRefPtr CreateInternalHandlerFactory( + scoped_ptr delegate) { + DCHECK(delegate.get()); + return new InternalHandlerFactory(delegate.Pass()); +} + +} // namespace scheme diff --git a/libcef/browser/internal_scheme_handler.h b/libcef/browser/internal_scheme_handler.h new file mode 100644 index 000000000..f29637374 --- /dev/null +++ b/libcef/browser/internal_scheme_handler.h @@ -0,0 +1,53 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_INTERNAL_SCHEME_HANDLER_H_ +#define CEF_LIBCEF_BROWSER_INTERNAL_SCHEME_HANDLER_H_ +#pragma once + +#include +#include "include/cef_scheme.h" +#include "base/memory/scoped_ptr.h" +#include "url/gurl.h" + +namespace scheme { + +// All methods will be called on the browser process IO thread. +class InternalHandlerDelegate { + public: + class Action { + public: + Action(); + + // Set to the appropriate value or leave empty to have it determined based + // on the file extension. + std::string mime_type; + + // Option 1: Provide a stream for the resource contents. Set |stream_size| + // to the stream size or to -1 if unknown. + CefRefPtr stream; + int stream_size; + + // Option 2: Specify a resource id to load static content. + int resource_id; + + // Option 3: Redirect to the specified URL. + GURL redirect_url; + }; + + virtual ~InternalHandlerDelegate() {} + + // Populate |action| and return true if the request was handled. + virtual bool OnRequest(CefRefPtr request, + Action* action) = 0; +}; + +// Create an internal scheme handler factory. The factory will take ownership of +// |delegate|. +CefRefPtr CreateInternalHandlerFactory( + scoped_ptr delegate); + +} // namespace scheme + +#endif // CEF_LIBCEF_BROWSER_INTERNAL_SCHEME_HANDLER_H_ diff --git a/libcef/browser/javascript_dialog.h b/libcef/browser/javascript_dialog.h new file mode 100644 index 000000000..4e1da5a27 --- /dev/null +++ b/libcef/browser/javascript_dialog.h @@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_JAVASCRIPT_DIALOG_H_ +#define CEF_LIBCEF_BROWSER_JAVASCRIPT_DIALOG_H_ +#pragma once + +#include "content/public/browser/javascript_dialog_manager.h" + +#if defined(OS_MACOSX) +#if __OBJC__ +@class CefJavaScriptDialogHelper; +#else +class CefJavaScriptDialogHelper; +#endif // __OBJC__ +#endif // defined(OS_MACOSX) + +class CefJavaScriptDialogManager; + +class CefJavaScriptDialog { + public: + CefJavaScriptDialog( + CefJavaScriptDialogManager* creator, + content::JavaScriptMessageType message_type, + const base::string16& display_url, + const base::string16& message_text, + const base::string16& default_prompt_text, + const content::JavaScriptDialogManager::DialogClosedCallback& callback); + ~CefJavaScriptDialog(); + + // Called to cancel a dialog mid-flight. + void Cancel(); + + // Activate the dialog. + void Activate(); + + private: + CefJavaScriptDialogManager* creator_; + content::JavaScriptDialogManager::DialogClosedCallback callback_; + +#if defined(OS_MACOSX) + CefJavaScriptDialogHelper* helper_; // owned +#elif defined(OS_WIN) + content::JavaScriptMessageType message_type_; + HWND dialog_win_; + HWND parent_win_; + base::string16 message_text_; + base::string16 default_prompt_text_; + static INT_PTR CALLBACK DialogProc(HWND dialog, UINT message, WPARAM wparam, + LPARAM lparam); + + // Since the message loop we expect to run in isn't going to be nicely + // calling IsDialogMessage(), we need to hook the wnd proc and call it + // ourselves. See http://support.microsoft.com/kb/q187988/ + static bool InstallMessageHook(); + static bool UninstallMessageHook(); + static LRESULT CALLBACK GetMsgProc(int code, WPARAM wparam, LPARAM lparam); + static HHOOK msg_hook_; + static int msg_hook_user_count_; +#endif + + DISALLOW_COPY_AND_ASSIGN(CefJavaScriptDialog); +}; + +#endif // CEF_LIBCEF_BROWSER_JAVASCRIPT_DIALOG_H_ diff --git a/libcef/browser/javascript_dialog_linux.cc b/libcef/browser/javascript_dialog_linux.cc new file mode 100644 index 000000000..83bcdfdd9 --- /dev/null +++ b/libcef/browser/javascript_dialog_linux.cc @@ -0,0 +1,28 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/javascript_dialog.h" +#include "libcef/browser/javascript_dialog_manager.h" + +CefJavaScriptDialog::CefJavaScriptDialog( + CefJavaScriptDialogManager* creator, + content::JavaScriptMessageType message_type, + const base::string16& display_url, + const base::string16& message_text, + const base::string16& default_prompt_text, + const content::JavaScriptDialogManager::DialogClosedCallback& callback) + : creator_(creator), + callback_(callback) { + NOTIMPLEMENTED(); + callback_.Run(false, base::string16()); + creator_->DialogClosed(this); +} + +CefJavaScriptDialog::~CefJavaScriptDialog() { +} + +void CefJavaScriptDialog::Cancel() { +} + diff --git a/libcef/browser/javascript_dialog_mac.mm b/libcef/browser/javascript_dialog_mac.mm new file mode 100644 index 000000000..83de49cf3 --- /dev/null +++ b/libcef/browser/javascript_dialog_mac.mm @@ -0,0 +1,155 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/javascript_dialog.h" +#include "libcef/browser/javascript_dialog_manager.h" + +#import + +#import "base/mac/scoped_nsobject.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" + +// Helper object that receives the notification that the dialog/sheet is +// going away. Is responsible for cleaning itself up. +@interface CefJavaScriptDialogHelper : NSObject { + @private + base::scoped_nsobject alert_; + NSTextField* textField_; // WEAK; owned by alert_ + + // Copies of the fields in CefJavaScriptDialog because they're private. + CefJavaScriptDialogManager* creator_; + content::JavaScriptDialogManager::DialogClosedCallback callback_; +} + +- (id)initHelperWithCreator:(CefJavaScriptDialogManager*)creator + andCallback:(content::JavaScriptDialogManager::DialogClosedCallback)callback; +- (NSAlert*)alert; +- (NSTextField*)textField; +- (void)alertDidEnd:(NSAlert*)alert + returnCode:(int)returnCode + contextInfo:(void*)contextInfo; +- (void)cancel; + +@end + +@implementation CefJavaScriptDialogHelper + +- (id)initHelperWithCreator:(CefJavaScriptDialogManager*)creator + andCallback:(content::JavaScriptDialogManager::DialogClosedCallback)callback { + if (self = [super init]) { + creator_ = creator; + callback_ = callback; + } + + return self; +} + +- (NSAlert*)alert { + alert_.reset([[NSAlert alloc] init]); + return alert_; +} + +- (NSTextField*)textField { + textField_ = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 22)]; + [[textField_ cell] setLineBreakMode:NSLineBreakByTruncatingTail]; + [alert_ setAccessoryView:textField_]; + [textField_ release]; + + return textField_; +} + +- (void)alertDidEnd:(NSAlert*)alert + returnCode:(int)returnCode + contextInfo:(void*)contextInfo { + if (returnCode == NSRunStoppedResponse) + return; + + bool success = returnCode == NSAlertFirstButtonReturn; + base::string16 input; + if (textField_) + input = base::SysNSStringToUTF16([textField_ stringValue]); + + CefJavaScriptDialog* native_dialog = + reinterpret_cast(contextInfo); + callback_.Run(success, input); + creator_->DialogClosed(native_dialog); +} + +- (void)cancel { + [NSApp endSheet:[alert_ window]]; + alert_.reset(); +} + +@end + +CefJavaScriptDialog::CefJavaScriptDialog( + CefJavaScriptDialogManager* creator, + content::JavaScriptMessageType message_type, + const base::string16& display_url, + const base::string16& message_text, + const base::string16& default_prompt_text, + const content::JavaScriptDialogManager::DialogClosedCallback& callback) + : creator_(creator), + callback_(callback) { + bool text_field = + message_type == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT; + bool one_button = + message_type == content::JAVASCRIPT_MESSAGE_TYPE_ALERT; + + helper_ = + [[CefJavaScriptDialogHelper alloc] initHelperWithCreator:creator + andCallback:callback]; + + // Show the modal dialog. + NSAlert* alert = [helper_ alert]; + NSTextField* field = nil; + if (text_field) { + field = [helper_ textField]; + [field setStringValue:base::SysUTF16ToNSString(default_prompt_text)]; + } + [alert setDelegate:helper_]; + [alert setInformativeText:base::SysUTF16ToNSString(message_text)]; + + base::string16 label; + switch (message_type) { + case content::JAVASCRIPT_MESSAGE_TYPE_ALERT: + label = base::ASCIIToUTF16("JavaScript Alert"); + break; + case content::JAVASCRIPT_MESSAGE_TYPE_PROMPT: + label = base::ASCIIToUTF16("JavaScript Prompt"); + break; + case content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM: + label = base::ASCIIToUTF16("JavaScript Confirm"); + break; + } + if (!display_url.empty()) + label += base::ASCIIToUTF16(" - ") + display_url; + + [alert setMessageText:base::SysUTF16ToNSString(label)]; + + [alert addButtonWithTitle:@"OK"]; + if (!one_button) { + NSButton* other = [alert addButtonWithTitle:@"Cancel"]; + [other setKeyEquivalent:@"\e"]; + } + + [alert + beginSheetModalForWindow:nil // nil here makes it app-modal + modalDelegate:helper_ + didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) + contextInfo:this]; + + if ([alert accessoryView]) + [[alert window] makeFirstResponder:[alert accessoryView]]; +} + +CefJavaScriptDialog::~CefJavaScriptDialog() { + [helper_ release]; +} + +void CefJavaScriptDialog::Cancel() { + [helper_ cancel]; +} diff --git a/libcef/browser/javascript_dialog_manager.cc b/libcef/browser/javascript_dialog_manager.cc new file mode 100644 index 000000000..6e8ce3103 --- /dev/null +++ b/libcef/browser/javascript_dialog_manager.cc @@ -0,0 +1,226 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/javascript_dialog_manager.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/javascript_dialog.h" +#include "libcef/browser/thread_util.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/strings/utf_string_conversions.h" +#include "net/base/net_util.h" + +namespace { + +class CefJSDialogCallbackImpl : public CefJSDialogCallback { + public: + CefJSDialogCallbackImpl( + const content::JavaScriptDialogManager::DialogClosedCallback& callback) + : callback_(callback) { + } + ~CefJSDialogCallbackImpl() override { + if (!callback_.is_null()) { + // The callback is still pending. Cancel it now. + if (CEF_CURRENTLY_ON_UIT()) { + CancelNow(callback_); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefJSDialogCallbackImpl::CancelNow, callback_)); + } + } + } + + void Continue(bool success, + const CefString& user_input) override { + if (CEF_CURRENTLY_ON_UIT()) { + if (!callback_.is_null()) { + callback_.Run(success, user_input); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefJSDialogCallbackImpl::Continue, this, success, + user_input)); + } + } + + void Disconnect() { + callback_.Reset(); + } + + private: + static void CancelNow( + const content::JavaScriptDialogManager::DialogClosedCallback& callback) { + CEF_REQUIRE_UIT(); + callback.Run(false, base::string16()); + } + + content::JavaScriptDialogManager::DialogClosedCallback callback_; + + IMPLEMENT_REFCOUNTING(CefJSDialogCallbackImpl); +}; + +} // namespace + + +CefJavaScriptDialogManager::CefJavaScriptDialogManager( + CefBrowserHostImpl* browser) + : browser_(browser) { +} + +CefJavaScriptDialogManager::~CefJavaScriptDialogManager() { +} + +void CefJavaScriptDialogManager::RunJavaScriptDialog( + content::WebContents* web_contents, + const GURL& origin_url, + const std::string& accept_lang, + content::JavaScriptMessageType message_type, + const base::string16& message_text, + const base::string16& default_prompt_text, + const DialogClosedCallback& callback, + bool* did_suppress_message) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetJSDialogHandler(); + if (handler.get()) { + *did_suppress_message = false; + + CefRefPtr callbackPtr( + new CefJSDialogCallbackImpl(callback)); + + // Execute the user callback. + bool handled = handler->OnJSDialog(browser_, origin_url.spec(), + accept_lang, + static_cast(message_type), + message_text, default_prompt_text, callbackPtr.get(), + *did_suppress_message); + if (handled) { + // Invalid combination of values. Crash sooner rather than later. + CHECK(!*did_suppress_message); + return; + } + + callbackPtr->Disconnect(); + if (*did_suppress_message) + return; + } + } + +#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK) + *did_suppress_message = false; + + if (dialog_.get()) { + // One dialog at a time, please. + *did_suppress_message = true; + return; + } + + base::string16 display_url = net::FormatUrl(origin_url, accept_lang); + + dialog_.reset(new CefJavaScriptDialog(this, + message_type, + display_url, + message_text, + default_prompt_text, + callback)); +#else + // TODO(port): implement CefJavaScriptDialog for other platforms. + *did_suppress_message = true; + return; +#endif +} + +void CefJavaScriptDialogManager::RunBeforeUnloadDialog( + content::WebContents* web_contents, + const base::string16& message_text, + bool is_reload, + const DialogClosedCallback& callback) { + if (browser_->destruction_state() >= + CefBrowserHostImpl::DESTRUCTION_STATE_ACCEPTED) { + // Currently destroying the browser. Accept the unload without showing + // the prompt. + callback.Run(true, base::string16()); + return; + } + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetJSDialogHandler(); + if (handler.get()) { + CefRefPtr callbackPtr( + new CefJSDialogCallbackImpl(callback)); + + // Execute the user callback. + bool handled = handler->OnBeforeUnloadDialog(browser_, message_text, + is_reload, callbackPtr.get()); + if (handled) + return; + + callbackPtr->Disconnect(); + } + } + +#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK) + if (dialog_.get()) { + // Seriously!? + callback.Run(true, base::string16()); + return; + } + + base::string16 new_message_text = + message_text + + base::ASCIIToUTF16("\n\nIs it OK to leave/reload this page?"); + + dialog_.reset( + new CefJavaScriptDialog(this, + content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM, + base::string16(), // display_url + new_message_text, + base::string16(), // default_prompt_text + callback)); +#else + // TODO(port): implement CefJavaScriptDialog for other platforms. + callback.Run(true, base::string16()); + return; +#endif +} + +void CefJavaScriptDialogManager::CancelActiveAndPendingDialogs( + content::WebContents* web_contents) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetJSDialogHandler(); + if (handler.get()) { + // Execute the user callback. + handler->OnResetDialogState(browser_); + } + } + +#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK) + if (dialog_.get()) { + dialog_->Cancel(); + dialog_.reset(); + } +#endif +} + +void CefJavaScriptDialogManager::WebContentsDestroyed( + content::WebContents* web_contents) { +} + +void CefJavaScriptDialogManager::DialogClosed(CefJavaScriptDialog* dialog) { +#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK) + DCHECK_EQ(dialog, dialog_.get()); + dialog_.reset(); + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetJSDialogHandler(); + if (handler.get()) + handler->OnDialogClosed(browser_); + } +#endif +} diff --git a/libcef/browser/javascript_dialog_manager.h b/libcef/browser/javascript_dialog_manager.h new file mode 100644 index 000000000..221050743 --- /dev/null +++ b/libcef/browser/javascript_dialog_manager.h @@ -0,0 +1,64 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_JAVASCRIPT_DIALOG_MANAGER_H_ +#define CEF_LIBCEF_BROWSER_JAVASCRIPT_DIALOG_MANAGER_H_ +#pragma once + +#include + +#include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" +#include "content/public/browser/javascript_dialog_manager.h" + +class CefBrowserHostImpl; +class CefJavaScriptDialog; + +class CefJavaScriptDialogManager : public content::JavaScriptDialogManager { + public: + explicit CefJavaScriptDialogManager(CefBrowserHostImpl* browser); + ~CefJavaScriptDialogManager() override; + + // JavaScriptDialogManager methods. + void RunJavaScriptDialog( + content::WebContents* web_contents, + const GURL& origin_url, + const std::string& accept_lang, + content::JavaScriptMessageType message_type, + const base::string16& message_text, + const base::string16& default_prompt_text, + const DialogClosedCallback& callback, + bool* did_suppress_message) override; + + void RunBeforeUnloadDialog( + content::WebContents* web_contents, + const base::string16& message_text, + bool is_reload, + const DialogClosedCallback& callback) override; + + void CancelActiveAndPendingDialogs( + content::WebContents* web_contents) override; + + void WebContentsDestroyed( + content::WebContents* web_contents) override; + + // Called by the CefJavaScriptDialog when it closes. + void DialogClosed(CefJavaScriptDialog* dialog); + + CefBrowserHostImpl* browser() const { return browser_; } + + private: + // This pointer is guaranteed to outlive the CefJavaScriptDialogManager. + CefBrowserHostImpl* browser_; + +#if defined(OS_MACOSX) || defined(OS_WIN) || defined(TOOLKIT_GTK) + // The dialog being shown. No queueing. + scoped_ptr dialog_; +#endif + + DISALLOW_COPY_AND_ASSIGN(CefJavaScriptDialogManager); +}; + +#endif // CEF_LIBCEF_BROWSER_JAVASCRIPT_DIALOG_MANAGER_H_ diff --git a/libcef/browser/javascript_dialog_win.cc b/libcef/browser/javascript_dialog_win.cc new file mode 100644 index 000000000..861978c2c --- /dev/null +++ b/libcef/browser/javascript_dialog_win.cc @@ -0,0 +1,228 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/javascript_dialog.h" +#include "libcef/browser/javascript_dialog_manager.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef_dll/resource.h" + +#include "base/files/file_path.h" +#include "base/path_service.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" + +class CefJavaScriptDialog; + +HHOOK CefJavaScriptDialog::msg_hook_ = NULL; +int CefJavaScriptDialog::msg_hook_user_count_ = 0; + +INT_PTR CALLBACK CefJavaScriptDialog::DialogProc(HWND dialog, + UINT message, + WPARAM wparam, + LPARAM lparam) { + switch (message) { + case WM_INITDIALOG: { + SetWindowLongPtr(dialog, DWLP_USER, static_cast(lparam)); + CefJavaScriptDialog* owner = + reinterpret_cast(lparam); + owner->dialog_win_ = dialog; + SetDlgItemText(dialog, IDC_DIALOGTEXT, owner->message_text_.c_str()); + if (owner->message_type_ == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT) + SetDlgItemText(dialog, IDC_PROMPTEDIT, + owner->default_prompt_text_.c_str()); + break; + } + case WM_CLOSE: { + CefJavaScriptDialog* owner = reinterpret_cast( + GetWindowLongPtr(dialog, DWLP_USER)); + if (owner) { + owner->Cancel(); + owner->callback_.Run(false, base::string16()); + owner->creator_->DialogClosed(owner); + + // No need for the system to call DestroyWindow() because it will be + // called by the Cancel() method. + return 0; + } + break; + } + case WM_COMMAND: { + CefJavaScriptDialog* owner = reinterpret_cast( + GetWindowLongPtr(dialog, DWLP_USER)); + base::string16 user_input; + bool finish = false; + bool result; + switch (LOWORD(wparam)) { + case IDOK: + finish = true; + result = true; + if (owner->message_type_ == content::JAVASCRIPT_MESSAGE_TYPE_PROMPT) { + size_t length = + GetWindowTextLength(GetDlgItem(dialog, IDC_PROMPTEDIT)) + 1; + if (length > 1) { + GetDlgItemText(dialog, IDC_PROMPTEDIT, + WriteInto(&user_input, length), length); + } + } + break; + case IDCANCEL: + finish = true; + result = false; + break; + } + if (finish) { + owner->Cancel(); + owner->callback_.Run(result, user_input); + owner->creator_->DialogClosed(owner); + } + break; + } + default: + return DefWindowProc(dialog, message, wparam, lparam); + } + return 0; +} + +CefJavaScriptDialog::CefJavaScriptDialog( + CefJavaScriptDialogManager* creator, + content::JavaScriptMessageType message_type, + const base::string16& display_url, + const base::string16& message_text, + const base::string16& default_prompt_text, + const content::JavaScriptDialogManager::DialogClosedCallback& callback) + : creator_(creator), + callback_(callback), + message_text_(message_text), + default_prompt_text_(default_prompt_text), + message_type_(message_type) { + InstallMessageHook(); + + int dialog_type; + if (message_type == content::JAVASCRIPT_MESSAGE_TYPE_ALERT) + dialog_type = IDD_ALERT; + else if (message_type == content::JAVASCRIPT_MESSAGE_TYPE_CONFIRM) + dialog_type = IDD_CONFIRM; + else // JAVASCRIPT_MESSAGE_TYPE_PROMPT + dialog_type = IDD_PROMPT; + + base::FilePath file_path; + HMODULE hModule = NULL; + + // Try to load the dialog from the DLL. + if (PathService::Get(base::FILE_MODULE, &file_path)) + hModule = ::GetModuleHandle(file_path.value().c_str()); + if (!hModule) + hModule = ::GetModuleHandle(NULL); + DCHECK(hModule); + + parent_win_ = GetAncestor(creator->browser()->GetWindowHandle(), GA_ROOT); + dialog_win_ = CreateDialogParam(hModule, + MAKEINTRESOURCE(dialog_type), + parent_win_, + DialogProc, + reinterpret_cast(this)); + DCHECK(dialog_win_); + + if (!display_url.empty()) { + // Add the display URL to the window title. + TCHAR text[64]; + GetWindowText(dialog_win_, text, sizeof(text)/sizeof(TCHAR)); + + base::string16 new_window_text = + text + base::ASCIIToUTF16(" - ") + display_url; + SetWindowText(dialog_win_, new_window_text.c_str()); + } + + // Disable the parent window so the user can't interact with it. + if (IsWindowEnabled(parent_win_)) + EnableWindow(parent_win_, FALSE); + + ShowWindow(dialog_win_, SW_SHOWNORMAL); +} + +CefJavaScriptDialog::~CefJavaScriptDialog() { + Cancel(); + UninstallMessageHook(); +} + +void CefJavaScriptDialog::Cancel() { + HWND parent = NULL; + + // Re-enable the parent before closing the popup to avoid focus/activation/ + // z-order issues. + if (parent_win_ && IsWindow(parent_win_) && !IsWindowEnabled(parent_win_)) { + parent = parent_win_; + EnableWindow(parent_win_, TRUE); + parent_win_ = NULL; + } + + if (dialog_win_ && IsWindow(dialog_win_)) { + SetWindowLongPtr(dialog_win_, DWLP_USER, NULL); + DestroyWindow(dialog_win_); + dialog_win_ = NULL; + } + + // Return focus to the parent window. + if (parent) + SetFocus(parent); +} + +// static +LRESULT CALLBACK CefJavaScriptDialog::GetMsgProc(int code, WPARAM wparam, + LPARAM lparam) { + // Mostly borrowed from http://support.microsoft.com/kb/q187988/ + // and http://www.codeproject.com/KB/atl/cdialogmessagehook.aspx. + LPMSG msg = reinterpret_cast(lparam); + if (code >= 0 && wparam == PM_REMOVE && + msg->message >= WM_KEYFIRST && msg->message <= WM_KEYLAST) { + HWND hwnd = GetActiveWindow(); + if (::IsWindow(hwnd) && ::IsDialogMessage(hwnd, msg)) { + // The value returned from this hookproc is ignored, and it cannot + // be used to tell Windows the message has been handled. To avoid + // further processing, convert the message to WM_NULL before + // returning. + msg->hwnd = NULL; + msg->message = WM_NULL; + msg->lParam = 0L; + msg->wParam = 0; + } + } + + // Passes the hook information to the next hook procedure in + // the current hook chain. + return ::CallNextHookEx(msg_hook_, code, wparam, lparam); +} + +// static +bool CefJavaScriptDialog::InstallMessageHook() { + msg_hook_user_count_++; + + // Make sure we only call this once. + if (msg_hook_ != NULL) + return true; + + msg_hook_ = ::SetWindowsHookEx(WH_GETMESSAGE, + &CefJavaScriptDialog::GetMsgProc, + NULL, + GetCurrentThreadId()); + DCHECK(msg_hook_ != NULL); + return msg_hook_ != NULL; +} + +// static +bool CefJavaScriptDialog::UninstallMessageHook() { + msg_hook_user_count_--; + DCHECK_GE(msg_hook_user_count_, 0); + + if (msg_hook_user_count_ > 0) + return true; + + DCHECK(msg_hook_ != NULL); + BOOL result = ::UnhookWindowsHookEx(msg_hook_); + DCHECK(result); + msg_hook_ = NULL; + + return result != FALSE; +} diff --git a/libcef/browser/media_capture_devices_dispatcher.cc b/libcef/browser/media_capture_devices_dispatcher.cc new file mode 100644 index 000000000..21fd32c4c --- /dev/null +++ b/libcef/browser/media_capture_devices_dispatcher.cc @@ -0,0 +1,128 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/media_capture_devices_dispatcher.h" + +#include "base/prefs/pref_registry_simple.h" +#include "base/prefs/pref_service.h" +#include "chrome/common/pref_names.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/media_capture_devices.h" + +using content::BrowserThread; +using content::MediaStreamDevices; + +namespace { + +const content::MediaStreamDevice* FindDefaultDeviceWithId( + const content::MediaStreamDevices& devices, + const std::string& device_id) { + if (devices.empty()) + return NULL; + + content::MediaStreamDevices::const_iterator iter = devices.begin(); + for (; iter != devices.end(); ++iter) { + if (iter->id == device_id) { + return &(*iter); + } + } + + return &(*devices.begin()); +}; + +} // namespace + + +CefMediaCaptureDevicesDispatcher* + CefMediaCaptureDevicesDispatcher::GetInstance() { + return Singleton::get(); +} + +CefMediaCaptureDevicesDispatcher::CefMediaCaptureDevicesDispatcher() {} + +CefMediaCaptureDevicesDispatcher::~CefMediaCaptureDevicesDispatcher() {} + +void CefMediaCaptureDevicesDispatcher::RegisterPrefs( + PrefRegistrySimple* registry) { + registry->RegisterStringPref(prefs::kDefaultAudioCaptureDevice, + std::string()); + registry->RegisterStringPref(prefs::kDefaultVideoCaptureDevice, + std::string()); +} + +void CefMediaCaptureDevicesDispatcher::GetDefaultDevices( + PrefService* prefs, + bool audio, + bool video, + content::MediaStreamDevices* devices) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK(audio || video); + + std::string default_device; + if (audio) { + default_device = prefs->GetString(prefs::kDefaultAudioCaptureDevice); + GetRequestedDevice(default_device, true, false, devices); + } + + if (video) { + default_device = prefs->GetString(prefs::kDefaultVideoCaptureDevice); + GetRequestedDevice(default_device, false, true, devices); + } +} + +void CefMediaCaptureDevicesDispatcher::GetRequestedDevice( + const std::string& requested_device_id, + bool audio, + bool video, + content::MediaStreamDevices* devices) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK(audio || video); + + if (audio) { + const content::MediaStreamDevices& audio_devices = GetAudioCaptureDevices(); + const content::MediaStreamDevice* const device = + FindDefaultDeviceWithId(audio_devices, requested_device_id); + if (device) + devices->push_back(*device); + } + if (video) { + const content::MediaStreamDevices& video_devices = GetVideoCaptureDevices(); + const content::MediaStreamDevice* const device = + FindDefaultDeviceWithId(video_devices, requested_device_id); + if (device) + devices->push_back(*device); + } +} + +void CefMediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged() { +} + +void CefMediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged() { +} + +void CefMediaCaptureDevicesDispatcher::OnMediaRequestStateChanged( + int render_process_id, + int render_frame_id, + int page_request_id, + const GURL& security_origin, + content::MediaStreamType stream_type, + content::MediaRequestState state) { +} + +void CefMediaCaptureDevicesDispatcher::OnCreatingAudioStream( + int render_process_id, + int render_view_id) { +} + +const MediaStreamDevices& +CefMediaCaptureDevicesDispatcher::GetAudioCaptureDevices() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + return content::MediaCaptureDevices::GetInstance()->GetAudioCaptureDevices(); +} + +const MediaStreamDevices& +CefMediaCaptureDevicesDispatcher::GetVideoCaptureDevices() { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + return content::MediaCaptureDevices::GetInstance()->GetVideoCaptureDevices(); +} diff --git a/libcef/browser/media_capture_devices_dispatcher.h b/libcef/browser/media_capture_devices_dispatcher.h new file mode 100644 index 000000000..cae0d3b0e --- /dev/null +++ b/libcef/browser/media_capture_devices_dispatcher.h @@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_ +#define CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_ + +#include "base/callback.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/singleton.h" +#include "base/observer_list.h" +#include "content/public/browser/media_observer.h" +#include "content/public/common/media_stream_request.h" + +class PrefRegistrySimple; +class PrefService; + +// This singleton is used to receive updates about media events from the content +// layer. Based on chrome/browser/media/media_capture_devices_dispatcher.[h|cc]. +class CefMediaCaptureDevicesDispatcher : public content::MediaObserver { + public: + static CefMediaCaptureDevicesDispatcher* GetInstance(); + + // Registers the preferences related to Media Stream default devices. + static void RegisterPrefs(PrefRegistrySimple* registry); + + // Helper to get the default devices which can be used by the media request, + // if the return list is empty, it means there is no available device on the + // OS. Called on the UI thread. + void GetDefaultDevices(PrefService* prefs, + bool audio, + bool video, + content::MediaStreamDevices* devices); + + // Helper for picking the device that was requested for an OpenDevice request. + // If the device requested is not available it will revert to using the first + // available one instead or will return an empty list if no devices of the + // requested kind are present. Called on the UI thread. + void GetRequestedDevice(const std::string& requested_device_id, + bool audio, + bool video, + content::MediaStreamDevices* devices); + + // Overridden from content::MediaObserver: + void OnAudioCaptureDevicesChanged() override; + void OnVideoCaptureDevicesChanged() override; + void OnMediaRequestStateChanged( + int render_process_id, + int render_frame_id, + int page_request_id, + const GURL& security_origin, + content::MediaStreamType stream_type, + content::MediaRequestState state) override; + void OnCreatingAudioStream(int render_process_id, + int render_view_id) override; + + private: + friend struct DefaultSingletonTraits; + + CefMediaCaptureDevicesDispatcher(); + ~CefMediaCaptureDevicesDispatcher() override; + + const content::MediaStreamDevices& GetAudioCaptureDevices(); + const content::MediaStreamDevices& GetVideoCaptureDevices(); +}; + +#endif // CEF_LIBCEF_BROWSER_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_ diff --git a/libcef/browser/menu_creator.cc b/libcef/browser/menu_creator.cc new file mode 100644 index 000000000..26f787214 --- /dev/null +++ b/libcef/browser/menu_creator.cc @@ -0,0 +1,357 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/menu_creator.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/context_menu_params_impl.h" +#include "libcef/common/content_client.h" + +#include "base/compiler_specific.h" +#include "base/logging.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/render_widget_host_view.h" +#include "grit/cef_strings.h" + +#if defined(OS_WIN) +#include "libcef/browser/menu_creator_runner_win.h" +#elif defined(OS_MACOSX) +#include "libcef/browser/menu_creator_runner_mac.h" +#elif defined(OS_LINUX) +#include "libcef/browser/menu_creator_runner_linux.h" +#endif + +namespace { + +CefString GetLabel(int message_id) { + base::string16 label = + CefContentClient::Get()->GetLocalizedString(message_id); + DCHECK(!label.empty()); + return label; +} + +} // namespace + +CefMenuCreator::CefMenuCreator(CefBrowserHostImpl* browser) + : browser_(browser) { + model_ = new CefMenuModelImpl(this); +} + +CefMenuCreator::~CefMenuCreator() { + // The model may outlive the delegate if the context menu is visible when the + // application is closed. + model_->set_delegate(NULL); +} + +bool CefMenuCreator::IsShowingContextMenu() { + content::WebContents* web_contents = browser_->GetWebContents(); + if (!web_contents) + return false; + content::RenderWidgetHostView* view = web_contents->GetRenderWidgetHostView(); + return (view && view->IsShowingContextMenu()); +} + +bool CefMenuCreator::CreateContextMenu( + const content::ContextMenuParams& params) { + if (!CreateRunner()) + return true; + + // The renderer may send the "show context menu" message multiple times, one + // for each right click mouse event it receives. Normally, this doesn't happen + // because mouse events are not forwarded once the context menu is showing. + // However, there's a race - the context menu may not yet be showing when + // the second mouse event arrives. In this case, |HandleContextMenu()| will + // get called multiple times - if so, don't create another context menu. + // TODO(asvitkine): Fix the renderer so that it doesn't do this. + if (IsShowingContextMenu()) + return true; + + params_ = params; + model_->Clear(); + + // Create the default menu model. + CreateDefaultModel(); + + // Give the client a chance to modify the model. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = + client->GetContextMenuHandler(); + if (handler.get()) { + CefRefPtr paramsPtr( + new CefContextMenuParamsImpl(¶ms_)); + + handler->OnBeforeContextMenu(browser_, + browser_->GetFocusedFrame(), + paramsPtr.get(), + model_.get()); + + // Do not keep references to the parameters in the callback. + paramsPtr->Detach(NULL); + DCHECK(paramsPtr->HasOneRef()); + DCHECK(model_->VerifyRefCount()); + + // Menu is empty so notify the client and return. + if (model_->GetCount() == 0) { + MenuClosed(model_); + return true; + } + } + } + + return runner_->RunContextMenu(this); +} + +void CefMenuCreator::CancelContextMenu() { + if (IsShowingContextMenu()) + runner_->CancelContextMenu(); +} + +bool CefMenuCreator::CreateRunner() { + if (!runner_.get()) { + // Create the menu runner. +#if defined(OS_WIN) + runner_.reset(new CefMenuCreatorRunnerWin); +#elif defined(OS_MACOSX) + runner_.reset(new CefMenuCreatorRunnerMac); +#elif defined(OS_LINUX) + runner_.reset(new CefMenuCreatorRunnerLinux); +#else + // Need an implementation. + NOTREACHED(); +#endif + } + return (runner_.get() != NULL); +} + +void CefMenuCreator::ExecuteCommand(CefRefPtr source, + int command_id, + cef_event_flags_t event_flags) { + // Give the client a chance to handle the command. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = + client->GetContextMenuHandler(); + if (handler.get()) { + CefRefPtr paramsPtr( + new CefContextMenuParamsImpl(¶ms_)); + + bool handled = handler->OnContextMenuCommand( + browser_, + browser_->GetFocusedFrame(), + paramsPtr.get(), + command_id, + event_flags); + + // Do not keep references to the parameters in the callback. + paramsPtr->Detach(NULL); + DCHECK(paramsPtr->HasOneRef()); + + if (handled) + return; + } + } + + // Execute the default command handling. + ExecuteDefaultCommand(command_id); +} + +void CefMenuCreator::MenuWillShow(CefRefPtr source) { + // May be called for sub-menus as well. + if (source.get() != model_.get()) + return; + + content::WebContents* web_contents = browser_->GetWebContents(); + if (!web_contents) + return; + + // Notify the host before showing the context menu. + content::RenderWidgetHostView* view = web_contents->GetRenderWidgetHostView(); + if (view) + view->SetShowingContextMenu(true); +} + +void CefMenuCreator::MenuClosed(CefRefPtr source) { + // May be called for sub-menus as well. + if (source.get() != model_.get()) + return; + + // Notify the client. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = + client->GetContextMenuHandler(); + if (handler.get()) { + handler->OnContextMenuDismissed(browser_, browser_->GetFocusedFrame()); + } + } + + if (IsShowingContextMenu()) { + // Notify the host after closing the context menu. + content::WebContents* web_contents = browser_->GetWebContents(); + content::RenderWidgetHostView* view = + web_contents->GetRenderWidgetHostView(); + if (view) + view->SetShowingContextMenu(false); + web_contents->NotifyContextMenuClosed(params_.custom_context); + } +} + +bool CefMenuCreator::FormatLabel(base::string16& label) { + return runner_->FormatLabel(label); +} + +void CefMenuCreator::CreateDefaultModel() { + if (params_.is_editable) { + // Editable node. + model_->AddItem(MENU_ID_UNDO, GetLabel(IDS_MENU_UNDO)); + model_->AddItem(MENU_ID_REDO, GetLabel(IDS_MENU_REDO)); + + model_->AddSeparator(); + model_->AddItem(MENU_ID_CUT, GetLabel(IDS_MENU_CUT)); + model_->AddItem(MENU_ID_COPY, GetLabel(IDS_MENU_COPY)); + model_->AddItem(MENU_ID_PASTE, GetLabel(IDS_MENU_PASTE)); + model_->AddItem(MENU_ID_DELETE, GetLabel(IDS_MENU_DELETE)); + + model_->AddSeparator(); + model_->AddItem(MENU_ID_SELECT_ALL, GetLabel(IDS_MENU_SELECT_ALL)); + + if (!(params_.edit_flags & CM_EDITFLAG_CAN_UNDO)) + model_->SetEnabled(MENU_ID_UNDO, false); + if (!(params_.edit_flags & CM_EDITFLAG_CAN_REDO)) + model_->SetEnabled(MENU_ID_REDO, false); + if (!(params_.edit_flags & CM_EDITFLAG_CAN_CUT)) + model_->SetEnabled(MENU_ID_CUT, false); + if (!(params_.edit_flags & CM_EDITFLAG_CAN_COPY)) + model_->SetEnabled(MENU_ID_COPY, false); + if (!(params_.edit_flags & CM_EDITFLAG_CAN_PASTE)) + model_->SetEnabled(MENU_ID_PASTE, false); + if (!(params_.edit_flags & CM_EDITFLAG_CAN_DELETE)) + model_->SetEnabled(MENU_ID_DELETE, false); + if (!(params_.edit_flags & CM_EDITFLAG_CAN_SELECT_ALL)) + model_->SetEnabled(MENU_ID_SELECT_ALL, false); + + if(!params_.misspelled_word.empty()) { + // Always add a separator before the list of dictionary suggestions or + // "No spelling suggestions". + model_->AddSeparator(); + + if (!params_.dictionary_suggestions.empty()) { + for (size_t i = 0; + i < params_.dictionary_suggestions.size() && + MENU_ID_SPELLCHECK_SUGGESTION_0 + i <= + MENU_ID_SPELLCHECK_SUGGESTION_LAST; + ++i) { + model_->AddItem(MENU_ID_SPELLCHECK_SUGGESTION_0 + static_cast(i), + params_.dictionary_suggestions[i].c_str()); + } + + // When there are dictionary suggestions add a separator before "Add to + // dictionary". + model_->AddSeparator(); + } else { + model_->AddItem( + MENU_ID_NO_SPELLING_SUGGESTIONS, + GetLabel(IDS_CONTENT_CONTEXT_NO_SPELLING_SUGGESTIONS)); + model_->SetEnabled(MENU_ID_NO_SPELLING_SUGGESTIONS, false); + } + + model_->AddItem( + MENU_ID_ADD_TO_DICTIONARY, + GetLabel(IDS_CONTENT_CONTEXT_ADD_TO_DICTIONARY)); + } + } else if (!params_.selection_text.empty()) { + // Something is selected. + model_->AddItem(MENU_ID_COPY, GetLabel(IDS_MENU_COPY)); + } else if (!params_.page_url.is_empty() || !params_.frame_url.is_empty()) { + // Page or frame. + model_->AddItem(MENU_ID_BACK, GetLabel(IDS_MENU_BACK)); + model_->AddItem(MENU_ID_FORWARD, GetLabel(IDS_MENU_FORWARD)); + + model_->AddSeparator(); + model_->AddItem(MENU_ID_PRINT, GetLabel(IDS_MENU_PRINT)); + model_->AddItem(MENU_ID_VIEW_SOURCE, GetLabel(IDS_MENU_VIEW_SOURCE)); + + if (!browser_->CanGoBack()) + model_->SetEnabled(MENU_ID_BACK, false); + if (!browser_->CanGoForward()) + model_->SetEnabled(MENU_ID_FORWARD, false); + } +} + +void CefMenuCreator::ExecuteDefaultCommand(int command_id) { + // If the user chose a replacement word for a misspelling, replace it here. + if (command_id >= MENU_ID_SPELLCHECK_SUGGESTION_0 && + command_id <= MENU_ID_SPELLCHECK_SUGGESTION_LAST) { + const size_t suggestion_index = + static_cast(command_id) - MENU_ID_SPELLCHECK_SUGGESTION_0; + if (suggestion_index < params_.dictionary_suggestions.size()) { + browser_->ReplaceMisspelling( + params_.dictionary_suggestions[suggestion_index]); + } + return; + } + + switch (command_id) { + // Navigation. + case MENU_ID_BACK: + browser_->GoBack(); + break; + case MENU_ID_FORWARD: + browser_->GoForward(); + break; + case MENU_ID_RELOAD: + browser_->Reload(); + break; + case MENU_ID_RELOAD_NOCACHE: + browser_->ReloadIgnoreCache(); + break; + case MENU_ID_STOPLOAD: + browser_->StopLoad(); + break; + + // Editing. + case MENU_ID_UNDO: + browser_->GetFocusedFrame()->Undo(); + break; + case MENU_ID_REDO: + browser_->GetFocusedFrame()->Redo(); + break; + case MENU_ID_CUT: + browser_->GetFocusedFrame()->Cut(); + break; + case MENU_ID_COPY: + browser_->GetFocusedFrame()->Copy(); + break; + case MENU_ID_PASTE: + browser_->GetFocusedFrame()->Paste(); + break; + case MENU_ID_DELETE: + browser_->GetFocusedFrame()->Delete(); + break; + case MENU_ID_SELECT_ALL: + browser_->GetFocusedFrame()->SelectAll(); + break; + + // Miscellaneous. + case MENU_ID_FIND: + // TODO(cef): Implement. + NOTIMPLEMENTED(); + break; + case MENU_ID_PRINT: + browser_->Print(); + break; + case MENU_ID_VIEW_SOURCE: + browser_->GetFocusedFrame()->ViewSource(); + break; + + // Spell checking. + case MENU_ID_ADD_TO_DICTIONARY: + browser_->GetHost()->AddWordToDictionary(params_.misspelled_word); + break; + + default: + break; + } +} diff --git a/libcef/browser/menu_creator.h b/libcef/browser/menu_creator.h new file mode 100644 index 000000000..732415053 --- /dev/null +++ b/libcef/browser/menu_creator.h @@ -0,0 +1,72 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_MENU_MANAGER_H_ +#define CEF_LIBCEF_BROWSER_MENU_MANAGER_H_ +#pragma once + +#include "libcef/browser/menu_model_impl.h" + +#include "base/memory/scoped_ptr.h" +#include "content/public/common/context_menu_params.h" + +namespace content { +class RenderFrameHost; +}; + +class CefBrowserHostImpl; + +class CefMenuCreator : public CefMenuModelImpl::Delegate { + public: + // Used for OS-specific menu implementations. + class Runner { + public: + virtual ~Runner() {} + virtual bool RunContextMenu(CefMenuCreator* manager) =0; + virtual void CancelContextMenu() {} + virtual bool FormatLabel(base::string16& label) { return false; } + }; + + explicit CefMenuCreator(CefBrowserHostImpl* browser); + ~CefMenuCreator() override; + + // Returns true if the context menu is currently showing. + bool IsShowingContextMenu(); + + // Create the context menu. + bool CreateContextMenu(const content::ContextMenuParams& params); + void CancelContextMenu(); + + CefBrowserHostImpl* browser() { return browser_; } + ui::MenuModel* model() { return model_->model(); } + const content::ContextMenuParams& params() const { return params_; } + + private: + // Create the menu runner if it doesn't already exist. + bool CreateRunner(); + + // CefMenuModelImpl::Delegate methods. + void ExecuteCommand(CefRefPtr source, + int command_id, + cef_event_flags_t event_flags) override; + void MenuWillShow(CefRefPtr source) override; + void MenuClosed(CefRefPtr source) override; + bool FormatLabel(base::string16& label) override; + + // Create the default menu model. + void CreateDefaultModel(); + // Execute the default command handling. + void ExecuteDefaultCommand(int command_id); + + // CefBrowserHostImpl pointer is guaranteed to outlive this object. + CefBrowserHostImpl* browser_; + + CefRefPtr model_; + content::ContextMenuParams params_; + scoped_ptr runner_; + + DISALLOW_COPY_AND_ASSIGN(CefMenuCreator); +}; + +#endif // CEF_LIBCEF_BROWSER_MENU_MANAGER_H_ diff --git a/libcef/browser/menu_creator_runner_linux.cc b/libcef/browser/menu_creator_runner_linux.cc new file mode 100644 index 000000000..22a51fcd8 --- /dev/null +++ b/libcef/browser/menu_creator_runner_linux.cc @@ -0,0 +1,72 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +#include "libcef/browser/menu_creator_runner_linux.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/window_x11.h" + +#include "base/compiler_specific.h" +#include "base/strings/string_util.h" +#include "ui/aura/window.h" +#include "ui/gfx/geometry/point.h" + +CefMenuCreatorRunnerLinux::CefMenuCreatorRunnerLinux() { +} + +CefMenuCreatorRunnerLinux::~CefMenuCreatorRunnerLinux() { +} + +bool CefMenuCreatorRunnerLinux::RunContextMenu(CefMenuCreator* manager) { + menu_.reset( + new views::MenuRunner(manager->model(), views::MenuRunner::CONTEXT_MENU)); + + gfx::Point screen_point; + + if (manager->browser()->IsWindowless()) { + CefRefPtr client = manager->browser()->GetClient(); + if (!client.get()) + return false; + + CefRefPtr handler = client->GetRenderHandler(); + if (!handler.get()) + return false; + + int screenX = 0, screenY = 0; + if (!handler->GetScreenPoint(manager->browser(), + manager->params().x, manager->params().y, + screenX, screenY)) { + return false; + } + + screen_point = gfx::Point(screenX, screenY); + } else { + // We can't use aura::Window::GetBoundsInScreen on Linux because it will + // return bounds from DesktopWindowTreeHostX11 which in our case is relative + // to the parent window instead of the root window (screen). + const gfx::Rect& bounds_in_screen = + manager->browser()->window_x11()->GetBoundsInScreen(); + screen_point = gfx::Point(bounds_in_screen.x() + manager->params().x, + bounds_in_screen.y() + manager->params().y); + } + + views::MenuRunner::RunResult result = + menu_->RunMenuAt(manager->browser()->window_widget(), + NULL, gfx::Rect(screen_point, gfx::Size()), + views::MENU_ANCHOR_TOPRIGHT, + ui::MENU_SOURCE_NONE); + ALLOW_UNUSED_LOCAL(result); + + return true; +} + +void CefMenuCreatorRunnerLinux::CancelContextMenu() { + if (menu_) + menu_->Cancel(); +} + +bool CefMenuCreatorRunnerLinux::FormatLabel(base::string16& label) { + // Remove the accelerator indicator (&) from label strings. + const char16 replace[] = {L'&', 0}; + return base::ReplaceChars(label, replace, base::string16(), &label); +} diff --git a/libcef/browser/menu_creator_runner_linux.h b/libcef/browser/menu_creator_runner_linux.h new file mode 100644 index 000000000..4d00bc0d0 --- /dev/null +++ b/libcef/browser/menu_creator_runner_linux.h @@ -0,0 +1,28 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_LINUX_H_ +#define CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_LINUX_H_ +#pragma once + +#include "libcef/browser/menu_creator.h" + +#include "base/memory/scoped_ptr.h" +#include "ui/views/controls/menu/menu_runner.h" + +class CefMenuCreatorRunnerLinux: public CefMenuCreator::Runner { + public: + CefMenuCreatorRunnerLinux(); + ~CefMenuCreatorRunnerLinux() override; + + // CefMemoryManager::Runner methods. + bool RunContextMenu(CefMenuCreator* manager) override; + void CancelContextMenu() override; + bool FormatLabel(base::string16& label) override; + + private: + scoped_ptr menu_; +}; + +#endif // CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_LINUX_H_ diff --git a/libcef/browser/menu_creator_runner_mac.h b/libcef/browser/menu_creator_runner_mac.h new file mode 100644 index 000000000..dc7f8c50a --- /dev/null +++ b/libcef/browser/menu_creator_runner_mac.h @@ -0,0 +1,29 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_MAC_H_ +#define CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_MAC_H_ +#pragma once + +#include "libcef/browser/menu_creator.h" + +#if __OBJC__ +@class MenuController; +#else +class MenuController; +#endif + +class CefMenuCreatorRunnerMac : public CefMenuCreator::Runner { + public: + CefMenuCreatorRunnerMac(); + ~CefMenuCreatorRunnerMac() override; + + // CefMemoryManager::Runner methods. + bool RunContextMenu(CefMenuCreator* manager) override; + + private: + MenuController* menu_controller_; +}; + +#endif // CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_MAC_H_ diff --git a/libcef/browser/menu_creator_runner_mac.mm b/libcef/browser/menu_creator_runner_mac.mm new file mode 100644 index 000000000..151d80042 --- /dev/null +++ b/libcef/browser/menu_creator_runner_mac.mm @@ -0,0 +1,94 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/menu_creator_runner_mac.h" +#include "libcef/browser/browser_host_impl.h" + +#include "base/message_loop/message_loop.h" +#include "base/compiler_specific.h" +#import "base/mac/scoped_sending_event.h" +#import "ui/base/cocoa/menu_controller.h" + +CefMenuCreatorRunnerMac::CefMenuCreatorRunnerMac() + : menu_controller_(nil) { +} + +CefMenuCreatorRunnerMac::~CefMenuCreatorRunnerMac() { + if (menu_controller_ != nil) + [menu_controller_ release]; +} + +bool CefMenuCreatorRunnerMac::RunContextMenu(CefMenuCreator* manager) { + // Create a menu controller based on the model. + if (menu_controller_ != nil) + [menu_controller_ release]; + menu_controller_ = + [[MenuController alloc] initWithModel:manager->model() + useWithPopUpButtonCell:NO]; + + NSView* parent_view = + manager->browser()->GetWebContents()->GetContentNativeView(); + + // Synthesize an event for the click, as there is no certainty that + // [NSApp currentEvent] will return a valid event. + NSEvent* currentEvent = [NSApp currentEvent]; + NSWindow* window = [parent_view window]; + + NSPoint position = [window mouseLocationOutsideOfEventStream]; + + NSTimeInterval eventTime = [currentEvent timestamp]; + NSEvent* clickEvent = [NSEvent mouseEventWithType:NSRightMouseDown + location:position + modifierFlags:NSRightMouseDownMask + timestamp:eventTime + windowNumber:[window windowNumber] + context:nil + eventNumber:0 + clickCount:1 + pressure:1.0]; + + { + // Make sure events can be pumped while the menu is up. + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + + // One of the events that could be pumped is |window.close()|. + // User-initiated event-tracking loops protect against this by + // setting flags in -[CrApplication sendEvent:], but since + // web-content menus are initiated by IPC message the setup has to + // be done manually. + base::mac::ScopedSendingEvent sendingEventScoper; + + // Show the menu. Blocks until the menu is dismissed. + if (manager->browser()->IsWindowless()) { + // Showing the menu in OSR is pretty much self contained, only using + // the initialized menu_controller_ in this function, and the scoped + // variables in this block. + int screenX = 0, screenY = 0; + CefRefPtr handler = + manager->browser()->GetClient()->GetRenderHandler(); + if (!handler->GetScreenPoint(manager->browser(), + manager->params().x, manager->params().y, + screenX, screenY)) { + return false; + } + + // Don't show the menu unless there is a parent native window to tie it to + if (!manager->browser()->GetWindowHandle()) + return false; + + NSPoint screen_position = + NSPointFromCGPoint(gfx::Point(screenX, screenY).ToCGPoint()); + [[menu_controller_ menu] popUpMenuPositioningItem:nil + atLocation:screen_position + inView:nil]; + } else { + [NSMenu popUpContextMenu:[menu_controller_ menu] + withEvent:clickEvent + forView:parent_view]; + } + } + + return true; +} diff --git a/libcef/browser/menu_creator_runner_win.cc b/libcef/browser/menu_creator_runner_win.cc new file mode 100644 index 000000000..5ad234bc6 --- /dev/null +++ b/libcef/browser/menu_creator_runner_win.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/menu_creator_runner_win.h" +#include "libcef/browser/browser_host_impl.h" + +#include "base/message_loop/message_loop.h" +#include "ui/aura/window.h" +#include "ui/gfx/geometry/point.h" +#include "ui/views/controls/menu/menu_2.h" + +CefMenuCreatorRunnerWin::CefMenuCreatorRunnerWin() { +} + +bool CefMenuCreatorRunnerWin::RunContextMenu(CefMenuCreator* manager) { + // Create a menu based on the model. + menu_.reset(new views::NativeMenuWin(manager->model(), NULL)); + menu_->Rebuild(NULL); + + // Make sure events can be pumped while the menu is up. + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + + gfx::Point screen_point; + + if (manager->browser()->IsWindowless()) { + CefRefPtr client = manager->browser()->GetClient(); + if (!client.get()) + return false; + + CefRefPtr handler = client->GetRenderHandler(); + if (!handler.get()) + return false; + + int screenX = 0, screenY = 0; + if (!handler->GetScreenPoint(manager->browser(), + manager->params().x, manager->params().y, + screenX, screenY)) { + return false; + } + + screen_point = gfx::Point(screenX, screenY); + } else { + aura::Window* window = manager->browser()->GetContentView(); + const gfx::Rect& bounds_in_screen = window->GetBoundsInScreen(); + screen_point = gfx::Point(bounds_in_screen.x() + manager->params().x, + bounds_in_screen.y() + manager->params().y); + } + + // Show the menu. Blocks until the menu is dismissed. + menu_->RunMenuAt(screen_point, views::Menu2::ALIGN_TOPLEFT); + + return true; +} diff --git a/libcef/browser/menu_creator_runner_win.h b/libcef/browser/menu_creator_runner_win.h new file mode 100644 index 000000000..1e4b4e304 --- /dev/null +++ b/libcef/browser/menu_creator_runner_win.h @@ -0,0 +1,25 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_WIN_H_ +#define CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_WIN_H_ +#pragma once + +#include "libcef/browser/menu_creator.h" + +#include "base/memory/scoped_ptr.h" +#include "ui/views/controls/menu/native_menu_win.h" + +class CefMenuCreatorRunnerWin : public CefMenuCreator::Runner { + public: + CefMenuCreatorRunnerWin(); + + // CefMemoryManager::Runner methods. + bool RunContextMenu(CefMenuCreator* manager) override; + + private: + scoped_ptr menu_; +}; + +#endif // CEF_LIBCEF_BROWSER_MENU_MANAGER_RUNNER_WIN_H_ diff --git a/libcef/browser/menu_model_impl.cc b/libcef/browser/menu_model_impl.cc new file mode 100644 index 000000000..a847ffc4c --- /dev/null +++ b/libcef/browser/menu_model_impl.cc @@ -0,0 +1,703 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/menu_model_impl.h" + +#include + +#include "base/bind.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "ui/base/accelerators/accelerator.h" + +namespace { + +const int kSeparatorId = -1; + +// A simple MenuModel implementation that delegates to CefMenuModelImpl. +class CefSimpleMenuModel : public ui::MenuModel { + public: + // The Delegate can be NULL, though if it is items can't be checked or + // disabled. + explicit CefSimpleMenuModel(CefMenuModelImpl* impl) + : impl_(impl), + menu_model_delegate_(NULL) { + } + + // MenuModel methods. + bool HasIcons() const override { + return false; + } + + int GetItemCount() const override { + return impl_->GetCount(); + } + + ItemType GetTypeAt(int index) const override { + switch (impl_->GetTypeAt(index)) { + case MENUITEMTYPE_COMMAND: + return TYPE_COMMAND; + case MENUITEMTYPE_CHECK: + return TYPE_CHECK; + case MENUITEMTYPE_RADIO: + return TYPE_RADIO; + case MENUITEMTYPE_SEPARATOR: + return TYPE_SEPARATOR; + case MENUITEMTYPE_SUBMENU: + return TYPE_SUBMENU; + default: + NOTREACHED(); + return TYPE_COMMAND; + } + } + + ui::MenuSeparatorType GetSeparatorTypeAt(int index) const override { + return ui::NORMAL_SEPARATOR; + } + + int GetCommandIdAt(int index) const override { + return impl_->GetCommandIdAt(index); + } + + base::string16 GetLabelAt(int index) const override { + return impl_->GetFormattedLabelAt(index); + } + + bool IsItemDynamicAt(int index) const override { + return false; + } + + bool GetAcceleratorAt(int index, + ui::Accelerator* accelerator) const override { + int key_code = 0; + bool shift_pressed = false; + bool ctrl_pressed = false; + bool alt_pressed = false; + if (impl_->GetAcceleratorAt(index, key_code, shift_pressed, ctrl_pressed, + alt_pressed)) { + int modifiers = 0; + if (shift_pressed) + modifiers |= ui::EF_SHIFT_DOWN; + if (ctrl_pressed) + modifiers |= ui::EF_CONTROL_DOWN; + if (alt_pressed) + modifiers |= ui::EF_ALT_DOWN; + + *accelerator = ui::Accelerator(static_cast(key_code), + modifiers); + return true; + } + return false; + } + + bool IsItemCheckedAt(int index) const override { + return impl_->IsCheckedAt(index); + } + + int GetGroupIdAt(int index) const override { + return impl_->GetGroupIdAt(index); + } + + bool GetIconAt(int index, gfx::Image* icon) override { + return false; + } + + ui::ButtonMenuItemModel* GetButtonMenuItemAt( + int index) const override { + return NULL; + } + + bool IsEnabledAt(int index) const override { + return impl_->IsEnabledAt(index); + } + + bool IsVisibleAt(int index) const override { + return impl_->IsVisibleAt(index); + } + + void HighlightChangedTo(int index) override { + } + + void ActivatedAt(int index) override { + ActivatedAt(index, 0); + } + + void ActivatedAt(int index, int event_flags) override { + impl_->ActivatedAt(index, static_cast(event_flags)); + } + + MenuModel* GetSubmenuModelAt(int index) const override { + CefRefPtr submenu = impl_->GetSubMenuAt(index); + if (submenu.get()) + return static_cast(submenu.get())->model(); + return NULL; + } + + void MenuWillShow() override { + impl_->MenuWillShow(); + } + + void MenuClosed() override { + impl_->MenuClosed(); + } + + void SetMenuModelDelegate( + ui::MenuModelDelegate* menu_model_delegate) override { + menu_model_delegate_ = menu_model_delegate; + } + + ui::MenuModelDelegate* GetMenuModelDelegate() const override { + return menu_model_delegate_; + } + + private: + CefMenuModelImpl* impl_; + ui::MenuModelDelegate* menu_model_delegate_; + + DISALLOW_COPY_AND_ASSIGN(CefSimpleMenuModel); +}; + +} // namespace + + +struct CefMenuModelImpl::Item { + Item(cef_menu_item_type_t type, + int command_id, + const CefString& label, + int group_id) + : type_(type), + command_id_(command_id), + label_(label), + group_id_(group_id), + enabled_(true), + visible_(true), + checked_(false), + has_accelerator_(false), + key_code_(0), + shift_pressed_(false), + ctrl_pressed_(false), + alt_pressed_(false) { + } + + // Basic information. + cef_menu_item_type_t type_; + int command_id_; + CefString label_; + int group_id_; + CefRefPtr submenu_; + + // State information. + bool enabled_; + bool visible_; + bool checked_; + + // Accelerator information. + bool has_accelerator_; + int key_code_; + bool shift_pressed_; + bool ctrl_pressed_; + bool alt_pressed_; +}; + + +CefMenuModelImpl::CefMenuModelImpl(Delegate* delegate) + : supported_thread_id_(base::PlatformThread::CurrentId()), + delegate_(delegate) { + model_.reset(new CefSimpleMenuModel(this)); +} + +CefMenuModelImpl::~CefMenuModelImpl() { +} + +bool CefMenuModelImpl::Clear() { + if (!VerifyContext()) + return false; + + items_.clear(); + return true; +} + +int CefMenuModelImpl::GetCount() { + if (!VerifyContext()) + return 0; + + return static_cast(items_.size()); +} + +bool CefMenuModelImpl::AddSeparator() { + if (!VerifyContext()) + return false; + + AppendItem(Item(MENUITEMTYPE_SEPARATOR, kSeparatorId, CefString(), -1)); + return true; +} + +bool CefMenuModelImpl::AddItem(int command_id, const CefString& label) { + if (!VerifyContext()) + return false; + + AppendItem(Item(MENUITEMTYPE_COMMAND, command_id, label, -1)); + return true; +} + +bool CefMenuModelImpl::AddCheckItem(int command_id, const CefString& label) { + if (!VerifyContext()) + return false; + + AppendItem(Item(MENUITEMTYPE_CHECK, command_id, label, -1)); + return true; +} + +bool CefMenuModelImpl::AddRadioItem(int command_id, const CefString& label, + int group_id) { + if (!VerifyContext()) + return false; + + AppendItem(Item(MENUITEMTYPE_RADIO, command_id, label, group_id)); + return true; +} + +CefRefPtr CefMenuModelImpl::AddSubMenu(int command_id, + const CefString& label) { + if (!VerifyContext()) + return NULL; + + Item item(MENUITEMTYPE_SUBMENU, command_id, label, -1); + item.submenu_ = new CefMenuModelImpl(delegate_); + AppendItem(item); + return item.submenu_.get(); +} + +bool CefMenuModelImpl::InsertSeparatorAt(int index) { + if (!VerifyContext()) + return false; + + InsertItemAt(Item(MENUITEMTYPE_SEPARATOR, kSeparatorId, CefString(), -1), + index); + return true; +} + +bool CefMenuModelImpl::InsertItemAt(int index, int command_id, + const CefString& label) { + if (!VerifyContext()) + return false; + + InsertItemAt(Item(MENUITEMTYPE_COMMAND, command_id, label, -1), index); + return true; +} + +bool CefMenuModelImpl::InsertCheckItemAt(int index, int command_id, + const CefString& label) { + if (!VerifyContext()) + return false; + + InsertItemAt(Item(MENUITEMTYPE_CHECK, command_id, label, -1), index); + return true; +} + +bool CefMenuModelImpl::InsertRadioItemAt(int index, int command_id, + const CefString& label, int group_id) { + if (!VerifyContext()) + return false; + + InsertItemAt(Item(MENUITEMTYPE_RADIO, command_id, label, -1), index); + return true; +} + +CefRefPtr CefMenuModelImpl::InsertSubMenuAt( + int index, int command_id, const CefString& label) { + if (!VerifyContext()) + return NULL; + + Item item(MENUITEMTYPE_SUBMENU, command_id, label, -1); + item.submenu_ = new CefMenuModelImpl(delegate_); + InsertItemAt(item, index); + return item.submenu_.get(); +} + +bool CefMenuModelImpl::Remove(int command_id) { + return RemoveAt(GetIndexOf(command_id)); +} + +bool CefMenuModelImpl::RemoveAt(int index) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_.erase(items_.begin()+index); + return true; + } + return false; +} + +int CefMenuModelImpl::GetIndexOf(int command_id) { + if (!VerifyContext()) + return -1; + + for (ItemVector::iterator i = items_.begin(); i != items_.end(); ++i) { + if ((*i).command_id_ == command_id) { + return static_cast(std::distance(items_.begin(), i)); + } + } + return -1; +} + +int CefMenuModelImpl::GetCommandIdAt(int index) { + if (!VerifyContext()) + return -1; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].command_id_; + return -1; +} + +bool CefMenuModelImpl::SetCommandIdAt(int index, int command_id) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_[index].command_id_ = command_id; + return true; + } + return false; +} + +CefString CefMenuModelImpl::GetLabel(int command_id) { + return GetLabelAt(GetIndexOf(command_id)); +} + +CefString CefMenuModelImpl::GetLabelAt(int index) { + if (!VerifyContext()) + return CefString(); + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].label_; + return CefString(); +} + +bool CefMenuModelImpl::SetLabel(int command_id, const CefString& label) { + return SetLabelAt(GetIndexOf(command_id), label); +} + +bool CefMenuModelImpl::SetLabelAt(int index, const CefString& label) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_[index].label_ = label; + return true; + } + return false; +} + +CefMenuModelImpl::MenuItemType CefMenuModelImpl::GetType(int command_id) { + return GetTypeAt(GetIndexOf(command_id)); +} + +CefMenuModelImpl::MenuItemType CefMenuModelImpl::GetTypeAt(int index) { + if (!VerifyContext()) + return MENUITEMTYPE_NONE; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].type_; + return MENUITEMTYPE_NONE; +} + +int CefMenuModelImpl::GetGroupId(int command_id) { + return GetGroupIdAt(GetIndexOf(command_id)); +} + +int CefMenuModelImpl::GetGroupIdAt(int index) { + if (!VerifyContext()) + return -1; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].group_id_; + return -1; +} + +bool CefMenuModelImpl::SetGroupId(int command_id, int group_id) { + return SetGroupIdAt(GetIndexOf(command_id), group_id); +} + +bool CefMenuModelImpl::SetGroupIdAt(int index, int group_id) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_[index].group_id_ = group_id; + return true; + } + return false; +} + +CefRefPtr CefMenuModelImpl::GetSubMenu(int command_id) { + return GetSubMenuAt(GetIndexOf(command_id)); +} + +CefRefPtr CefMenuModelImpl::GetSubMenuAt(int index) { + if (!VerifyContext()) + return NULL; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].submenu_.get(); + return NULL; +} + +bool CefMenuModelImpl::IsVisible(int command_id) { + return IsVisibleAt(GetIndexOf(command_id)); +} + +bool CefMenuModelImpl::IsVisibleAt(int index) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].visible_; + return false; +} + +bool CefMenuModelImpl::SetVisible(int command_id, bool visible) { + return SetVisibleAt(GetIndexOf(command_id), visible); +} + +bool CefMenuModelImpl::SetVisibleAt(int index, bool visible) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_[index].visible_ = visible; + return true; + } + return false; +} + +bool CefMenuModelImpl::IsEnabled(int command_id) { + return IsEnabledAt(GetIndexOf(command_id)); +} + +bool CefMenuModelImpl::IsEnabledAt(int index) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].enabled_; + return false; +} + +bool CefMenuModelImpl::SetEnabled(int command_id, bool enabled) { + return SetEnabledAt(GetIndexOf(command_id), enabled); +} + +bool CefMenuModelImpl::SetEnabledAt(int index, bool enabled) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_[index].enabled_ = enabled; + return true; + } + return false; +} + +bool CefMenuModelImpl::IsChecked(int command_id) { + return IsCheckedAt(GetIndexOf(command_id)); +} + +bool CefMenuModelImpl::IsCheckedAt(int index) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].checked_; + return false; +} + +bool CefMenuModelImpl::SetChecked(int command_id, bool checked) { + return SetCheckedAt(GetIndexOf(command_id), checked); +} + +bool CefMenuModelImpl::SetCheckedAt(int index, bool checked) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + items_[index].checked_ = checked; + return true; + } + return false; +} + +bool CefMenuModelImpl::HasAccelerator(int command_id) { + return HasAcceleratorAt(GetIndexOf(command_id)); +} + +bool CefMenuModelImpl::HasAcceleratorAt(int index) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) + return items_[index].has_accelerator_; + return false; +} + +bool CefMenuModelImpl::SetAccelerator(int command_id, int key_code, + bool shift_pressed, bool ctrl_pressed, + bool alt_pressed) { + return SetAcceleratorAt(GetIndexOf(command_id), key_code, shift_pressed, + ctrl_pressed, alt_pressed); +} + +bool CefMenuModelImpl::SetAcceleratorAt(int index, int key_code, + bool shift_pressed, bool ctrl_pressed, + bool alt_pressed) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + Item& item = items_[index]; + item.has_accelerator_ = true; + item.key_code_ = key_code; + item.shift_pressed_ = shift_pressed; + item.ctrl_pressed_ = ctrl_pressed; + item.alt_pressed_ = alt_pressed; + return true; + } + return false; +} + +bool CefMenuModelImpl::RemoveAccelerator(int command_id) { + return RemoveAcceleratorAt(GetIndexOf(command_id)); +} + +bool CefMenuModelImpl::RemoveAcceleratorAt(int index) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + Item& item = items_[index]; + if (item.has_accelerator_) { + item.has_accelerator_ = false; + item.key_code_ = 0; + item.shift_pressed_ = false; + item.ctrl_pressed_ = false; + item.alt_pressed_ = false; + } + return true; + } + return false; +} + +bool CefMenuModelImpl::GetAccelerator(int command_id, int& key_code, + bool& shift_pressed, bool& ctrl_pressed, + bool& alt_pressed) { + return GetAcceleratorAt(GetIndexOf(command_id), key_code, shift_pressed, + ctrl_pressed, alt_pressed); +} + +bool CefMenuModelImpl::GetAcceleratorAt(int index, int& key_code, + bool& shift_pressed, bool& ctrl_pressed, + bool& alt_pressed) { + if (!VerifyContext()) + return false; + + if (index >= 0 && index < static_cast(items_.size())) { + const Item& item = items_[index]; + if (item.has_accelerator_) { + key_code = item.key_code_; + shift_pressed = item.shift_pressed_; + ctrl_pressed = item.ctrl_pressed_; + alt_pressed = item.alt_pressed_; + return true; + } + } + return false; +} + +void CefMenuModelImpl::ActivatedAt(int index, cef_event_flags_t event_flags) { + if (VerifyContext() && delegate_) + delegate_->ExecuteCommand(this, GetCommandIdAt(index), event_flags); +} + +void CefMenuModelImpl::MenuWillShow() { + if (VerifyContext() && delegate_) + delegate_->MenuWillShow(this); +} + +void CefMenuModelImpl::MenuClosed() { + if (!VerifyContext()) + return; + + // Due to how menus work on the different platforms, ActivatedAt will be + // called after this. It's more convenient for the delegate to be called + // afterwards, though, so post a task. + base::MessageLoop::current()->PostTask( + FROM_HERE, + base::Bind(&CefMenuModelImpl::OnMenuClosed, this)); +} + +base::string16 CefMenuModelImpl::GetFormattedLabelAt(int index) { + base::string16 label = GetLabelAt(index).ToString16(); + delegate_->FormatLabel(label); + return label; +} + +bool CefMenuModelImpl::VerifyRefCount() { + if (!VerifyContext()) + return false; + + if (!HasOneRef()) + return false; + + for (ItemVector::iterator i = items_.begin(); i != items_.end(); ++i) { + if ((*i).submenu_.get()) { + if (!(*i).submenu_->VerifyRefCount()) + return false; + } + } + + return true; +} + +void CefMenuModelImpl::AppendItem(const Item& item) { + ValidateItem(item); + items_.push_back(item); +} + +void CefMenuModelImpl::InsertItemAt(const Item& item, int index) { + // Sanitize the index. + if (index < 0) + index = 0; + else if (index > static_cast(items_.size())) + index = items_.size(); + + ValidateItem(item); + items_.insert(items_.begin() + index, item); +} + +void CefMenuModelImpl::ValidateItem(const Item& item) { +#ifndef NDEBUG + if (item.type_ == MENUITEMTYPE_SEPARATOR) { + DCHECK_EQ(item.command_id_, kSeparatorId); + } else { + DCHECK_GE(item.command_id_, 0); + } +#endif // NDEBUG +} + +void CefMenuModelImpl::OnMenuClosed() { + if (delegate_) + delegate_->MenuClosed(this); +} + +bool CefMenuModelImpl::VerifyContext() { + if (base::PlatformThread::CurrentId() != supported_thread_id_) { + // This object should only be accessed from the thread that created it. + NOTREACHED(); + return false; + } + + return true; +} diff --git a/libcef/browser/menu_model_impl.h b/libcef/browser/menu_model_impl.h new file mode 100644 index 000000000..6e3996861 --- /dev/null +++ b/libcef/browser/menu_model_impl.h @@ -0,0 +1,144 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_MENU_MODEL_IMPL_H_ +#define CEF_LIBCEF_BROWSER_MENU_MODEL_IMPL_H_ +#pragma once + +#include + +#include "include/cef_menu_model.h" + +#include "base/memory/scoped_ptr.h" +#include "base/threading/platform_thread.h" +#include "ui/base/models/menu_model.h" + +class CefMenuModelImpl : public CefMenuModel { + public: + class Delegate { + public: + // Perform the action associated with the specified |command_id| and + // optional |event_flags|. + virtual void ExecuteCommand(CefRefPtr source, + int command_id, + cef_event_flags_t event_flags) =0; + + // Notifies the delegate that the menu is about to show. + virtual void MenuWillShow(CefRefPtr source) =0; + + // Notifies the delegate that the menu has closed. + virtual void MenuClosed(CefRefPtr source) =0; + + // Allows the delegate to modify a menu item label before it's displayed. + virtual bool FormatLabel(base::string16& label) =0; + + protected: + virtual ~Delegate() {} + }; + + // The delegate must outlive this class. + explicit CefMenuModelImpl(Delegate* delegate); + ~CefMenuModelImpl() override; + + // CefMenuModel methods. + bool Clear() override; + int GetCount() override; + bool AddSeparator() override; + bool AddItem(int command_id, const CefString& label) override; + bool AddCheckItem(int command_id, const CefString& label) override; + bool AddRadioItem(int command_id, const CefString& label, + int group_id) override; + CefRefPtr AddSubMenu(int command_id, + const CefString& label) override; + bool InsertSeparatorAt(int index) override; + bool InsertItemAt(int index, int command_id, + const CefString& label) override; + bool InsertCheckItemAt(int index, int command_id, + const CefString& label) override; + bool InsertRadioItemAt(int index, int command_id, + const CefString& label, int group_id) override; + CefRefPtr InsertSubMenuAt(int index, int command_id, + const CefString& label) override; + bool Remove(int command_id) override; + bool RemoveAt(int index) override; + int GetIndexOf(int command_id) override; + int GetCommandIdAt(int index) override; + bool SetCommandIdAt(int index, int command_id) override; + CefString GetLabel(int command_id) override; + CefString GetLabelAt(int index) override; + bool SetLabel(int command_id, const CefString& label) override; + bool SetLabelAt(int index, const CefString& label) override; + MenuItemType GetType(int command_id) override; + MenuItemType GetTypeAt(int index) override; + int GetGroupId(int command_id) override; + int GetGroupIdAt(int index) override; + bool SetGroupId(int command_id, int group_id) override; + bool SetGroupIdAt(int index, int group_id) override; + CefRefPtr GetSubMenu(int command_id) override; + CefRefPtr GetSubMenuAt(int index) override; + bool IsVisible(int command_id) override; + bool IsVisibleAt(int index) override; + bool SetVisible(int command_id, bool visible) override; + bool SetVisibleAt(int index, bool visible) override; + bool IsEnabled(int command_id) override; + bool IsEnabledAt(int index) override; + bool SetEnabled(int command_id, bool enabled) override; + bool SetEnabledAt(int index, bool enabled) override; + bool IsChecked(int command_id) override; + bool IsCheckedAt(int index) override; + bool SetChecked(int command_id, bool checked) override; + bool SetCheckedAt(int index, bool checked) override; + bool HasAccelerator(int command_id) override; + bool HasAcceleratorAt(int index) override; + bool SetAccelerator(int command_id, int key_code, bool shift_pressed, + bool ctrl_pressed, bool alt_pressed) override; + bool SetAcceleratorAt(int index, int key_code, bool shift_pressed, + bool ctrl_pressed, bool alt_pressed) override; + bool RemoveAccelerator(int command_id) override; + bool RemoveAcceleratorAt(int index) override; + bool GetAccelerator(int command_id, int& key_code, + bool& shift_pressed, bool& ctrl_pressed, bool& alt_pressed) override; + bool GetAcceleratorAt(int index, int& key_code, bool& shift_pressed, + bool& ctrl_pressed, bool& alt_pressed) override; + + // Callbacks from the ui::MenuModel implementation. + void ActivatedAt(int index, cef_event_flags_t event_flags); + void MenuWillShow(); + void MenuClosed(); + base::string16 GetFormattedLabelAt(int index); + + // Verify that only a single reference exists to all CefMenuModelImpl objects. + bool VerifyRefCount(); + + ui::MenuModel* model() { return model_.get(); } + Delegate* delegate() { return delegate_; } + void set_delegate(Delegate* delegate) { delegate_ = NULL; } + + private: + struct Item; + + typedef std::vector ItemVector; + + // Functions for inserting items into |items_|. + void AppendItem(const Item& item); + void InsertItemAt(const Item& item, int index); + void ValidateItem(const Item& item); + + // Notify the delegate that the menu is closed. + void OnMenuClosed(); + + // Verify that the object is being accessed from the correct thread. + bool VerifyContext(); + + base::PlatformThreadId supported_thread_id_; + Delegate* delegate_; + ItemVector items_; + scoped_ptr model_; + + IMPLEMENT_REFCOUNTING(CefMenuModelImpl); + DISALLOW_COPY_AND_ASSIGN(CefMenuModelImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_MENU_MODEL_IMPL_H_ diff --git a/libcef/browser/navigate_params.cc b/libcef/browser/navigate_params.cc new file mode 100644 index 000000000..03c420963 --- /dev/null +++ b/libcef/browser/navigate_params.cc @@ -0,0 +1,20 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/navigate_params.h" + +CefNavigateParams::CefNavigateParams( + const GURL& a_url, + ui::PageTransition a_transition) + : url(a_url), + frame_id(-1), + disposition(CURRENT_TAB), + transition(a_transition), + is_renderer_initiated(false), + user_gesture(true) { +} + +CefNavigateParams::~CefNavigateParams() { +} diff --git a/libcef/browser/navigate_params.h b/libcef/browser/navigate_params.h new file mode 100644 index 000000000..e1c30efc1 --- /dev/null +++ b/libcef/browser/navigate_params.h @@ -0,0 +1,85 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_NAVIGATE_PARAMS_H_ +#define CEF_LIBCEF_BROWSER_NAVIGATE_PARAMS_H_ +#pragma once + +#include + +#include "libcef/common/upload_data.h" + +#include "content/public/browser/global_request_id.h" +#include "content/public/common/referrer.h" +#include "ui/base/page_transition_types.h" +#include "ui/base/window_open_disposition.h" +#include "url/gurl.h" + +// Parameters that tell CefBrowserHostImpl::Navigate() what to do. +struct CefNavigateParams { + CefNavigateParams(const GURL& a_url, + ui::PageTransition a_transition); + ~CefNavigateParams(); + + // The following parameters are sent to the renderer via CefMsg_LoadRequest. + // --------------------------------------------------------------------------- + + // Request method. + std::string method; + + // The URL/referrer to be loaded. + GURL url; + content::Referrer referrer; + + // The frame that the request should be loaded in or -1 to use the main frame. + int64 frame_id; + + // Usually the URL of the document in the top-level window, which may be + // checked by the third-party cookie blocking policy. Leaving it empty may + // lead to undesired cookie blocking. Third-party cookie blocking can be + // bypassed by setting first_party_for_cookies = url, but this should ideally + // only be done if there really is no way to determine the correct value. + GURL first_party_for_cookies; + + // Additional HTTP request headers. + std::string headers; + + // net::URLRequest load flags (0 by default). + int load_flags; + + // Upload data (may be NULL). + scoped_refptr upload_data; + + + // The following parameters are used to define browser behavior when servicing + // the navigation request. + // --------------------------------------------------------------------------- + + // The disposition requested by the navigation source. Default is CURRENT_TAB. + WindowOpenDisposition disposition; + + // The transition type of the navigation. + ui::PageTransition transition; + + // Whether this navigation was initiated by the renderer process. + bool is_renderer_initiated; + + // If non-empty, the new tab contents encoding is overriden by this value. + std::string override_encoding; + + // If false then the navigation was not initiated by a user gesture. Default + // is true. + bool user_gesture; + + // Refers to a navigation that was parked in the browser in order to be + // transferred to another RVH. Only used in case of a redirection of a request + // to a different site that created a new RVH. + content::GlobalRequestID transferred_global_request_id; + + private: + CefNavigateParams(); +}; + +#endif // CEF_LIBCEF_BROWSER_NAVIGATE_PARAMS_H_ diff --git a/libcef/browser/navigation_entry_impl.cc b/libcef/browser/navigation_entry_impl.cc new file mode 100644 index 000000000..5a475cb4d --- /dev/null +++ b/libcef/browser/navigation_entry_impl.cc @@ -0,0 +1,69 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/navigation_entry_impl.h" + +#include "libcef/common/time_util.h" + +#include "content/public/browser/navigation_entry.h" +#include "url/gurl.h" + +CefNavigationEntryImpl::CefNavigationEntryImpl(content::NavigationEntry* value) + : CefValueBase( + value, NULL, kOwnerNoDelete, true, + new CefValueControllerNonThreadSafe()) { + // Indicate that this object owns the controller. + SetOwnsController(); +} + +bool CefNavigationEntryImpl::IsValid() { + return !detached(); +} + +CefString CefNavigationEntryImpl::GetURL() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetURL().spec(); +} + +CefString CefNavigationEntryImpl::GetDisplayURL() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetVirtualURL().spec(); +} + +CefString CefNavigationEntryImpl::GetOriginalURL() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetUserTypedURL().spec(); +} + +CefString CefNavigationEntryImpl::GetTitle() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetTitle(); +} + +CefNavigationEntry::TransitionType CefNavigationEntryImpl::GetTransitionType() { + CEF_VALUE_VERIFY_RETURN(false, TT_EXPLICIT); + return static_cast(const_value().GetTransitionType()); +} + +bool CefNavigationEntryImpl::HasPostData() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().GetHasPostData(); +} + +CefString CefNavigationEntryImpl::GetFrameName() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetFrameToNavigate(); +} + +CefTime CefNavigationEntryImpl::GetCompletionTime() { + CefTime time; + CEF_VALUE_VERIFY_RETURN(false, time); + cef_time_from_basetime(const_value().GetTimestamp(), time); + return time; +} + +int CefNavigationEntryImpl::GetHttpStatusCode() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().GetHttpStatusCode(); +} diff --git a/libcef/browser/navigation_entry_impl.h b/libcef/browser/navigation_entry_impl.h new file mode 100644 index 000000000..876d768ee --- /dev/null +++ b/libcef/browser/navigation_entry_impl.h @@ -0,0 +1,38 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_NAVIGATION_ENTRY_IMPL_H_ +#define CEF_LIBCEF_BROWSER_NAVIGATION_ENTRY_IMPL_H_ +#pragma once + +#include "include/cef_navigation_entry.h" +#include "libcef/common/value_base.h" + +namespace content { +class NavigationEntry; +} + +// CefDownloadItem implementation +class CefNavigationEntryImpl + : public CefValueBase { + public: + explicit CefNavigationEntryImpl(content::NavigationEntry* value); + + // CefNavigationEntry methods. + bool IsValid() override; + CefString GetURL() override; + CefString GetDisplayURL() override; + CefString GetOriginalURL() override; + CefString GetTitle() override; + TransitionType GetTransitionType() override; + bool HasPostData() override; + CefString GetFrameName() override; + CefTime GetCompletionTime() override; + int GetHttpStatusCode() override; + + private: + DISALLOW_COPY_AND_ASSIGN(CefNavigationEntryImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_NAVIGATION_ENTRY_IMPL_H_ diff --git a/libcef/browser/origin_whitelist_impl.cc b/libcef/browser/origin_whitelist_impl.cc new file mode 100644 index 000000000..209cb7dc7 --- /dev/null +++ b/libcef/browser/origin_whitelist_impl.cc @@ -0,0 +1,288 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/origin_whitelist_impl.h" + +#include +#include + +#include "include/cef_origin_whitelist.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/cef_messages.h" + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "base/synchronization/lock.h" +#include "content/public/browser/render_process_host.h" +#include "url/gurl.h" + +namespace { + +// Class that manages cross-origin whitelist registrations. +class CefOriginWhitelistManager { + public: + CefOriginWhitelistManager() {} + + // Retrieve the singleton instance. + static CefOriginWhitelistManager* GetInstance(); + + bool AddOriginEntry(const std::string& source_origin, + const std::string& target_protocol, + const std::string& target_domain, + bool allow_target_subdomains) { + Cef_CrossOriginWhiteListEntry_Params info; + info.source_origin = source_origin; + info.target_protocol = target_protocol; + info.target_domain = target_domain; + info.allow_target_subdomains = allow_target_subdomains; + + { + base::AutoLock lock_scope(lock_); + + // Verify that the origin entry doesn't already exist. + OriginList::const_iterator it = origin_list_.begin(); + for (; it != origin_list_.end(); ++it) { + if (IsEqual(*it, info)) + return false; + } + + origin_list_.push_back(info); + } + + SendModifyCrossOriginWhitelistEntry(true, info); + return true; + } + + bool RemoveOriginEntry(const std::string& source_origin, + const std::string& target_protocol, + const std::string& target_domain, + bool allow_target_subdomains) { + Cef_CrossOriginWhiteListEntry_Params info; + info.source_origin = source_origin; + info.target_protocol = target_protocol; + info.target_domain = target_domain; + info.allow_target_subdomains = allow_target_subdomains; + + bool found = false; + + { + base::AutoLock lock_scope(lock_); + + OriginList::iterator it = origin_list_.begin(); + for (; it != origin_list_.end(); ++it) { + if (IsEqual(*it, info)) { + origin_list_.erase(it); + found = true; + break; + } + } + } + + if (!found) + return false; + + SendModifyCrossOriginWhitelistEntry(false, info); + return true; + } + + void ClearOrigins() { + { + base::AutoLock lock_scope(lock_); + origin_list_.clear(); + } + + SendClearCrossOriginWhitelist(); + } + + void GetCrossOriginWhitelistEntries( + std::vector* entries) { + base::AutoLock lock_scope(lock_); + + if (origin_list_.empty()) + return; + entries->insert(entries->end(), origin_list_.begin(), origin_list_.end()); + } + + private: + // Send the modify cross-origin whitelist entry message to all currently + // existing hosts. + static void SendModifyCrossOriginWhitelistEntry( + bool add, + Cef_CrossOriginWhiteListEntry_Params& params) { + CEF_REQUIRE_UIT(); + + content::RenderProcessHost::iterator i( + content::RenderProcessHost::AllHostsIterator()); + for (; !i.IsAtEnd(); i.Advance()) { + i.GetCurrentValue()->Send( + new CefProcessMsg_ModifyCrossOriginWhitelistEntry(add, params)); + } + } + + // Send the clear cross-origin whitelists message to all currently existing + // hosts. + static void SendClearCrossOriginWhitelist() { + CEF_REQUIRE_UIT(); + + content::RenderProcessHost::iterator i( + content::RenderProcessHost::AllHostsIterator()); + for (; !i.IsAtEnd(); i.Advance()) { + i.GetCurrentValue()->Send(new CefProcessMsg_ClearCrossOriginWhitelist); + } + } + + static bool IsEqual(const Cef_CrossOriginWhiteListEntry_Params& param1, + const Cef_CrossOriginWhiteListEntry_Params& param2) { + return (param1.source_origin == param2.source_origin && + param1.target_protocol == param2.target_protocol && + param1.target_domain == param2.target_domain && + param1.allow_target_subdomains == param2.allow_target_subdomains); + } + + base::Lock lock_; + + // List of registered origins. Access must be protected by |lock_|. + typedef std::vector OriginList; + OriginList origin_list_; + + DISALLOW_EVIL_CONSTRUCTORS(CefOriginWhitelistManager); +}; + +base::LazyInstance g_manager = + LAZY_INSTANCE_INITIALIZER; + +CefOriginWhitelistManager* CefOriginWhitelistManager::GetInstance() { + return g_manager.Pointer(); +} + +bool IsMatch(const GURL& source_origin, + const GURL& target_origin, + const Cef_CrossOriginWhiteListEntry_Params& param) { + if (source_origin.GetOrigin() != GURL(param.source_origin)) { + // Source origin does not match. + return false; + } + + if (target_origin.scheme() != param.target_protocol) { + // Target scheme does not match. + return false; + } + + if (param.allow_target_subdomains) { + if (param.target_domain.empty()) { + // Any domain will match. + return true; + } else { + // Match sub-domains. + return target_origin.DomainIs(param.target_domain.c_str()); + } + } else { + // Match full domain. + return (target_origin.host() == param.target_domain); + } +} + +} // namespace + +bool CefAddCrossOriginWhitelistEntry(const CefString& source_origin, + const CefString& target_protocol, + const CefString& target_domain, + bool allow_target_subdomains) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED(); + return false; + } + + std::string source_url = source_origin; + GURL gurl = GURL(source_url); + if (gurl.is_empty() || !gurl.is_valid()) { + NOTREACHED() << "Invalid source_origin URL: " << source_url; + return false; + } + + if (CEF_CURRENTLY_ON_UIT()) { + return CefOriginWhitelistManager::GetInstance()->AddOriginEntry( + source_origin, target_protocol, target_domain, allow_target_subdomains); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(base::IgnoreResult(&CefAddCrossOriginWhitelistEntry), + source_origin, target_protocol, target_domain, + allow_target_subdomains)); + } + + return true; +} + +bool CefRemoveCrossOriginWhitelistEntry(const CefString& source_origin, + const CefString& target_protocol, + const CefString& target_domain, + bool allow_target_subdomains) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED(); + return false; + } + + std::string source_url = source_origin; + GURL gurl = GURL(source_url); + if (gurl.is_empty() || !gurl.is_valid()) { + NOTREACHED() << "Invalid source_origin URL: " << source_url; + return false; + } + + if (CEF_CURRENTLY_ON_UIT()) { + return CefOriginWhitelistManager::GetInstance()->RemoveOriginEntry( + source_origin, target_protocol, target_domain, allow_target_subdomains); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(base::IgnoreResult(&CefRemoveCrossOriginWhitelistEntry), + source_origin, target_protocol, target_domain, + allow_target_subdomains)); + } + + return true; +} + +bool CefClearCrossOriginWhitelist() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED(); + return false; + } + + if (CEF_CURRENTLY_ON_UIT()) { + CefOriginWhitelistManager::GetInstance()->ClearOrigins(); + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(base::IgnoreResult(&CefClearCrossOriginWhitelist))); + } + + return true; +} + +void GetCrossOriginWhitelistEntries( + std::vector* entries) { + CefOriginWhitelistManager::GetInstance()->GetCrossOriginWhitelistEntries( + entries); +} + +bool HasCrossOriginWhitelistEntry(const GURL& source, const GURL& target) { + std::vector params; + CefOriginWhitelistManager::GetInstance()->GetCrossOriginWhitelistEntries( + ¶ms); + + if (params.empty()) + return false; + + std::vector::const_iterator it = + params.begin(); + for (; it != params.end(); ++it) { + if (IsMatch(source, target, *it)) + return true; + } + + return false; +} diff --git a/libcef/browser/origin_whitelist_impl.h b/libcef/browser/origin_whitelist_impl.h new file mode 100644 index 000000000..bca948c2d --- /dev/null +++ b/libcef/browser/origin_whitelist_impl.h @@ -0,0 +1,28 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_ORIGIN_WHITELIST_IMPL_H_ +#define CEF_LIBCEF_BROWSER_ORIGIN_WHITELIST_IMPL_H_ + +#include +#include + +namespace content { +class RenderProcessHost; +} + +class GURL; + +struct Cef_CrossOriginWhiteListEntry_Params; + +// Called to retrieve the current list of cross-origin white list entries. This +// method is thread safe. +void GetCrossOriginWhitelistEntries( + std::vector* entries); + +// Returns true if |source| can access |target| based on the cross-origin white +// list settings. +bool HasCrossOriginWhitelistEntry(const GURL& source, const GURL& target); + +#endif // CEF_LIBCEF_BROWSER_ORIGIN_WHITELIST_IMPL_H_ diff --git a/libcef/browser/path_util_impl.cc b/libcef/browser/path_util_impl.cc new file mode 100644 index 000000000..9a73d800c --- /dev/null +++ b/libcef/browser/path_util_impl.cc @@ -0,0 +1,44 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/cef_path_util.h" + +#include "base/files/file_path.h" +#include "base/logging.h" +#include "base/path_service.h" + +bool CefGetPath(PathKey key, CefString& path) { + int pref_key = base::PATH_START; + switch(key) { + case PK_DIR_CURRENT: + pref_key = base::DIR_CURRENT; + break; + case PK_DIR_EXE: + pref_key = base::DIR_EXE; + break; + case PK_DIR_MODULE: + pref_key = base::DIR_MODULE; + break; + case PK_DIR_TEMP: + pref_key = base::DIR_TEMP; + break; + case PK_FILE_EXE: + pref_key = base::FILE_EXE; + break; + case PK_FILE_MODULE: + pref_key = base::FILE_MODULE; + break; + default: + NOTREACHED() << "invalid argument"; + return false; + } + + base::FilePath file_path; + if (PathService::Get(pref_key, &file_path)) { + path = file_path.value(); + return true; + } + + return false; +} diff --git a/libcef/browser/print_settings_impl.cc b/libcef/browser/print_settings_impl.cc new file mode 100644 index 000000000..fd38b4047 --- /dev/null +++ b/libcef/browser/print_settings_impl.cc @@ -0,0 +1,165 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/print_settings_impl.h" + +#include "base/logging.h" + +CefPrintSettingsImpl::CefPrintSettingsImpl(printing::PrintSettings* value, + bool will_delete, + bool read_only) + : CefValueBase( + value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete, + read_only, NULL) { +} + +bool CefPrintSettingsImpl::IsValid() { + return !detached(); +} + +bool CefPrintSettingsImpl::IsReadOnly() { + return read_only(); +} + +CefRefPtr CefPrintSettingsImpl::Copy() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + printing::PrintSettings* new_settings = new printing::PrintSettings; + *new_settings = const_value(); + return new CefPrintSettingsImpl(new_settings, true, false); +} + +void CefPrintSettingsImpl::SetOrientation(bool landscape) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->SetOrientation(landscape); +} + +bool CefPrintSettingsImpl::IsLandscape() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().landscape(); +} + +void CefPrintSettingsImpl::SetPrinterPrintableArea( + const CefSize& physical_size_device_units, + const CefRect& printable_area_device_units, + bool landscape_needs_flip) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + gfx::Size size(physical_size_device_units.width, + physical_size_device_units.height); + gfx::Rect rect(printable_area_device_units.x, + printable_area_device_units.y, + printable_area_device_units.width, + printable_area_device_units.height); + mutable_value()->SetPrinterPrintableArea(size, rect, landscape_needs_flip); +} + +void CefPrintSettingsImpl::SetDeviceName(const CefString& name) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_device_name(name.ToString16()); +} + +CefString CefPrintSettingsImpl::GetDeviceName() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().device_name(); +} + +void CefPrintSettingsImpl::SetDPI(int dpi) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_dpi(dpi); +} + +int CefPrintSettingsImpl::GetDPI() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().dpi(); +} + +void CefPrintSettingsImpl::SetPageRanges(const PageRangeList& ranges) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + printing::PageRanges page_ranges; + PageRangeList::const_iterator it = ranges.begin(); + for(; it != ranges.end(); ++it) { + const CefPageRange& cef_range = *it; + printing::PageRange range; + range.from = cef_range.from; + range.to = cef_range.to; + page_ranges.push_back(range); + } + mutable_value()->set_ranges(page_ranges); +} + +size_t CefPrintSettingsImpl::GetPageRangesCount() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().ranges().size(); +} + +void CefPrintSettingsImpl::GetPageRanges(PageRangeList& ranges) { + CEF_VALUE_VERIFY_RETURN_VOID(false); + if (!ranges.empty()) + ranges.clear(); + const printing::PageRanges& page_ranges = const_value().ranges(); + printing::PageRanges::const_iterator it = page_ranges.begin(); + for (; it != page_ranges.end(); ++it) { + const printing::PageRange& range = *it; + ranges.push_back(CefPageRange(range.from, range.to)); + } +} + +void CefPrintSettingsImpl::SetSelectionOnly(bool selection_only) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_selection_only(selection_only); +} + +bool CefPrintSettingsImpl::IsSelectionOnly() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().selection_only(); +} + +void CefPrintSettingsImpl::SetCollate(bool collate) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_collate(collate); +} + +bool CefPrintSettingsImpl::WillCollate() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().collate(); +} + +void CefPrintSettingsImpl::SetColorModel(ColorModel model) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_color(static_cast(model)); +} + +CefPrintSettings::ColorModel CefPrintSettingsImpl::GetColorModel() { + CEF_VALUE_VERIFY_RETURN(false, COLOR_MODEL_UNKNOWN); + return static_cast(const_value().color()); +} + +void CefPrintSettingsImpl::SetCopies(int copies) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_copies(copies); +} + +int CefPrintSettingsImpl::GetCopies() { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().copies(); +} + +void CefPrintSettingsImpl::SetDuplexMode(DuplexMode mode) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->set_duplex_mode(static_cast(mode)); +} + +CefPrintSettings::DuplexMode CefPrintSettingsImpl::GetDuplexMode() { + CEF_VALUE_VERIFY_RETURN(false, DUPLEX_MODE_UNKNOWN); + return static_cast(const_value().duplex_mode()); +} + + +// CefPrintSettings implementation. + +// static +CefRefPtr CefPrintSettings::Create() { + return new CefPrintSettingsImpl( + new printing::PrintSettings(), true, false); +} + diff --git a/libcef/browser/print_settings_impl.h b/libcef/browser/print_settings_impl.h new file mode 100644 index 000000000..0ae7e10e4 --- /dev/null +++ b/libcef/browser/print_settings_impl.h @@ -0,0 +1,56 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_PRINT_SETTINGS_IMPL_H_ +#define CEF_LIBCEF_BROWSER_PRINT_SETTINGS_IMPL_H_ +#pragma once + +#include "include/cef_print_settings.h" +#include "libcef/common/value_base.h" + +#include "printing/print_settings.h" + +// CefPrintSettings implementation +class CefPrintSettingsImpl + : public CefValueBase { + public: + CefPrintSettingsImpl(printing::PrintSettings* value, + bool will_delete, + bool read_only); + + // CefPrintSettings methods. + bool IsValid() override; + bool IsReadOnly() override; + CefRefPtr Copy() override; + void SetOrientation(bool landscape) override; + bool IsLandscape() override; + void SetPrinterPrintableArea( + const CefSize& physical_size_device_units, + const CefRect& printable_area_device_units, + bool landscape_needs_flip) override; + void SetDeviceName(const CefString& name) override; + CefString GetDeviceName() override; + void SetDPI(int dpi) override; + int GetDPI() override; + void SetPageRanges(const PageRangeList& ranges) override; + size_t GetPageRangesCount() override; + void GetPageRanges(PageRangeList& ranges) override; + void SetSelectionOnly(bool selection_only) override; + bool IsSelectionOnly() override; + void SetCollate(bool collate) override; + bool WillCollate() override; + void SetColorModel(ColorModel model) override; + ColorModel GetColorModel() override; + void SetCopies(int copies) override; + int GetCopies() override; + void SetDuplexMode(DuplexMode mode) override; + DuplexMode GetDuplexMode() override; + + // Must hold the controller lock while using this value. + const printing::PrintSettings& print_settings() { return const_value(); } + + DISALLOW_COPY_AND_ASSIGN(CefPrintSettingsImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_PRINT_SETTINGS_IMPL_H_ diff --git a/libcef/browser/printing/print_dialog_linux.cc b/libcef/browser/printing/print_dialog_linux.cc new file mode 100644 index 000000000..53a5c51e4 --- /dev/null +++ b/libcef/browser/printing/print_dialog_linux.cc @@ -0,0 +1,278 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/printing/print_dialog_linux.h" + +#include +#include + +#include "libcef/browser/print_settings_impl.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/content_client.h" + +#include "base/bind.h" +#include "base/files/file_util.h" +#include "base/files/file_util_proxy.h" +#include "base/lazy_instance.h" +#include "base/logging.h" +#include "base/message_loop/message_loop_proxy.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "printing/metafile.h" +#include "printing/print_job_constants.h" +#include "printing/print_settings.h" + +using content::BrowserThread; +using printing::PageRanges; +using printing::PrintSettings; + +class CefPrintDialogCallbackImpl : public CefPrintDialogCallback { + public: + explicit CefPrintDialogCallbackImpl(CefRefPtr dialog) + : dialog_(dialog) { + } + + void Continue(CefRefPtr settings) override { + if (CEF_CURRENTLY_ON_UIT()) { + if (dialog_.get()) { + dialog_->OnPrintContinue(settings); + dialog_ = NULL; + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefPrintDialogCallbackImpl::Continue, this, settings)); + } + } + + void Cancel() override { + if (CEF_CURRENTLY_ON_UIT()) { + if (dialog_.get()) { + dialog_->OnPrintCancel(); + dialog_ = NULL; + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefPrintDialogCallbackImpl::Cancel, this)); + } + } + + void Disconnect() { + dialog_ = NULL; + } + + private: + CefRefPtr dialog_; + + IMPLEMENT_REFCOUNTING(CefPrintDialogCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefPrintDialogCallbackImpl); +}; + +class CefPrintJobCallbackImpl : public CefPrintJobCallback { + public: + explicit CefPrintJobCallbackImpl(CefRefPtr dialog) + : dialog_(dialog) { + } + + void Continue() override { + if (CEF_CURRENTLY_ON_UIT()) { + if (dialog_.get()) { + dialog_->OnJobCompleted(); + dialog_ = NULL; + } + } else { + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefPrintJobCallbackImpl::Continue, this)); + } + } + + void Disconnect() { + dialog_ = NULL; + } + + private: + CefRefPtr dialog_; + + IMPLEMENT_REFCOUNTING(CefPrintJobCallbackImpl); + DISALLOW_COPY_AND_ASSIGN(CefPrintJobCallbackImpl); +}; + + +// static +printing::PrintDialogGtkInterface* CefPrintDialogLinux::CreatePrintDialog( + PrintingContextLinux* context) { + CEF_REQUIRE_UIT(); + return new CefPrintDialogLinux(context); +} + +CefPrintDialogLinux::CefPrintDialogLinux(PrintingContextLinux* context) + : context_(context) { +} + +CefPrintDialogLinux::~CefPrintDialogLinux() { + CEF_REQUIRE_UIT(); + ReleaseHandler(); +} + +void CefPrintDialogLinux::UseDefaultSettings() { + PrintSettings settings; + UpdateSettings(&settings, true); +} + +bool CefPrintDialogLinux::UpdateSettings(printing::PrintSettings* settings) { + return UpdateSettings(settings, false); +} + +void CefPrintDialogLinux::ShowDialog( + gfx::NativeView parent_view, + bool has_selection, + const PrintingContextLinux::PrintSettingsCallback& callback) { + CEF_REQUIRE_UIT(); + + SetHandler(); + if (!handler_.get()) { + callback.Run(PrintingContextLinux::CANCEL); + return; + } + + callback_ = callback; + + CefRefPtr callback_impl( + new CefPrintDialogCallbackImpl(this)); + + if (!handler_->OnPrintDialog(has_selection, callback_impl.get())) { + callback_impl->Disconnect(); + OnPrintCancel(); + } +} + +void CefPrintDialogLinux::PrintDocument( + const printing::MetafilePlayer& metafile, + const base::string16& document_name) { + // This runs on the print worker thread, does not block the UI thread. + DCHECK(!CEF_CURRENTLY_ON_UIT()); + + // The document printing tasks can outlive the PrintingContext that created + // this dialog. + AddRef(); + + bool success = base::CreateTemporaryFile(&path_to_pdf_); + + if (success) { + base::File file; + file.Initialize(path_to_pdf_, + base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); + success = metafile.SaveTo(&file); + file.Close(); + if (!success) + base::DeleteFile(path_to_pdf_, false); + } + + if (!success) { + LOG(ERROR) << "Saving metafile failed"; + // Matches AddRef() above. + Release(); + return; + } + + // No errors, continue printing. + CEF_POST_TASK( + CEF_UIT, + base::Bind(&CefPrintDialogLinux::SendDocumentToPrinter, this, + document_name)); +} + +void CefPrintDialogLinux::AddRefToDialog() { + AddRef(); +} + +void CefPrintDialogLinux::ReleaseDialog() { + Release(); +} + +void CefPrintDialogLinux::SetHandler() { + if (handler_.get()) + return; + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr browser_handler = + app->GetBrowserProcessHandler(); + if (browser_handler.get()) + handler_ = browser_handler->GetPrintHandler(); + } +} + +void CefPrintDialogLinux::ReleaseHandler() { + if (handler_.get()) { + handler_->OnPrintReset(); + handler_ = NULL; + } +} + +bool CefPrintDialogLinux::UpdateSettings(printing::PrintSettings* settings, + bool get_defaults) { + CEF_REQUIRE_UIT(); + + SetHandler(); + if (!handler_.get()) + return false; + + CefRefPtr settings_impl( + new CefPrintSettingsImpl(settings, false, false)); + handler_->OnPrintSettings(settings_impl.get(), get_defaults); + settings_impl->Detach(NULL); + + context_->InitWithSettings(*settings); + return true; +} + +void CefPrintDialogLinux::SendDocumentToPrinter( + const base::string16& document_name) { + CEF_REQUIRE_UIT(); + + if (!handler_.get()) { + OnJobCompleted(); + return; + } + + CefRefPtr callback_impl( + new CefPrintJobCallbackImpl(this)); + + if (!handler_->OnPrintJob(document_name, path_to_pdf_.value(), + callback_impl.get())) { + callback_impl->Disconnect(); + OnJobCompleted(); + } +} + +void CefPrintDialogLinux::OnPrintContinue( + CefRefPtr settings) { + { + CefPrintSettingsImpl* impl = + static_cast(settings.get()); + CefValueController::AutoLock lock_scope(impl->controller()); + context_->InitWithSettings(impl->print_settings()); + } + callback_.Run(PrintingContextLinux::OK); + callback_.Reset(); +} + +void CefPrintDialogLinux::OnPrintCancel() { + callback_.Run(PrintingContextLinux::CANCEL); + callback_.Reset(); +} + +void CefPrintDialogLinux::OnJobCompleted() { + base::FileUtilProxy::DeleteFile( + content::BrowserThread::GetMessageLoopProxyForThread( + BrowserThread::FILE).get(), + path_to_pdf_, + false, + base::FileUtilProxy::StatusCallback()); + + // Printing finished. Matches AddRef() in PrintDocument(); + Release(); +} + diff --git a/libcef/browser/printing/print_dialog_linux.h b/libcef/browser/printing/print_dialog_linux.h new file mode 100644 index 000000000..c7fcea771 --- /dev/null +++ b/libcef/browser/printing/print_dialog_linux.h @@ -0,0 +1,87 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef LIBCEF_BROWSER_PRINTING_PRINT_DIALOG_LINUX_H_ +#define LIBCEF_BROWSER_PRINTING_PRINT_DIALOG_LINUX_H_ + +#include "include/cef_print_handler.h" + +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/sequenced_task_runner_helpers.h" +#include "content/public/browser/browser_thread.h" +#include "printing/print_dialog_gtk_interface.h" +#include "printing/printing_context_linux.h" + +namespace printing { +class MetafilePlayer; +class PrintSettings; +} + +using printing::PrintingContextLinux; + +// Needs to be freed on the UI thread to clean up its member variables. +class CefPrintDialogLinux + : public printing::PrintDialogGtkInterface, + public base::RefCountedThreadSafe< + CefPrintDialogLinux, content::BrowserThread::DeleteOnUIThread> { + public: + // Creates and returns a print dialog. + static printing::PrintDialogGtkInterface* CreatePrintDialog( + PrintingContextLinux* context); + + // printing::CefPrintDialogLinuxInterface implementation. + void UseDefaultSettings() override; + bool UpdateSettings(printing::PrintSettings* settings) override; + void ShowDialog( + gfx::NativeView parent_view, + bool has_selection, + const PrintingContextLinux::PrintSettingsCallback& callback) override; + void PrintDocument(const printing::MetafilePlayer& metafile, + const base::string16& document_name) override; + void AddRefToDialog() override; + void ReleaseDialog() override; + + private: + friend class base::DeleteHelper; + friend class base::RefCountedThreadSafe< + CefPrintDialogLinux, content::BrowserThread::DeleteOnUIThread>; + friend struct content::BrowserThread::DeleteOnThread< + content::BrowserThread::UI>; + friend class CefPrintDialogCallbackImpl; + friend class CefPrintJobCallbackImpl; + + explicit CefPrintDialogLinux(PrintingContextLinux* context); + ~CefPrintDialogLinux() override; + + void SetHandler(); + void ReleaseHandler(); + + bool UpdateSettings(printing::PrintSettings* settings, + bool get_defaults); + + // Prints document named |document_name|. + void SendDocumentToPrinter(const base::string16& document_name); + + // Handles print dialog response. + void OnPrintContinue(CefRefPtr settings); + void OnPrintCancel(); + + // Handles print job response. + void OnJobCompleted(); + + CefRefPtr handler_; + + // Printing dialog callback. + PrintingContextLinux::PrintSettingsCallback callback_; + PrintingContextLinux* context_; + + base::FilePath path_to_pdf_; + + DISALLOW_COPY_AND_ASSIGN(CefPrintDialogLinux); +}; + +#endif // LIBCEF_BROWSER_PRINTING_PRINT_DIALOG_LINUX_H_ diff --git a/libcef/browser/printing/print_view_manager.cc b/libcef/browser/printing/print_view_manager.cc new file mode 100644 index 000000000..028bbfae4 --- /dev/null +++ b/libcef/browser/printing/print_view_manager.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/printing/print_view_manager.h" + +#include + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "base/metrics/histogram.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/printing/print_job_manager.h" +#include "chrome/browser/printing/print_preview_dialog_controller.h" +#include "chrome/common/print_messages.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/web_contents.h" + +using content::BrowserThread; + +DEFINE_WEB_CONTENTS_USER_DATA_KEY(printing::PrintViewManager); + +namespace printing { + +PrintViewManager::PrintViewManager(content::WebContents* web_contents) + : PrintViewManagerBase(web_contents) { +} + +PrintViewManager::~PrintViewManager() { +} + +#if defined(ENABLE_BASIC_PRINTING) +bool PrintViewManager::PrintForSystemDialogNow() { + return PrintNowInternal(new PrintMsg_PrintForSystemDialog(routing_id())); +} +#endif // ENABLE_BASIC_PRINTING + +void PrintViewManager::RenderProcessGone(base::TerminationStatus status) { + PrintViewManagerBase::RenderProcessGone(status); +} + +void PrintViewManager::OnDidShowPrintDialog() { +} + +bool PrintViewManager::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(PrintViewManager, message) + IPC_MESSAGE_HANDLER(PrintHostMsg_DidShowPrintDialog, OnDidShowPrintDialog) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + + return handled ? true : PrintViewManagerBase::OnMessageReceived(message); +} + +} // namespace printing diff --git a/libcef/browser/printing/print_view_manager.h b/libcef/browser/printing/print_view_manager.h new file mode 100644 index 000000000..d886809e4 --- /dev/null +++ b/libcef/browser/printing/print_view_manager.h @@ -0,0 +1,48 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_PRINTING_PRINT_VIEW_MANAGER_H_ +#define CEF_LIBCEF_BROWSER_PRINTING_PRINT_VIEW_MANAGER_H_ + +#include "libcef/browser/printing/print_view_manager_base.h" +#include "content/public/browser/web_contents_user_data.h" + +namespace content { +class RenderProcessHost; +} + +namespace printing { + +// Manages the print commands for a WebContents. +class PrintViewManager : public PrintViewManagerBase, + public content::WebContentsUserData { + public: + ~PrintViewManager() override; + +#if defined(ENABLE_BASIC_PRINTING) + // Same as PrintNow(), but for the case where a user prints with the system + // dialog from print preview. + bool PrintForSystemDialogNow(); +#endif // ENABLE_BASIC_PRINTING + + // content::WebContentsObserver implementation. + bool OnMessageReceived(const IPC::Message& message) override; + + // content::WebContentsObserver implementation. + // Terminates or cancels the print job if one was pending. + void RenderProcessGone(base::TerminationStatus status) override; + + private: + explicit PrintViewManager(content::WebContents* web_contents); + friend class content::WebContentsUserData; + + // IPC Message handlers. + void OnDidShowPrintDialog(); + + DISALLOW_COPY_AND_ASSIGN(PrintViewManager); +}; + +} // namespace printing + +#endif // CEF_LIBCEF_BROWSER_PRINTING_PRINT_VIEW_MANAGER_H_ diff --git a/libcef/browser/printing/print_view_manager_base.cc b/libcef/browser/printing/print_view_manager_base.cc new file mode 100644 index 000000000..29fd627a4 --- /dev/null +++ b/libcef/browser/printing/print_view_manager_base.cc @@ -0,0 +1,509 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/printing/print_view_manager_base.h" + +#include "libcef/browser/content_browser_client.h" + +#include "base/bind.h" +#include "base/memory/scoped_ptr.h" +#include "base/prefs/pref_service.h" +#include "base/strings/utf_string_conversions.h" +#include "base/timer/timer.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/printing/print_job.h" +#include "chrome/browser/printing/print_job_manager.h" +#include "chrome/browser/printing/printer_query.h" +#include "chrome/common/pref_names.h" +#include "chrome/common/print_messages.h" +#include "chrome/grit/generated_resources.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/notification_details.h" +#include "content/public/browser/notification_service.h" +#include "content/public/browser/notification_source.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/web_contents.h" +#include "printing/pdf_metafile_skia.h" +#include "printing/printed_document.h" +#include "ui/base/l10n/l10n_util.h" + +using base::TimeDelta; +using content::BrowserThread; + +namespace printing { + +namespace { + +} // namespace + +PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) + : content::WebContentsObserver(web_contents), + number_pages_(0), + printing_succeeded_(false), + inside_inner_message_loop_(false), + cookie_(0), + queue_(g_browser_process->print_job_manager()->queue()) { + DCHECK(queue_.get()); +#if !defined(OS_MACOSX) + expecting_first_page_ = true; +#endif // OS_MACOSX + printing_enabled_.Init( + prefs::kPrintingEnabled, + CefContentBrowserClient::Get()->pref_service(), + base::Bind(&PrintViewManagerBase::UpdateScriptedPrintingBlocked, + base::Unretained(this))); +} + +PrintViewManagerBase::~PrintViewManagerBase() { + ReleasePrinterQuery(); + DisconnectFromCurrentPrintJob(); +} + +#if defined(ENABLE_BASIC_PRINTING) +bool PrintViewManagerBase::PrintNow() { + return PrintNowInternal(new PrintMsg_PrintPages(routing_id())); +} +#endif // ENABLE_BASIC_PRINTING + +void PrintViewManagerBase::UpdateScriptedPrintingBlocked() { + Send(new PrintMsg_SetScriptedPrintingBlocked( + routing_id(), + !printing_enabled_.GetValue())); +} + +void PrintViewManagerBase::NavigationStopped() { + // Cancel the current job, wait for the worker to finish. + TerminatePrintJob(true); +} + +void PrintViewManagerBase::RenderProcessGone(base::TerminationStatus status) { + ReleasePrinterQuery(); + + if (!print_job_.get()) + return; + + scoped_refptr document(print_job_->document()); + if (document.get()) { + // If IsComplete() returns false, the document isn't completely rendered. + // Since our renderer is gone, there's nothing to do, cancel it. Otherwise, + // the print job may finish without problem. + TerminatePrintJob(!document->IsComplete()); + } +} + +base::string16 PrintViewManagerBase::RenderSourceName() { + base::string16 name(web_contents()->GetTitle()); + if (name.empty()) + name = l10n_util::GetStringUTF16(IDS_DEFAULT_PRINT_DOCUMENT_TITLE); + return name; +} + +void PrintViewManagerBase::OnDidGetPrintedPagesCount(int cookie, + int number_pages) { + DCHECK_GT(cookie, 0); + DCHECK_GT(number_pages, 0); + number_pages_ = number_pages; + OpportunisticallyCreatePrintJob(cookie); +} + +void PrintViewManagerBase::OnDidGetDocumentCookie(int cookie) { + cookie_ = cookie; +} + +void PrintViewManagerBase::OnDidPrintPage( + const PrintHostMsg_DidPrintPage_Params& params) { + if (!OpportunisticallyCreatePrintJob(params.document_cookie)) + return; + + PrintedDocument* document = print_job_->document(); + if (!document || params.document_cookie != document->cookie()) { + // Out of sync. It may happen since we are completely asynchronous. Old + // spurious messages can be received if one of the processes is overloaded. + return; + } + +#if defined(OS_MACOSX) + const bool metafile_must_be_valid = true; +#else + const bool metafile_must_be_valid = expecting_first_page_; + expecting_first_page_ = false; +#endif // OS_MACOSX + + base::SharedMemory shared_buf(params.metafile_data_handle, true); + if (metafile_must_be_valid) { + if (!shared_buf.Map(params.data_size)) { + NOTREACHED() << "couldn't map"; + web_contents()->Stop(); + return; + } + } + + scoped_ptr metafile(new PdfMetafileSkia); + if (metafile_must_be_valid) { + if (!metafile->InitFromData(shared_buf.memory(), params.data_size)) { + NOTREACHED() << "Invalid metafile header"; + web_contents()->Stop(); + return; + } + } + +#if !defined(OS_WIN) + // Update the rendered document. It will send notifications to the listener. + document->SetPage(params.page_number, + metafile.Pass(), + params.page_size, + params.content_area); + + ShouldQuitFromInnerMessageLoop(); +#else + if (metafile_must_be_valid) { + scoped_refptr bytes = new base::RefCountedBytes( + reinterpret_cast(shared_buf.memory()), + params.data_size); + + document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL(".pdf")); + print_job_->StartPdfToEmfConversion( + bytes, params.page_size, params.content_area); + } +#endif // !OS_WIN +} + +void PrintViewManagerBase::OnPrintingFailed(int cookie) { + if (cookie != cookie_) { + NOTREACHED(); + return; + } + + ReleasePrinterQuery(); + + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PRINT_JOB_RELEASED, + content::Source(web_contents()), + content::NotificationService::NoDetails()); +} + +void PrintViewManagerBase::OnShowInvalidPrinterSettingsError() { +} + +void PrintViewManagerBase::DidStartLoading( + content::RenderViewHost* render_view_host) { + UpdateScriptedPrintingBlocked(); +} + +bool PrintViewManagerBase::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(PrintViewManagerBase, message) + IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetPrintedPagesCount, + OnDidGetPrintedPagesCount) + IPC_MESSAGE_HANDLER(PrintHostMsg_DidGetDocumentCookie, + OnDidGetDocumentCookie) + IPC_MESSAGE_HANDLER(PrintHostMsg_DidPrintPage, OnDidPrintPage) + IPC_MESSAGE_HANDLER(PrintHostMsg_PrintingFailed, OnPrintingFailed) + IPC_MESSAGE_HANDLER(PrintHostMsg_ShowInvalidPrinterSettingsError, + OnShowInvalidPrinterSettingsError); + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void PrintViewManagerBase::Observe( + int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) { + switch (type) { + case chrome::NOTIFICATION_PRINT_JOB_EVENT: { + OnNotifyPrintJobEvent(*content::Details(details).ptr()); + break; + } + default: { + NOTREACHED(); + break; + } + } +} + +void PrintViewManagerBase::OnNotifyPrintJobEvent( + const JobEventDetails& event_details) { + switch (event_details.type()) { + case JobEventDetails::FAILED: { + TerminatePrintJob(true); + + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PRINT_JOB_RELEASED, + content::Source(web_contents()), + content::NotificationService::NoDetails()); + break; + } + case JobEventDetails::USER_INIT_DONE: + case JobEventDetails::DEFAULT_INIT_DONE: + case JobEventDetails::USER_INIT_CANCELED: { + NOTREACHED(); + break; + } + case JobEventDetails::ALL_PAGES_REQUESTED: { + ShouldQuitFromInnerMessageLoop(); + break; + } + case JobEventDetails::NEW_DOC: + case JobEventDetails::NEW_PAGE: + case JobEventDetails::PAGE_DONE: + case JobEventDetails::DOC_DONE: { + // Don't care about the actual printing process. + break; + } + case JobEventDetails::JOB_DONE: { + // Printing is done, we don't need it anymore. + // print_job_->is_job_pending() may still be true, depending on the order + // of object registration. + printing_succeeded_ = true; + ReleasePrintJob(); + + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PRINT_JOB_RELEASED, + content::Source(web_contents()), + content::NotificationService::NoDetails()); + break; + } + default: { + NOTREACHED(); + break; + } + } +} + +bool PrintViewManagerBase::RenderAllMissingPagesNow() { + if (!print_job_.get() || !print_job_->is_job_pending()) + return false; + + // We can't print if there is no renderer. + if (!web_contents() || + !web_contents()->GetRenderViewHost() || + !web_contents()->GetRenderViewHost()->IsRenderViewLive()) { + return false; + } + + // Is the document already complete? + if (print_job_->document() && print_job_->document()->IsComplete()) { + printing_succeeded_ = true; + return true; + } + + // WebContents is either dying or a second consecutive request to print + // happened before the first had time to finish. We need to render all the + // pages in an hurry if a print_job_ is still pending. No need to wait for it + // to actually spool the pages, only to have the renderer generate them. Run + // a message loop until we get our signal that the print job is satisfied. + // PrintJob will send a ALL_PAGES_REQUESTED after having received all the + // pages it needs. MessageLoop::current()->Quit() will be called as soon as + // print_job_->document()->IsComplete() is true on either ALL_PAGES_REQUESTED + // or in DidPrintPage(). The check is done in + // ShouldQuitFromInnerMessageLoop(). + // BLOCKS until all the pages are received. (Need to enable recursive task) + if (!RunInnerMessageLoop()) { + // This function is always called from DisconnectFromCurrentPrintJob() so we + // know that the job will be stopped/canceled in any case. + return false; + } + return true; +} + +void PrintViewManagerBase::ShouldQuitFromInnerMessageLoop() { + // Look at the reason. + DCHECK(print_job_->document()); + if (print_job_->document() && + print_job_->document()->IsComplete() && + inside_inner_message_loop_) { + // We are in a message loop created by RenderAllMissingPagesNow. Quit from + // it. + base::MessageLoop::current()->Quit(); + inside_inner_message_loop_ = false; + } +} + +bool PrintViewManagerBase::CreateNewPrintJob(PrintJobWorkerOwner* job) { + DCHECK(!inside_inner_message_loop_); + + // Disconnect the current print_job_. + DisconnectFromCurrentPrintJob(); + + // We can't print if there is no renderer. + if (!web_contents()->GetRenderViewHost() || + !web_contents()->GetRenderViewHost()->IsRenderViewLive()) { + return false; + } + + // Ask the renderer to generate the print preview, create the print preview + // view and switch to it, initialize the printer and show the print dialog. + DCHECK(!print_job_.get()); + DCHECK(job); + if (!job) + return false; + + print_job_ = new PrintJob(); + print_job_->Initialize(job, this, number_pages_); + registrar_.Add(this, chrome::NOTIFICATION_PRINT_JOB_EVENT, + content::Source(print_job_.get())); + printing_succeeded_ = false; + return true; +} + +void PrintViewManagerBase::DisconnectFromCurrentPrintJob() { + // Make sure all the necessary rendered page are done. Don't bother with the + // return value. + bool result = RenderAllMissingPagesNow(); + + // Verify that assertion. + if (print_job_.get() && + print_job_->document() && + !print_job_->document()->IsComplete()) { + DCHECK(!result); + // That failed. + TerminatePrintJob(true); + } else { + // DO NOT wait for the job to finish. + ReleasePrintJob(); + } +#if !defined(OS_MACOSX) + expecting_first_page_ = true; +#endif // OS_MACOSX +} + +void PrintViewManagerBase::PrintingDone(bool success) { + if (!print_job_.get()) + return; + Send(new PrintMsg_PrintingDone(routing_id(), success)); +} + +void PrintViewManagerBase::TerminatePrintJob(bool cancel) { + if (!print_job_.get()) + return; + + if (cancel) { + // We don't need the metafile data anymore because the printing is canceled. + print_job_->Cancel(); + inside_inner_message_loop_ = false; + } else { + DCHECK(!inside_inner_message_loop_); + DCHECK(!print_job_->document() || print_job_->document()->IsComplete()); + + // WebContents is either dying or navigating elsewhere. We need to render + // all the pages in an hurry if a print job is still pending. This does the + // trick since it runs a blocking message loop: + print_job_->Stop(); + } + ReleasePrintJob(); +} + +void PrintViewManagerBase::ReleasePrintJob() { + if (!print_job_.get()) + return; + + PrintingDone(printing_succeeded_); + + registrar_.Remove(this, chrome::NOTIFICATION_PRINT_JOB_EVENT, + content::Source(print_job_.get())); + print_job_->DisconnectSource(); + // Don't close the worker thread. + print_job_ = NULL; +} + +bool PrintViewManagerBase::RunInnerMessageLoop() { + // This value may actually be too low: + // + // - If we're looping because of printer settings initialization, the premise + // here is that some poor users have their print server away on a VPN over a + // slow connection. In this situation, the simple fact of opening the printer + // can be dead slow. On the other side, we don't want to die infinitely for a + // real network error. Give the printer 60 seconds to comply. + // + // - If we're looping because of renderer page generation, the renderer could + // be CPU bound, the page overly complex/large or the system just + // memory-bound. + static const int kPrinterSettingsTimeout = 60000; + base::OneShotTimer quit_timer; + quit_timer.Start(FROM_HERE, + TimeDelta::FromMilliseconds(kPrinterSettingsTimeout), + base::MessageLoop::current(), &base::MessageLoop::Quit); + + inside_inner_message_loop_ = true; + + // Need to enable recursive task. + { + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + base::MessageLoop::current()->Run(); + } + + bool success = true; + if (inside_inner_message_loop_) { + // Ok we timed out. That's sad. + inside_inner_message_loop_ = false; + success = false; + } + + return success; +} + +bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { + if (print_job_.get()) + return true; + + if (!cookie) { + // Out of sync. It may happens since we are completely asynchronous. Old + // spurious message can happen if one of the processes is overloaded. + return false; + } + + // The job was initiated by a script. Time to get the corresponding worker + // thread. + scoped_refptr queued_query = queue_->PopPrinterQuery(cookie); + if (!queued_query.get()) { + NOTREACHED(); + return false; + } + + if (!CreateNewPrintJob(queued_query.get())) { + // Don't kill anything. + return false; + } + + // Settings are already loaded. Go ahead. This will set + // print_job_->is_job_pending() to true. + print_job_->StartPrinting(); + return true; +} + +bool PrintViewManagerBase::PrintNowInternal(IPC::Message* message) { + // Don't print / print preview interstitials. + if (web_contents()->ShowingInterstitialPage()) { + delete message; + return false; + } + return Send(message); +} + +void PrintViewManagerBase::ReleasePrinterQuery() { + if (!cookie_) + return; + + int cookie = cookie_; + cookie_ = 0; + + printing::PrintJobManager* print_job_manager = + g_browser_process->print_job_manager(); + // May be NULL in tests. + if (!print_job_manager) + return; + + scoped_refptr printer_query; + printer_query = queue_->PopPrinterQuery(cookie); + if (!printer_query.get()) + return; + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::Bind(&PrinterQuery::StopWorker, printer_query.get())); +} + +} // namespace printing diff --git a/libcef/browser/printing/print_view_manager_base.h b/libcef/browser/printing/print_view_manager_base.h new file mode 100644 index 000000000..2af7b3933 --- /dev/null +++ b/libcef/browser/printing/print_view_manager_base.h @@ -0,0 +1,170 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_PRINTING_PRINT_VIEW_MANAGER_BASE_H_ +#define CEF_LIBCEF_BROWSER_PRINTING_PRINT_VIEW_MANAGER_BASE_H_ + +#include "base/memory/ref_counted.h" +#include "base/prefs/pref_member.h" +#include "base/strings/string16.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#include "content/public/browser/web_contents_observer.h" +#include "content/public/browser/web_contents_user_data.h" +#include "printing/printed_pages_source.h" + +struct PrintHostMsg_DidPrintPage_Params; + +namespace content { +class RenderViewHost; +} + +namespace printing { + +class JobEventDetails; +class MetafilePlayer; +class PrintJob; +class PrintJobWorkerOwner; +class PrintQueriesQueue; + +// Base class for managing the print commands for a WebContents. +class PrintViewManagerBase : public content::NotificationObserver, + public PrintedPagesSource, + public content::WebContentsObserver { + public: + ~PrintViewManagerBase() override; + +#if defined(ENABLE_BASIC_PRINTING) + // Prints the current document immediately. Since the rendering is + // asynchronous, the actual printing will not be completed on the return of + // this function. Returns false if printing is impossible at the moment. + virtual bool PrintNow(); +#endif // ENABLE_BASIC_PRINTING + + // Whether to block scripted printing for our tab or not. + void UpdateScriptedPrintingBlocked(); + + // PrintedPagesSource implementation. + base::string16 RenderSourceName() override; + + protected: + explicit PrintViewManagerBase(content::WebContents* web_contents); + + // Helper method for Print*Now(). + bool PrintNowInternal(IPC::Message* message); + + // Terminates or cancels the print job if one was pending. + void RenderProcessGone(base::TerminationStatus status) override; + + // content::WebContentsObserver implementation. + bool OnMessageReceived(const IPC::Message& message) override; + + // IPC Message handlers. + virtual void OnPrintingFailed(int cookie); + + private: + // content::NotificationObserver implementation. + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override; + + // content::WebContentsObserver implementation. + void DidStartLoading( + content::RenderViewHost* render_view_host) override; + + // Cancels the print job. + void NavigationStopped() override; + + // IPC Message handlers. + void OnDidGetPrintedPagesCount(int cookie, int number_pages); + void OnDidGetDocumentCookie(int cookie); + void OnDidPrintPage(const PrintHostMsg_DidPrintPage_Params& params); + void OnShowInvalidPrinterSettingsError(); + + // Processes a NOTIFY_PRINT_JOB_EVENT notification. + void OnNotifyPrintJobEvent(const JobEventDetails& event_details); + + // Requests the RenderView to render all the missing pages for the print job. + // No-op if no print job is pending. Returns true if at least one page has + // been requested to the renderer. + bool RenderAllMissingPagesNow(); + + // Quits the current message loop if these conditions hold true: a document is + // loaded and is complete and waiting_for_pages_to_be_rendered_ is true. This + // function is called in DidPrintPage() or on ALL_PAGES_REQUESTED + // notification. The inner message loop is created was created by + // RenderAllMissingPagesNow(). + void ShouldQuitFromInnerMessageLoop(); + + // Creates a new empty print job. It has no settings loaded. If there is + // currently a print job, safely disconnect from it. Returns false if it is + // impossible to safely disconnect from the current print job or it is + // impossible to create a new print job. + bool CreateNewPrintJob(PrintJobWorkerOwner* job); + + // Makes sure the current print_job_ has all its data before continuing, and + // disconnect from it. + void DisconnectFromCurrentPrintJob(); + + // Notify that the printing is done. + void PrintingDone(bool success); + + // Terminates the print job. No-op if no print job has been created. If + // |cancel| is true, cancel it instead of waiting for the job to finish. Will + // call ReleasePrintJob(). + void TerminatePrintJob(bool cancel); + + // Releases print_job_. Correctly deregisters from notifications. No-op if + // no print job has been created. + void ReleasePrintJob(); + + // Runs an inner message loop. It will set inside_inner_message_loop_ to true + // while the blocking inner message loop is running. This is useful in cases + // where the RenderView is about to be destroyed while a printing job isn't + // finished. + bool RunInnerMessageLoop(); + + // In the case of Scripted Printing, where the renderer is controlling the + // control flow, print_job_ is initialized whenever possible. No-op is + // print_job_ is initialized. + bool OpportunisticallyCreatePrintJob(int cookie); + + // Release the PrinterQuery associated with our |cookie_|. + void ReleasePrinterQuery(); + + content::NotificationRegistrar registrar_; + + // Manages the low-level talk to the printer. + scoped_refptr print_job_; + + // Number of pages to print in the print job. + int number_pages_; + + // Indication of success of the print job. + bool printing_succeeded_; + + // Running an inner message loop inside RenderAllMissingPagesNow(). This means + // we are _blocking_ until all the necessary pages have been rendered or the + // print settings are being loaded. + bool inside_inner_message_loop_; + +#if !defined(OS_MACOSX) + // Set to true when OnDidPrintPage() should be expecting the first page. + bool expecting_first_page_; +#endif // OS_MACOSX + + // The document cookie of the current PrinterQuery. + int cookie_; + + // Whether printing is enabled. + BooleanPrefMember printing_enabled_; + + scoped_refptr queue_; + + DISALLOW_COPY_AND_ASSIGN(PrintViewManagerBase); +}; + +} // namespace printing + +#endif // CEF_LIBCEF_BROWSER_PRINTING_PRINT_VIEW_MANAGER_BASE_H_ diff --git a/libcef/browser/printing/printing_message_filter.cc b/libcef/browser/printing/printing_message_filter.cc new file mode 100644 index 000000000..2612defc0 --- /dev/null +++ b/libcef/browser/printing/printing_message_filter.cc @@ -0,0 +1,423 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/printing/printing_message_filter.h" + +#include + +#include "base/bind.h" +#include "chrome/browser/browser_process.h" +#include "chrome/browser/printing/print_job_manager.h" +#include "chrome/browser/printing/printer_query.h" +#include "chrome/common/print_messages.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/child_process_host.h" + +#if defined(OS_CHROMEOS) +#include + +#include + +#include "base/files/file_util.h" +#include "base/lazy_instance.h" +#include "chrome/browser/printing/print_dialog_cloud.h" +#endif + +#if defined(OS_ANDROID) +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/printing/print_view_manager_basic.h" +#include "printing/printing_context_android.h" +#endif + +using content::BrowserThread; + +namespace printing { + +namespace { + +#if defined(OS_CHROMEOS) +typedef std::map SequenceToPathMap; + +struct PrintingSequencePathMap { + SequenceToPathMap map; + int sequence; +}; + +// No locking, only access on the FILE thread. +static base::LazyInstance + g_printing_file_descriptor_map = LAZY_INSTANCE_INITIALIZER; +#endif + +void RenderParamsFromPrintSettings(const PrintSettings& settings, + PrintMsg_Print_Params* params) { + params->page_size = settings.page_setup_device_units().physical_size(); + params->content_size.SetSize( + settings.page_setup_device_units().content_area().width(), + settings.page_setup_device_units().content_area().height()); + params->printable_area.SetRect( + settings.page_setup_device_units().printable_area().x(), + settings.page_setup_device_units().printable_area().y(), + settings.page_setup_device_units().printable_area().width(), + settings.page_setup_device_units().printable_area().height()); + params->margin_top = settings.page_setup_device_units().content_area().y(); + params->margin_left = settings.page_setup_device_units().content_area().x(); + params->dpi = settings.dpi(); + // Currently hardcoded at 1.25. See PrintSettings' constructor. + params->min_shrink = settings.min_shrink(); + // Currently hardcoded at 2.0. See PrintSettings' constructor. + params->max_shrink = settings.max_shrink(); + // Currently hardcoded at 72dpi. See PrintSettings' constructor. + params->desired_dpi = settings.desired_dpi(); + // Always use an invalid cookie. + params->document_cookie = 0; + params->selection_only = settings.selection_only(); + params->supports_alpha_blend = settings.supports_alpha_blend(); + params->should_print_backgrounds = settings.should_print_backgrounds(); + params->display_header_footer = settings.display_header_footer(); + params->title = settings.title(); + params->url = settings.url(); +} + +} // namespace + +PrintingMessageFilter::PrintingMessageFilter(int render_process_id) + : content::BrowserMessageFilter(PrintMsgStart), + render_process_id_(render_process_id), + queue_(g_browser_process->print_job_manager()->queue()) { + DCHECK(queue_.get()); +} + +PrintingMessageFilter::~PrintingMessageFilter() { +} + +void PrintingMessageFilter::OverrideThreadForMessage( + const IPC::Message& message, BrowserThread::ID* thread) { +#if defined(OS_CHROMEOS) + if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID || + message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) { + *thread = BrowserThread::FILE; + } +#elif defined(OS_ANDROID) + if (message.type() == PrintHostMsg_AllocateTempFileForPrinting::ID || + message.type() == PrintHostMsg_TempFileForPrintingWritten::ID) { + *thread = BrowserThread::UI; + } +#endif +} + +bool PrintingMessageFilter::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(PrintingMessageFilter, message) +#if defined(OS_WIN) + IPC_MESSAGE_HANDLER(PrintHostMsg_DuplicateSection, OnDuplicateSection) +#endif +#if defined(OS_CHROMEOS) || defined(OS_ANDROID) + IPC_MESSAGE_HANDLER(PrintHostMsg_AllocateTempFileForPrinting, + OnAllocateTempFileForPrinting) + IPC_MESSAGE_HANDLER(PrintHostMsg_TempFileForPrintingWritten, + OnTempFileForPrintingWritten) +#endif + IPC_MESSAGE_HANDLER(PrintHostMsg_IsPrintingEnabled, OnIsPrintingEnabled) + IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_GetDefaultPrintSettings, + OnGetDefaultPrintSettings) + IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_ScriptedPrint, OnScriptedPrint) + IPC_MESSAGE_HANDLER_DELAY_REPLY(PrintHostMsg_UpdatePrintSettings, + OnUpdatePrintSettings) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +#if defined(OS_WIN) +void PrintingMessageFilter::OnDuplicateSection( + base::SharedMemoryHandle renderer_handle, + base::SharedMemoryHandle* browser_handle) { + // Duplicate the handle in this process right now so the memory is kept alive + // (even if it is not mapped) + base::SharedMemory shared_buf(renderer_handle, true, PeerHandle()); + shared_buf.GiveToProcess(base::GetCurrentProcessHandle(), browser_handle); +} +#endif + +#if defined(OS_CHROMEOS) || defined(OS_ANDROID) +void PrintingMessageFilter::OnAllocateTempFileForPrinting( + int render_view_id, + base::FileDescriptor* temp_file_fd, + int* sequence_number) { +#if defined(OS_CHROMEOS) + // TODO(thestig): Use |render_view_id| for Chrome OS. + DCHECK_CURRENTLY_ON(BrowserThread::FILE); + temp_file_fd->fd = *sequence_number = -1; + temp_file_fd->auto_close = false; + + SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map; + *sequence_number = g_printing_file_descriptor_map.Get().sequence++; + + base::FilePath path; + if (base::CreateTemporaryFile(&path)) { + int fd = open(path.value().c_str(), O_WRONLY); + if (fd >= 0) { + SequenceToPathMap::iterator it = map->find(*sequence_number); + if (it != map->end()) { + NOTREACHED() << "Sequence number already in use. seq=" << + *sequence_number; + } else { + (*map)[*sequence_number] = path; + temp_file_fd->fd = fd; + temp_file_fd->auto_close = true; + } + } + } +#elif defined(OS_ANDROID) + DCHECK_CURRENTLY_ON(BrowserThread::UI); + content::WebContents* wc = GetWebContentsForRenderView(render_view_id); + if (!wc) + return; + PrintViewManagerBasic* print_view_manager = + PrintViewManagerBasic::FromWebContents(wc); + // The file descriptor is originally created in & passed from the Android + // side, and it will handle the closing. + const base::FileDescriptor& file_descriptor = + print_view_manager->file_descriptor(); + temp_file_fd->fd = file_descriptor.fd; + temp_file_fd->auto_close = false; +#endif +} + +void PrintingMessageFilter::OnTempFileForPrintingWritten(int render_view_id, + int sequence_number) { +#if defined(OS_CHROMEOS) + DCHECK_CURRENTLY_ON(BrowserThread::FILE); + SequenceToPathMap* map = &g_printing_file_descriptor_map.Get().map; + SequenceToPathMap::iterator it = map->find(sequence_number); + if (it == map->end()) { + NOTREACHED() << "Got a sequence that we didn't pass to the " + "renderer: " << sequence_number; + return; + } + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&PrintingMessageFilter::CreatePrintDialogForFile, + this, render_view_id, it->second)); + + // Erase the entry in the map. + map->erase(it); +#elif defined(OS_ANDROID) + DCHECK_CURRENTLY_ON(BrowserThread::UI); + content::WebContents* wc = GetWebContentsForRenderView(render_view_id); + if (!wc) + return; + PrintViewManagerBasic* print_view_manager = + PrintViewManagerBasic::FromWebContents(wc); + const base::FileDescriptor& file_descriptor = + print_view_manager->file_descriptor(); + PrintingContextAndroid::PdfWritingDone(file_descriptor.fd, true); + // Invalidate the file descriptor so it doesn't accidentally get reused. + print_view_manager->set_file_descriptor(base::FileDescriptor(-1, false)); +#endif +} +#endif // defined(OS_CHROMEOS) || defined(OS_ANDROID) + +#if defined(OS_CHROMEOS) +void PrintingMessageFilter::CreatePrintDialogForFile( + int render_view_id, + const base::FilePath& path) { + content::WebContents* wc = GetWebContentsForRenderView(render_view_id); + if (!wc) + return; + print_dialog_cloud::CreatePrintDialogForFile( + wc->GetBrowserContext(), + wc->GetTopLevelNativeWindow(), + path, + wc->GetTitle(), + base::string16(), + std::string("application/pdf")); +} +#endif // defined(OS_CHROMEOS) + +content::WebContents* PrintingMessageFilter::GetWebContentsForRenderView( + int render_view_id) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + content::RenderViewHost* view = content::RenderViewHost::FromID( + render_process_id_, render_view_id); + return view ? content::WebContents::FromRenderViewHost(view) : NULL; +} + +void PrintingMessageFilter::OnIsPrintingEnabled(bool* is_enabled) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + *is_enabled = true; +} + +void PrintingMessageFilter::OnGetDefaultPrintSettings(IPC::Message* reply_msg) { + DCHECK_CURRENTLY_ON(BrowserThread::IO); + scoped_refptr printer_query; + printer_query = queue_->PopPrinterQuery(0); + if (!printer_query.get()) { + printer_query = + queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id()); + } + + // Loads default settings. This is asynchronous, only the IPC message sender + // will hang until the settings are retrieved. + printer_query->GetSettings( + PrinterQuery::GetSettingsAskParam::DEFAULTS, + 0, + false, + DEFAULT_MARGINS, + false, + base::Bind(&PrintingMessageFilter::OnGetDefaultPrintSettingsReply, + this, + printer_query, + reply_msg)); +} + +void PrintingMessageFilter::OnGetDefaultPrintSettingsReply( + scoped_refptr printer_query, + IPC::Message* reply_msg) { + PrintMsg_Print_Params params; + if (!printer_query.get() || + printer_query->last_status() != PrintingContext::OK) { + params.Reset(); + } else { + RenderParamsFromPrintSettings(printer_query->settings(), ¶ms); + params.document_cookie = printer_query->cookie(); + } + PrintHostMsg_GetDefaultPrintSettings::WriteReplyParams(reply_msg, params); + Send(reply_msg); + // If printing was enabled. + if (printer_query.get()) { + // If user hasn't cancelled. + if (printer_query->cookie() && printer_query->settings().dpi()) { + queue_->QueuePrinterQuery(printer_query.get()); + } else { + printer_query->StopWorker(); + } + } +} + +void PrintingMessageFilter::OnScriptedPrint( + const PrintHostMsg_ScriptedPrint_Params& params, + IPC::Message* reply_msg) { + scoped_refptr printer_query = + queue_->PopPrinterQuery(params.cookie); + if (!printer_query.get()) { + printer_query = + queue_->CreatePrinterQuery(render_process_id_, reply_msg->routing_id()); + } + printer_query->GetSettings( + PrinterQuery::GetSettingsAskParam::ASK_USER, + params.expected_pages_count, + params.has_selection, + params.margin_type, + params.is_scripted, + base::Bind(&PrintingMessageFilter::OnScriptedPrintReply, + this, + printer_query, + reply_msg)); +} + +void PrintingMessageFilter::OnScriptedPrintReply( + scoped_refptr printer_query, + IPC::Message* reply_msg) { + PrintMsg_PrintPages_Params params; +#if defined(OS_ANDROID) + // We need to save the routing ID here because Send method below deletes the + // |reply_msg| before we can get the routing ID for the Android code. + int routing_id = reply_msg->routing_id(); +#endif + if (printer_query->last_status() != PrintingContext::OK || + !printer_query->settings().dpi()) { + params.Reset(); + } else { + RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params); + params.params.document_cookie = printer_query->cookie(); + params.pages = PageRange::GetPages(printer_query->settings().ranges()); + } + PrintHostMsg_ScriptedPrint::WriteReplyParams(reply_msg, params); + Send(reply_msg); + if (params.params.dpi && params.params.document_cookie) { +#if defined(OS_ANDROID) + int file_descriptor; + const base::string16& device_name = printer_query->settings().device_name(); + if (base::StringToInt(device_name, &file_descriptor)) { + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::Bind(&PrintingMessageFilter::UpdateFileDescriptor, this, + routing_id, file_descriptor)); + } +#endif + queue_->QueuePrinterQuery(printer_query.get()); + } else { + printer_query->StopWorker(); + } +} + +#if defined(OS_ANDROID) +void PrintingMessageFilter::UpdateFileDescriptor(int render_view_id, int fd) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + content::WebContents* wc = GetWebContentsForRenderView(render_view_id); + if (!wc) + return; + PrintViewManagerBasic* print_view_manager = + PrintViewManagerBasic::FromWebContents(wc); + print_view_manager->set_file_descriptor(base::FileDescriptor(fd, false)); +} +#endif + +void PrintingMessageFilter::OnUpdatePrintSettings( + int document_cookie, const base::DictionaryValue& job_settings, + IPC::Message* reply_msg) { + scoped_ptr new_settings(job_settings.DeepCopy()); + + scoped_refptr printer_query; + printer_query = queue_->PopPrinterQuery(document_cookie); + if (!printer_query.get()) { + int host_id = render_process_id_; + int routing_id = reply_msg->routing_id(); + if (!new_settings->GetInteger(printing::kPreviewInitiatorHostId, + &host_id) || + !new_settings->GetInteger(printing::kPreviewInitiatorRoutingId, + &routing_id)) { + host_id = content::ChildProcessHost::kInvalidUniqueID; + routing_id = content::ChildProcessHost::kInvalidUniqueID; + } + printer_query = queue_->CreatePrinterQuery(host_id, routing_id); + } + printer_query->SetSettings( + new_settings.Pass(), + base::Bind(&PrintingMessageFilter::OnUpdatePrintSettingsReply, this, + printer_query, reply_msg)); +} + +void PrintingMessageFilter::OnUpdatePrintSettingsReply( + scoped_refptr printer_query, + IPC::Message* reply_msg) { + PrintMsg_PrintPages_Params params; + if (!printer_query.get() || + printer_query->last_status() != PrintingContext::OK) { + params.Reset(); + } else { + RenderParamsFromPrintSettings(printer_query->settings(), ¶ms.params); + params.params.document_cookie = printer_query->cookie(); + params.pages = PageRange::GetPages(printer_query->settings().ranges()); + } + PrintHostMsg_UpdatePrintSettings::WriteReplyParams( + reply_msg, + params, + printer_query.get() && + (printer_query->last_status() == printing::PrintingContext::CANCEL)); + Send(reply_msg); + // If user hasn't cancelled. + if (printer_query.get()) { + if (printer_query->cookie() && printer_query->settings().dpi()) { + queue_->QueuePrinterQuery(printer_query.get()); + } else { + printer_query->StopWorker(); + } + } +} + +} // namespace printing diff --git a/libcef/browser/printing/printing_message_filter.h b/libcef/browser/printing/printing_message_filter.h new file mode 100644 index 000000000..f169b2368 --- /dev/null +++ b/libcef/browser/printing/printing_message_filter.h @@ -0,0 +1,117 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_PRINTING_PRINTING_MESSAGE_FILTER_H_ +#define CEF_LIBCEF_BROWSER_PRINTING_PRINTING_MESSAGE_FILTER_H_ + +#include + +#include "base/compiler_specific.h" +#include "content/public/browser/browser_message_filter.h" + +#if defined(OS_WIN) +#include "base/memory/shared_memory.h" +#endif + +struct PrintHostMsg_ScriptedPrint_Params; + +namespace base { +class DictionaryValue; +class FilePath; +} + +namespace content { +class WebContents; +} + +namespace printing { + +class PrintJobManager; +class PrintQueriesQueue; +class PrinterQuery; + +// This class filters out incoming printing related IPC messages for the +// renderer process on the IPC thread. +class PrintingMessageFilter : public content::BrowserMessageFilter { + public: + explicit PrintingMessageFilter(int render_process_id); + + // content::BrowserMessageFilter methods. + void OverrideThreadForMessage(const IPC::Message& message, + content::BrowserThread::ID* thread) override; + bool OnMessageReceived(const IPC::Message& message) override; + + private: + ~PrintingMessageFilter() override; + +#if defined(OS_WIN) + // Used to pass resulting EMF from renderer to browser in printing. + void OnDuplicateSection(base::SharedMemoryHandle renderer_handle, + base::SharedMemoryHandle* browser_handle); +#endif + +#if defined(OS_CHROMEOS) || defined(OS_ANDROID) + // Used to ask the browser allocate a temporary file for the renderer + // to fill in resulting PDF in renderer. + void OnAllocateTempFileForPrinting(int render_view_id, + base::FileDescriptor* temp_file_fd, + int* sequence_number); + void OnTempFileForPrintingWritten(int render_view_id, int sequence_number); +#endif + +#if defined(OS_CHROMEOS) + void CreatePrintDialogForFile(int render_view_id, const base::FilePath& path); +#endif + +#if defined(OS_ANDROID) + // Updates the file descriptor for the PrintViewManagerBasic of a given + // render_view_id. + void UpdateFileDescriptor(int render_view_id, int fd); +#endif + + // Given a render_view_id get the corresponding WebContents. + // Must be called on the UI thread. + content::WebContents* GetWebContentsForRenderView(int render_view_id); + + // GetPrintSettingsForRenderView must be called via PostTask and + // base::Bind. Collapse the settings-specific params into a + // struct to avoid running into issues with too many params + // to base::Bind. + struct GetPrintSettingsForRenderViewParams; + + // Checks if printing is enabled. + void OnIsPrintingEnabled(bool* is_enabled); + + // Get the default print setting. + void OnGetDefaultPrintSettings(IPC::Message* reply_msg); + void OnGetDefaultPrintSettingsReply(scoped_refptr printer_query, + IPC::Message* reply_msg); + + // The renderer host have to show to the user the print dialog and returns + // the selected print settings. The task is handled by the print worker + // thread and the UI thread. The reply occurs on the IO thread. + void OnScriptedPrint(const PrintHostMsg_ScriptedPrint_Params& params, + IPC::Message* reply_msg); + void OnScriptedPrintReply(scoped_refptr printer_query, + IPC::Message* reply_msg); + + // Modify the current print settings based on |job_settings|. The task is + // handled by the print worker thread and the UI thread. The reply occurs on + // the IO thread. + void OnUpdatePrintSettings(int document_cookie, + const base::DictionaryValue& job_settings, + IPC::Message* reply_msg); + void OnUpdatePrintSettingsReply(scoped_refptr printer_query, + IPC::Message* reply_msg); + + const int render_process_id_; + + scoped_refptr queue_; + + DISALLOW_COPY_AND_ASSIGN(PrintingMessageFilter); +}; + +} // namespace printing + +#endif // CEF_LIBCEF_BROWSER_PRINTING_PRINTING_MESSAGE_FILTER_H_ diff --git a/libcef/browser/process_util_impl.cc b/libcef/browser/process_util_impl.cc new file mode 100644 index 000000000..c73dea79d --- /dev/null +++ b/libcef/browser/process_util_impl.cc @@ -0,0 +1,31 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/cef_process_util.h" +#include "libcef/common/command_line_impl.h" + +#include "base/logging.h" +#include "base/process/launch.h" +#include "content/public/browser/browser_thread.h" + +bool CefLaunchProcess(CefRefPtr command_line) { + if (!command_line.get()) { + NOTREACHED() << "invalid parameter"; + return false; + } + + if (!content::BrowserThread::CurrentlyOn( + content::BrowserThread::PROCESS_LAUNCHER)) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + CefCommandLineImpl* impl = + static_cast(command_line.get()); + + CefValueController::AutoLock lock_scope(impl->controller()); + + base::LaunchOptions options; + return base::LaunchProcess(impl->command_line(), options, NULL); +} diff --git a/libcef/browser/proxy_stubs.cc b/libcef/browser/proxy_stubs.cc new file mode 100644 index 000000000..135c6af64 --- /dev/null +++ b/libcef/browser/proxy_stubs.cc @@ -0,0 +1,24 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/logging.h" +#include "content/public/browser/browser_context.h" + +// Used by chrome/browser/spellchecker/spellcheck_factory.cc. +namespace chrome { + +// Returns the original browser context even for Incognito contexts. +content::BrowserContext* GetBrowserContextRedirectedInIncognito( + content::BrowserContext* context) { + return context; +} + +// Returns non-NULL even for Incognito contexts so that a separate +// instance of a service is created for the Incognito context. +content::BrowserContext* GetBrowserContextOwnInstanceInIncognito( + content::BrowserContext* context) { + return context; +} + +} // namespace chrome diff --git a/libcef/browser/render_widget_host_view_osr.cc b/libcef/browser/render_widget_host_view_osr.cc new file mode 100644 index 000000000..2a1f25c5e --- /dev/null +++ b/libcef/browser/render_widget_host_view_osr.cc @@ -0,0 +1,1346 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/render_widget_host_view_osr.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/software_output_device_osr.h" +#include "libcef/browser/thread_util.h" + +#include "base/callback_helpers.h" +#include "base/command_line.h" +#include "cc/output/copy_output_request.h" +#include "cc/scheduler/delay_based_time_source.h" +#include "content/browser/compositor/image_transport_factory.h" +#include "content/browser/compositor/resize_lock.h" +#include "content/browser/renderer_host/dip_util.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/common/gpu/client/gl_helper.h" +#include "content/common/view_messages.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/context_factory.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/render_widget_host_view_frame_subscriber.h" +#include "content/public/common/content_switches.h" +#include "third_party/WebKit/public/platform/WebScreenInfo.h" +#include "ui/gfx/geometry/dip_util.h" +#include "ui/gfx/geometry/size_conversions.h" +#include "ui/gfx/image/image_skia_operations.h" + +namespace { + +const float kDefaultScaleFactor = 1.0; + +// The rate at which new calls to OnPaint will be generated. +const int kDefaultFrameRate = 30; +const int kMaximumFrameRate = 60; + +// The maximum number of retry counts if frame capture fails. +const int kFrameRetryLimit = 2; + +// When accelerated compositing is enabled and a widget resize is pending, +// we delay further resizes of the UI. The following constant is the maximum +// length of time that we should delay further UI resizes while waiting for a +// resized frame from a renderer. +const int kResizeLockTimeoutMs = 67; + +static blink::WebScreenInfo webScreenInfoFrom(const CefScreenInfo& src) { + blink::WebScreenInfo webScreenInfo; + webScreenInfo.deviceScaleFactor = src.device_scale_factor; + webScreenInfo.depth = src.depth; + webScreenInfo.depthPerComponent = src.depth_per_component; + webScreenInfo.isMonochrome = src.is_monochrome ? true : false; + webScreenInfo.rect = blink::WebRect(src.rect.x, src.rect.y, + src.rect.width, src.rect.height); + webScreenInfo.availableRect = blink::WebRect(src.available_rect.x, + src.available_rect.y, + src.available_rect.width, + src.available_rect.height); + + return webScreenInfo; +} + +// Used to prevent further resizes while a resize is pending. +class CefResizeLock : public content::ResizeLock { + public: + CefResizeLock(CefRenderWidgetHostViewOSR* host, + const gfx::Size new_size, + bool defer_compositor_lock, + double timeout) + : ResizeLock(new_size, defer_compositor_lock), + host_(host), + cancelled_(false), + weak_ptr_factory_(this) { + DCHECK(host_); + host_->HoldResize(); + + CEF_POST_DELAYED_TASK( + CEF_UIT, + base::Bind(&CefResizeLock::CancelLock, + weak_ptr_factory_.GetWeakPtr()), + timeout); + } + + ~CefResizeLock() override { + CancelLock(); + } + + bool GrabDeferredLock() override { + return ResizeLock::GrabDeferredLock(); + } + + void UnlockCompositor() override { + ResizeLock::UnlockCompositor(); + compositor_lock_ = NULL; + } + + protected: + void LockCompositor() override { + ResizeLock::LockCompositor(); + compositor_lock_ = host_->compositor()->GetCompositorLock(); + } + + void CancelLock() { + if (cancelled_) + return; + cancelled_ = true; + UnlockCompositor(); + host_->ReleaseResize(); + } + + private: + CefRenderWidgetHostViewOSR* host_; + scoped_refptr compositor_lock_; + bool cancelled_; + base::WeakPtrFactory weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(CefResizeLock); +}; + +} // namespace + +// Used for managing copy requests when GPU compositing is enabled. Based on +// RendererOverridesHandler::InnerSwapCompositorFrame and +// DelegatedFrameHost::CopyFromCompositingSurface. +class CefCopyFrameGenerator { + public: + CefCopyFrameGenerator(int frame_rate_threshold_ms, + CefRenderWidgetHostViewOSR* view) + : frame_rate_threshold_ms_(frame_rate_threshold_ms), + view_(view), + frame_pending_(false), + frame_in_progress_(false), + frame_retry_count_(0), + weak_ptr_factory_(this) { + } + + void GenerateCopyFrame( + bool force_frame, + const gfx::Rect& damage_rect) { + if (force_frame && !frame_pending_) + frame_pending_ = true; + + // No frame needs to be generated at this time. + if (!frame_pending_) + return; + + // Keep track of |damage_rect| for when the next frame is generated. + if (!damage_rect.IsEmpty()) + pending_damage_rect_.Union(damage_rect); + + // Don't attempt to generate a frame while one is currently in-progress. + if (frame_in_progress_) + return; + frame_in_progress_ = true; + + // Don't exceed the frame rate threshold. + const int64 frame_rate_delta = + (base::TimeTicks::Now() - frame_start_time_).InMilliseconds(); + if (frame_rate_delta < frame_rate_threshold_ms_) { + // Generate the frame after the necessary time has passed. + CEF_POST_DELAYED_TASK(CEF_UIT, + base::Bind(&CefCopyFrameGenerator::InternalGenerateCopyFrame, + weak_ptr_factory_.GetWeakPtr()), + frame_rate_threshold_ms_ - frame_rate_delta); + return; + } + + InternalGenerateCopyFrame(); + } + + bool frame_pending() const { return frame_pending_; } + + private: + void InternalGenerateCopyFrame() { + frame_pending_ = false; + frame_start_time_ = base::TimeTicks::Now(); + + if (!view_->render_widget_host()) + return; + + const gfx::Rect damage_rect = pending_damage_rect_; + pending_damage_rect_.SetRect(0, 0, 0, 0); + + // The below code is similar in functionality to + // DelegatedFrameHost::CopyFromCompositingSurface but we reuse the same + // SkBitmap in the GPU codepath and avoid scaling where possible. + scoped_ptr request = + cc::CopyOutputRequest::CreateRequest(base::Bind( + &CefCopyFrameGenerator::CopyFromCompositingSurfaceHasResult, + weak_ptr_factory_.GetWeakPtr(), + damage_rect)); + + request->set_area(gfx::Rect(view_->GetPhysicalBackingSize())); + view_->RequestCopyOfOutput(request.Pass()); + } + + void CopyFromCompositingSurfaceHasResult( + const gfx::Rect& damage_rect, + scoped_ptr result) { + if (result->IsEmpty() || result->size().IsEmpty() || + !view_->render_widget_host()) { + OnCopyFrameCaptureFailure(damage_rect); + return; + } + + if (result->HasTexture()) { + PrepareTextureCopyOutputResult(damage_rect, result.Pass()); + return; + } + + DCHECK(result->HasBitmap()); + PrepareBitmapCopyOutputResult(damage_rect, result.Pass()); + } + + void PrepareTextureCopyOutputResult( + const gfx::Rect& damage_rect, + scoped_ptr result) { + DCHECK(result->HasTexture()); + base::ScopedClosureRunner scoped_callback_runner( + base::Bind(&CefCopyFrameGenerator::OnCopyFrameCaptureFailure, + weak_ptr_factory_.GetWeakPtr(), + damage_rect)); + + const gfx::Size& result_size = result->size(); + SkIRect bitmap_size; + if (bitmap_) + bitmap_->getBounds(&bitmap_size); + + if (!bitmap_ || + bitmap_size.width() != result_size.width() || + bitmap_size.height() != result_size.height()) { + // Create a new bitmap if the size has changed. + bitmap_.reset(new SkBitmap); + bitmap_->allocN32Pixels(result_size.width(), + result_size.height(), + true); + if (bitmap_->drawsNothing()) + return; + } + + content::ImageTransportFactory* factory = + content::ImageTransportFactory::GetInstance(); + content::GLHelper* gl_helper = factory->GetGLHelper(); + if (!gl_helper) + return; + + scoped_ptr bitmap_pixels_lock( + new SkAutoLockPixels(*bitmap_)); + uint8* pixels = static_cast(bitmap_->getPixels()); + + cc::TextureMailbox texture_mailbox; + scoped_ptr release_callback; + result->TakeTexture(&texture_mailbox, &release_callback); + DCHECK(texture_mailbox.IsTexture()); + if (!texture_mailbox.IsTexture()) + return; + + ignore_result(scoped_callback_runner.Release()); + + gl_helper->CropScaleReadbackAndCleanMailbox( + texture_mailbox.mailbox(), + texture_mailbox.sync_point(), + result_size, + gfx::Rect(result_size), + result_size, + pixels, + kN32_SkColorType, + base::Bind( + &CefCopyFrameGenerator::CopyFromCompositingSurfaceFinishedProxy, + weak_ptr_factory_.GetWeakPtr(), + base::Passed(&release_callback), + damage_rect, + base::Passed(&bitmap_), + base::Passed(&bitmap_pixels_lock)), + content::GLHelper::SCALER_QUALITY_FAST); + } + + static void CopyFromCompositingSurfaceFinishedProxy( + base::WeakPtr generator, + scoped_ptr release_callback, + const gfx::Rect& damage_rect, + scoped_ptr bitmap, + scoped_ptr bitmap_pixels_lock, + bool result) { + // This method may be called after the view has been deleted. + uint32 sync_point = 0; + if (result) { + content::GLHelper* gl_helper = + content::ImageTransportFactory::GetInstance()->GetGLHelper(); + sync_point = gl_helper->InsertSyncPoint(); + } + bool lost_resource = sync_point == 0; + release_callback->Run(sync_point, lost_resource); + + if (generator) { + generator->CopyFromCompositingSurfaceFinished( + damage_rect, bitmap.Pass(), bitmap_pixels_lock.Pass(), result); + } else { + bitmap_pixels_lock.reset(); + bitmap.reset(); + } + } + + void CopyFromCompositingSurfaceFinished( + const gfx::Rect& damage_rect, + scoped_ptr bitmap, + scoped_ptr bitmap_pixels_lock, + bool result) { + // Restore ownership of the bitmap to the view. + DCHECK(!bitmap_); + bitmap_ = bitmap.Pass(); + + if (result) { + OnCopyFrameCaptureSuccess(damage_rect, *bitmap_, + bitmap_pixels_lock.Pass()); + } else { + bitmap_pixels_lock.reset(); + OnCopyFrameCaptureFailure(damage_rect); + } + } + + void PrepareBitmapCopyOutputResult( + const gfx::Rect& damage_rect, + scoped_ptr result) { + DCHECK(result->HasBitmap()); + scoped_ptr source = result->TakeBitmap(); + DCHECK(source); + if (source) { + scoped_ptr bitmap_pixels_lock( + new SkAutoLockPixels(*source)); + OnCopyFrameCaptureSuccess(damage_rect, *source, + bitmap_pixels_lock.Pass()); + } else { + OnCopyFrameCaptureFailure(damage_rect); + } + } + + void OnCopyFrameCaptureFailure( + const gfx::Rect& damage_rect) { + // Retry with the same |damage_rect|. + pending_damage_rect_.Union(damage_rect); + + const bool force_frame = (++frame_retry_count_ <= kFrameRetryLimit); + OnCopyFrameCaptureCompletion(force_frame); + } + + void OnCopyFrameCaptureSuccess( + const gfx::Rect& damage_rect, + const SkBitmap& bitmap, + scoped_ptr bitmap_pixels_lock) { + view_->OnPaint(damage_rect, bitmap.width(), bitmap.height(), + bitmap.getPixels()); + bitmap_pixels_lock.reset(); + + // Reset the frame retry count on successful frame generation. + if (frame_retry_count_ > 0) + frame_retry_count_ = 0; + + OnCopyFrameCaptureCompletion(false); + } + + void OnCopyFrameCaptureCompletion(bool force_frame) { + frame_in_progress_ = false; + + if (frame_pending_) { + // Another frame was requested while the current frame was in-progress. + // Generate the pending frame now. + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefCopyFrameGenerator::GenerateCopyFrame, + weak_ptr_factory_.GetWeakPtr(), + force_frame, + gfx::Rect())); + } + } + + const int frame_rate_threshold_ms_; + CefRenderWidgetHostViewOSR* view_; + + base::TimeTicks frame_start_time_; + bool frame_pending_; + bool frame_in_progress_; + int frame_retry_count_; + scoped_ptr bitmap_; + gfx::Rect pending_damage_rect_; + + base::WeakPtrFactory weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(CefCopyFrameGenerator); +}; + +// Used to control the VSync rate in subprocesses when BeginFrame scheduling is +// enabled. +class CefBeginFrameTimer : public cc::TimeSourceClient { + public: + CefBeginFrameTimer(int frame_rate_threshold_ms, + const base::Closure& callback) + : callback_(callback) { + time_source_ = cc::DelayBasedTimeSource::Create( + base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms), + content::BrowserThread::GetMessageLoopProxyForThread(CEF_UIT).get()); + time_source_->SetClient(this); + } + + void SetActive(bool active) { + time_source_->SetActive(active); + } + + bool IsActive() const { + return time_source_->Active(); + } + + private: + // cc::TimerSourceClient implementation. + void OnTimerTick() override { + callback_.Run(); + } + + const base::Closure callback_; + scoped_refptr time_source_; + + DISALLOW_COPY_AND_ASSIGN(CefBeginFrameTimer); +}; + + +CefRenderWidgetHostViewOSR::CefRenderWidgetHostViewOSR( + content::RenderWidgetHost* widget) + : scale_factor_(kDefaultScaleFactor), + frame_rate_threshold_ms_(0), + delegated_frame_host_(new content::DelegatedFrameHost(this)), + compositor_widget_(gfx::kNullAcceleratedWidget), + software_output_device_(NULL), + hold_resize_(false), + pending_resize_(false), + render_widget_host_(content::RenderWidgetHostImpl::From(widget)), + parent_host_view_(NULL), + popup_host_view_(NULL), + is_showing_(true), + is_destroyed_(false), + is_scroll_offset_changed_pending_(false), +#if defined(OS_MACOSX) + text_input_context_osr_mac_(NULL), +#endif + weak_ptr_factory_(this) { + DCHECK(render_widget_host_); + render_widget_host_->SetView(this); + + // CefBrowserHostImpl might not be created at this time for popups. + if (render_widget_host_->IsRenderView()) { + browser_impl_ = CefBrowserHostImpl::GetBrowserForHost( + content::RenderViewHost::From(render_widget_host_)); + } + + root_layer_.reset(new ui::Layer(ui::LAYER_SOLID_COLOR)); + + PlatformCreateCompositorWidget(); +#if !defined(OS_MACOSX) + // On OS X the ui::Compositor is created/owned by the platform view. + compositor_.reset( + new ui::Compositor(compositor_widget_, + content::GetContextFactory(), + base::MessageLoopProxy::current())); +#endif + compositor_->SetDelegate(this); + compositor_->SetRootLayer(root_layer_.get()); + + if (browser_impl_.get()) + ResizeRootLayer(); +} + +CefRenderWidgetHostViewOSR::~CefRenderWidgetHostViewOSR() { + // Marking the DelegatedFrameHost as removed from the window hierarchy is + // necessary to remove all connections to its old ui::Compositor. + if (is_showing_) + delegated_frame_host_->WasHidden(); + delegated_frame_host_->RemovingFromWindow(); + + PlatformDestroyCompositorWidget(); + + if (copy_frame_generator_.get()) + copy_frame_generator_.reset(NULL); + + delegated_frame_host_.reset(NULL); + compositor_.reset(NULL); + root_layer_.reset(NULL); +} + +void CefRenderWidgetHostViewOSR::InitAsChild(gfx::NativeView parent_view) { +} + +content::RenderWidgetHost* + CefRenderWidgetHostViewOSR::GetRenderWidgetHost() const { + return render_widget_host_; +} + +void CefRenderWidgetHostViewOSR::SetSize(const gfx::Size& size) { +} + +void CefRenderWidgetHostViewOSR::SetBounds(const gfx::Rect& rect) { +} + +gfx::Vector2dF CefRenderWidgetHostViewOSR::GetLastScrollOffset() const { + return last_scroll_offset_; +} + +gfx::NativeView CefRenderWidgetHostViewOSR::GetNativeView() const { + return gfx::NativeView(); +} + +gfx::NativeViewId CefRenderWidgetHostViewOSR::GetNativeViewId() const { + return gfx::NativeViewId(); +} + +gfx::NativeViewAccessible + CefRenderWidgetHostViewOSR::GetNativeViewAccessible() { + return gfx::NativeViewAccessible(); +} + +ui::TextInputClient* CefRenderWidgetHostViewOSR::GetTextInputClient() { + return NULL; +} + +void CefRenderWidgetHostViewOSR::Focus() { +} + +bool CefRenderWidgetHostViewOSR::HasFocus() const { + return false; +} + +bool CefRenderWidgetHostViewOSR::IsSurfaceAvailableForCopy() const { + return delegated_frame_host_->CanCopyToBitmap(); +} + +void CefRenderWidgetHostViewOSR::Show() { + WasShown(); +} + +void CefRenderWidgetHostViewOSR::Hide() { + WasHidden(); +} + +bool CefRenderWidgetHostViewOSR::IsShowing() { + return is_showing_; +} + +gfx::Rect CefRenderWidgetHostViewOSR::GetViewBounds() const { + if (IsPopupWidget()) + return popup_position_; + + if (!browser_impl_.get()) + return gfx::Rect(); + + CefRect rc; + browser_impl_->GetClient()->GetRenderHandler()->GetViewRect( + browser_impl_.get(), rc); + return gfx::Rect(rc.x, rc.y, rc.width, rc.height); +} + +void CefRenderWidgetHostViewOSR::SetBackgroundColor(SkColor color) { + content::RenderWidgetHostViewBase::SetBackgroundColor(color); + bool opaque = GetBackgroundOpaque(); + if (render_widget_host_) + render_widget_host_->SetBackgroundOpaque(opaque); +} + +bool CefRenderWidgetHostViewOSR::LockMouse() { + return false; +} + +void CefRenderWidgetHostViewOSR::UnlockMouse() { +} + +void CefRenderWidgetHostViewOSR::OnSwapCompositorFrame( + uint32 output_surface_id, + scoped_ptr frame) { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::OnSwapCompositorFrame"); + + if (frame->metadata.root_scroll_offset != last_scroll_offset_) { + last_scroll_offset_ = frame->metadata.root_scroll_offset; + + if (!is_scroll_offset_changed_pending_) { + // Send the notification asnychronously. + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefRenderWidgetHostViewOSR::OnScrollOffsetChanged, + weak_ptr_factory_.GetWeakPtr())); + } + } + + if (frame->delegated_frame_data) { + if (software_output_device_) { + if (!begin_frame_timer_.get()) { + // If BeginFrame scheduling is enabled SoftwareOutputDevice activity + // will be controlled via OnSetNeedsBeginFrames. Otherwise, activate + // the SoftwareOutputDevice now (when the first frame is generated). + software_output_device_->SetActive(true); + } + + // The compositor will draw directly to the SoftwareOutputDevice which + // then calls OnPaint. + delegated_frame_host_->SwapDelegatedFrame( + output_surface_id, + frame->delegated_frame_data.Pass(), + frame->metadata.device_scale_factor, + frame->metadata.latency_info); + } else { + if (!copy_frame_generator_.get()) { + copy_frame_generator_.reset( + new CefCopyFrameGenerator(frame_rate_threshold_ms_, this)); + } + + // Determine the damage rectangle for the current frame. This is the same + // calculation that SwapDelegatedFrame uses. + cc::RenderPass* root_pass = + frame->delegated_frame_data->render_pass_list.back(); + gfx::Size frame_size = root_pass->output_rect.size(); + gfx::Rect damage_rect = gfx::ToEnclosingRect(root_pass->damage_rect); + damage_rect.Intersect(gfx::Rect(frame_size)); + + delegated_frame_host_->SwapDelegatedFrame( + output_surface_id, + frame->delegated_frame_data.Pass(), + frame->metadata.device_scale_factor, + frame->metadata.latency_info); + + // Request a copy of the last compositor frame which will eventually call + // OnPaint asynchronously. + copy_frame_generator_->GenerateCopyFrame(true, damage_rect); + } + + return; + } + + if (frame->software_frame_data) { + DLOG(ERROR) << "Unable to use software frame in CEF windowless rendering"; + if (render_widget_host_) + render_widget_host_->GetProcess()->ReceivedBadMessage(); + return; + } +} + +void CefRenderWidgetHostViewOSR::InitAsPopup( + content::RenderWidgetHostView* parent_host_view, + const gfx::Rect& pos) { + parent_host_view_ = static_cast( + parent_host_view); + browser_impl_ = parent_host_view_->browser_impl(); + DCHECK(browser_impl_.get()); + + if (parent_host_view_->popup_host_view_) { + // Cancel the previous popup widget. + parent_host_view_->popup_host_view_->CancelPopupWidget(); + } + + parent_host_view_->set_popup_host_view(this); + browser_impl_->GetClient()->GetRenderHandler()->OnPopupShow( + browser_impl_.get(), true); + + popup_position_ = pos; + + CefRect widget_pos(pos.x(), pos.y(), pos.width(), pos.height()); + browser_impl_->GetClient()->GetRenderHandler()->OnPopupSize( + browser_impl_.get(), widget_pos); + + ResizeRootLayer(); + WasShown(); +} + +void CefRenderWidgetHostViewOSR::InitAsFullscreen( + content::RenderWidgetHostView* reference_host_view) { + NOTREACHED() << "Fullscreen widgets are not supported in OSR"; +} + +void CefRenderWidgetHostViewOSR::WasShown() { + if (is_showing_) + return; + + is_showing_ = true; + if (render_widget_host_) + render_widget_host_->WasShown(ui::LatencyInfo()); + delegated_frame_host_->AddedToWindow(); + delegated_frame_host_->WasShown(ui::LatencyInfo()); +} + +void CefRenderWidgetHostViewOSR::WasHidden() { + if (!is_showing_) + return; + + if (browser_impl_.get()) + browser_impl_->CancelContextMenu(); + + if (render_widget_host_) + render_widget_host_->WasHidden(); + delegated_frame_host_->WasHidden(); + delegated_frame_host_->RemovingFromWindow(); + is_showing_ = false; +} + +void CefRenderWidgetHostViewOSR::MovePluginWindows( + const std::vector& moves) { +} + +void CefRenderWidgetHostViewOSR::Blur() { +} + +void CefRenderWidgetHostViewOSR::UpdateCursor( + const content::WebCursor& cursor) { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::UpdateCursor"); + if (!browser_impl_.get()) + return; + + content::WebCursor::CursorInfo cursor_info; + cursor.GetCursorInfo(&cursor_info); + + const cef_cursor_type_t cursor_type = + static_cast(cursor_info.type); + CefCursorInfo custom_cursor_info; + if (cursor.IsCustom()) { + custom_cursor_info.hotspot.x = cursor_info.hotspot.x(); + custom_cursor_info.hotspot.y = cursor_info.hotspot.y(); + custom_cursor_info.image_scale_factor = cursor_info.image_scale_factor; + custom_cursor_info.buffer = cursor_info.custom_image.getPixels(); + custom_cursor_info.size.width = cursor_info.custom_image.width(); + custom_cursor_info.size.height = cursor_info.custom_image.height(); + } + +#if defined(USE_AURA) + content::WebCursor web_cursor = cursor; + + ui::PlatformCursor platform_cursor; + if (web_cursor.IsCustom()) { + // |web_cursor| owns the resulting |platform_cursor|. + platform_cursor = web_cursor.GetPlatformCursor(); + } else { + platform_cursor = browser_impl_->GetPlatformCursor(cursor_info.type); + } + + browser_impl_->GetClient()->GetRenderHandler()->OnCursorChange( + browser_impl_.get(), platform_cursor, cursor_type, custom_cursor_info); +#elif defined(OS_MACOSX) + // |web_cursor| owns the resulting |native_cursor|. + content::WebCursor web_cursor = cursor; + CefCursorHandle native_cursor = web_cursor.GetNativeCursor(); + browser_impl_->GetClient()->GetRenderHandler()->OnCursorChange( + browser_impl_.get(), native_cursor, cursor_type, custom_cursor_info); +#else + // TODO(port): Implement this method to work on other platforms as part of + // off-screen rendering support. + NOTREACHED(); +#endif +} + +void CefRenderWidgetHostViewOSR::SetIsLoading(bool is_loading) { +} + +#if !defined(OS_MACOSX) +void CefRenderWidgetHostViewOSR::TextInputTypeChanged(ui::TextInputType type, + ui::TextInputMode mode, + bool can_compose_inline, + int flags) { +} + +void CefRenderWidgetHostViewOSR::ImeCancelComposition() { +} +#endif // !defined(OS_MACOSX) + +void CefRenderWidgetHostViewOSR::RenderProcessGone( + base::TerminationStatus status, + int error_code) { + // TODO(OSR): Need to also clear WebContentsViewOSR::view_? + Destroy(); + render_widget_host_ = NULL; + parent_host_view_ = NULL; + popup_host_view_ = NULL; +} + +void CefRenderWidgetHostViewOSR::Destroy() { + if (!is_destroyed_) { + is_destroyed_ = true; + + if (IsPopupWidget()) { + CancelPopupWidget(); + } else { + if (popup_host_view_) + popup_host_view_->CancelPopupWidget(); + WasHidden(); + } + } + + delete this; +} + +void CefRenderWidgetHostViewOSR::SetTooltipText( + const base::string16& tooltip_text) { + if (!browser_impl_.get()) + return; + + CefString tooltip(tooltip_text); + CefRefPtr handler = + browser_impl_->GetClient()->GetDisplayHandler(); + if (handler.get()) { + handler->OnTooltip(browser_impl_.get(), tooltip); + } +} + +void CefRenderWidgetHostViewOSR::SelectionChanged( + const base::string16& text, + size_t offset, + const gfx::Range& range) { +} + +gfx::Size CefRenderWidgetHostViewOSR::GetRequestedRendererSize() const { + return delegated_frame_host_->GetRequestedRendererSize(); +} + +gfx::Size CefRenderWidgetHostViewOSR::GetPhysicalBackingSize() const { + return gfx::ConvertSizeToPixel(scale_factor_, GetRequestedRendererSize()); +} + +void CefRenderWidgetHostViewOSR::SelectionBoundsChanged( + const ViewHostMsg_SelectionBounds_Params& params) { +} + +void CefRenderWidgetHostViewOSR::CopyFromCompositingSurface( + const gfx::Rect& src_subrect, + const gfx::Size& dst_size, + content::ReadbackRequestCallback& callback, + const SkColorType color_type) { + delegated_frame_host_->CopyFromCompositingSurface( + src_subrect, dst_size, callback, color_type); +} + +void CefRenderWidgetHostViewOSR::CopyFromCompositingSurfaceToVideoFrame( + const gfx::Rect& src_subrect, + const scoped_refptr& target, + const base::Callback& callback) { + delegated_frame_host_->CopyFromCompositingSurfaceToVideoFrame( + src_subrect, target, callback); +} + +bool CefRenderWidgetHostViewOSR::CanCopyToVideoFrame() const { + return delegated_frame_host_->CanCopyToVideoFrame(); +} + +bool CefRenderWidgetHostViewOSR::CanSubscribeFrame() const { + return delegated_frame_host_->CanSubscribeFrame(); +} + +void CefRenderWidgetHostViewOSR::BeginFrameSubscription( + scoped_ptr subscriber) { + delegated_frame_host_->BeginFrameSubscription(subscriber.Pass()); +} + +void CefRenderWidgetHostViewOSR::EndFrameSubscription() { + delegated_frame_host_->EndFrameSubscription(); +} + +void CefRenderWidgetHostViewOSR::AcceleratedSurfaceInitialized( + int route_id) { +} + +bool CefRenderWidgetHostViewOSR::HasAcceleratedSurface( + const gfx::Size& desired_size) { + // CEF doesn't use GetBackingStore for accelerated pages, so it doesn't + // matter what is returned here as GetBackingStore is the only caller of this + // method. + NOTREACHED(); + return false; +} + +void CefRenderWidgetHostViewOSR::GetScreenInfo(blink::WebScreenInfo* results) { + if (!browser_impl_.get()) + return; + + CefScreenInfo screen_info( + kDefaultScaleFactor, 0, 0, false, CefRect(), CefRect()); + + CefRefPtr handler = + browser_impl_->client()->GetRenderHandler(); + if (!handler->GetScreenInfo(browser_impl_.get(), screen_info) || + screen_info.rect.width == 0 || + screen_info.rect.height == 0 || + screen_info.available_rect.width == 0 || + screen_info.available_rect.height == 0) { + // If a screen rectangle was not provided, try using the view rectangle + // instead. Otherwise, popup views may be drawn incorrectly, or not at all. + CefRect screenRect; + if (!handler->GetViewRect(browser_impl_.get(), screenRect)) { + NOTREACHED(); + screenRect = CefRect(); + } + + if (screen_info.rect.width == 0 && screen_info.rect.height == 0) + screen_info.rect = screenRect; + + if (screen_info.available_rect.width == 0 && + screen_info.available_rect.height == 0) + screen_info.available_rect = screenRect; + } + + *results = webScreenInfoFrom(screen_info); +} + +gfx::Rect CefRenderWidgetHostViewOSR::GetBoundsInRootWindow() { + if (!browser_impl_.get()) + return gfx::Rect(); + + CefRect rc; + if (browser_impl_->GetClient()->GetRenderHandler()->GetRootScreenRect( + browser_impl_.get(), rc)) { + return gfx::Rect(rc.x, rc.y, rc.width, rc.height); + } + return gfx::Rect(); +} + +gfx::GLSurfaceHandle CefRenderWidgetHostViewOSR::GetCompositingSurface() { + return content::ImageTransportFactory::GetInstance()-> + GetSharedSurfaceHandle(); +} + +content::BrowserAccessibilityManager* + CefRenderWidgetHostViewOSR::CreateBrowserAccessibilityManager( + content::BrowserAccessibilityDelegate* delegate) { + return NULL; +} + +#if defined(TOOLKIT_VIEWS) || defined(USE_AURA) +void CefRenderWidgetHostViewOSR::ShowDisambiguationPopup( + const gfx::Rect& rect_pixels, + const SkBitmap& zoomed_bitmap) { +} +#endif + +#if !defined(OS_MACOSX) && defined(USE_AURA) +void CefRenderWidgetHostViewOSR::ImeCompositionRangeChanged( + const gfx::Range& range, + const std::vector& character_bounds) { +} +#endif + +bool CefRenderWidgetHostViewOSR::OnMessageReceived(const IPC::Message& msg) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(CefRenderWidgetHostViewOSR, msg) + IPC_MESSAGE_HANDLER(ViewHostMsg_SetNeedsBeginFrames, + OnSetNeedsBeginFrames) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + + if (!handled) + return content::RenderWidgetHostViewBase::OnMessageReceived(msg); + return handled; +} + +void CefRenderWidgetHostViewOSR::OnSetNeedsBeginFrames(bool enabled) { + // Start/stop the timer that sends BeginFrame requests. + begin_frame_timer_->SetActive(enabled); + if (software_output_device_) { + // When the SoftwareOutputDevice is active it will call OnPaint for each + // frame. If the SoftwareOutputDevice is deactivated while an invalidation + // region is pending it will call OnPaint immediately. + software_output_device_->SetActive(enabled); + } +} + +scoped_ptr +CefRenderWidgetHostViewOSR::CreateSoftwareOutputDevice( + ui::Compositor* compositor) { + DCHECK_EQ(compositor_.get(), compositor); + DCHECK(!copy_frame_generator_); + DCHECK(!software_output_device_); + software_output_device_ = new CefSoftwareOutputDeviceOSR( + compositor, + browser_impl_.get() ? browser_impl_->IsTransparent() : false, + base::Bind(&CefRenderWidgetHostViewOSR::OnPaint, + weak_ptr_factory_.GetWeakPtr())); + return make_scoped_ptr(software_output_device_); +} + +ui::Compositor* CefRenderWidgetHostViewOSR::GetCompositor() const { + return compositor_.get(); +} + +ui::Layer* CefRenderWidgetHostViewOSR::GetLayer() { + return root_layer_.get(); +} + +content::RenderWidgetHostImpl* CefRenderWidgetHostViewOSR::GetHost() { + DCHECK(render_widget_host_); + return render_widget_host_; +} + +bool CefRenderWidgetHostViewOSR::IsVisible() { + return IsShowing(); +} + +scoped_ptr CefRenderWidgetHostViewOSR::CreateResizeLock( + bool defer_compositor_lock) { + const gfx::Size& desired_size = root_layer_->bounds().size(); + return scoped_ptr(new CefResizeLock( + this, + desired_size, + defer_compositor_lock, + kResizeLockTimeoutMs)); +} + +gfx::Size CefRenderWidgetHostViewOSR::DesiredFrameSize() { + return root_layer_->bounds().size(); +} + +float CefRenderWidgetHostViewOSR::CurrentDeviceScaleFactor() { + return scale_factor_; +} + +gfx::Size CefRenderWidgetHostViewOSR::ConvertViewSizeToPixel( + const gfx::Size& size) { + return content::ConvertViewSizeToPixel(this, size); +} + +content::DelegatedFrameHost* + CefRenderWidgetHostViewOSR::GetDelegatedFrameHost() const { + return delegated_frame_host_.get(); +} + +bool CefRenderWidgetHostViewOSR::InstallTransparency() { + if (browser_impl_.get() && browser_impl_->IsTransparent()) { + SetBackgroundColor(SkColorSetARGB(SK_AlphaTRANSPARENT, 0, 0, 0)); + compositor_->SetHostHasTransparentBackground(true); + return true; + } + return false; +} + +void CefRenderWidgetHostViewOSR::WasResized() { + if (hold_resize_) { + if (!pending_resize_) + pending_resize_ = true; + return; + } + + ResizeRootLayer(); + if (render_widget_host_) + render_widget_host_->WasResized(); + delegated_frame_host_->WasResized(); +} + +void CefRenderWidgetHostViewOSR::OnScreenInfoChanged() { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::OnScreenInfoChanged"); + if (!render_widget_host_) + return; + + // TODO(OSR): Update the backing store. + + render_widget_host_->NotifyScreenInfoChanged(); + // We might want to change the cursor scale factor here as well - see the + // cache for the current_cursor_, as passed by UpdateCursor from the renderer + // in the rwhv_aura (current_cursor_.SetScaleFactor) +} + +void CefRenderWidgetHostViewOSR::Invalidate( + CefBrowserHost::PaintElementType type) { + TRACE_EVENT1("libcef", "CefRenderWidgetHostViewOSR::Invalidate", "type", + type); + if (!IsPopupWidget() && type == PET_POPUP) { + if (popup_host_view_) + popup_host_view_->Invalidate(type); + return; + } + + const gfx::Rect& bounds_in_pixels = gfx::Rect(GetPhysicalBackingSize()); + + if (software_output_device_) { + if (IsFramePending()) { + // Include the invalidated region in the next frame generated. + software_output_device_->Invalidate(bounds_in_pixels); + } else { + // Call OnPaint immediately. + software_output_device_->OnPaint(bounds_in_pixels); + } + } else if (copy_frame_generator_.get()) { + copy_frame_generator_->GenerateCopyFrame(true, bounds_in_pixels); + } +} + +void CefRenderWidgetHostViewOSR::SendKeyEvent( + const content::NativeWebKeyboardEvent& event) { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::SendKeyEvent"); + if (!render_widget_host_) + return; + render_widget_host_->ForwardKeyboardEvent(event); +} + +void CefRenderWidgetHostViewOSR::SendMouseEvent( + const blink::WebMouseEvent& event) { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::SendMouseEvent"); + if (!IsPopupWidget()) { + if (browser_impl_.get() && event.type == blink::WebMouseEvent::MouseDown) + browser_impl_->CancelContextMenu(); + + if (popup_host_view_ && + popup_host_view_->popup_position_.Contains(event.x, event.y)) { + blink::WebMouseEvent popup_event(event); + popup_event.x -= popup_host_view_->popup_position_.x(); + popup_event.y -= popup_host_view_->popup_position_.y(); + popup_event.windowX = popup_event.x; + popup_event.windowY = popup_event.y; + + popup_host_view_->SendMouseEvent(popup_event); + return; + } + } + if (!render_widget_host_) + return; + render_widget_host_->ForwardMouseEvent(event); +} + +void CefRenderWidgetHostViewOSR::SendMouseWheelEvent( + const blink::WebMouseWheelEvent& event) { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::SendMouseWheelEvent"); + if (!IsPopupWidget()) { + if (browser_impl_.get()) + browser_impl_->CancelContextMenu(); + + if (popup_host_view_) { + if (popup_host_view_->popup_position_.Contains(event.x, event.y)) { + blink::WebMouseWheelEvent popup_event(event); + popup_event.x -= popup_host_view_->popup_position_.x(); + popup_event.y -= popup_host_view_->popup_position_.y(); + popup_event.windowX = popup_event.x; + popup_event.windowY = popup_event.y; + popup_host_view_->SendMouseWheelEvent(popup_event); + return; + } else { + // Scrolling outside of the popup widget so destroy it. + // Execute asynchronously to avoid deleting the widget from inside some + // other callback. + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefRenderWidgetHostViewOSR::CancelPopupWidget, + popup_host_view_->weak_ptr_factory_.GetWeakPtr())); + } + } + } + if (!render_widget_host_) + return; + render_widget_host_->ForwardWheelEvent(event); +} + +void CefRenderWidgetHostViewOSR::SendFocusEvent(bool focus) { + if (!render_widget_host_) + return; + + content::RenderWidgetHostImpl* widget = + content::RenderWidgetHostImpl::From(render_widget_host_); + if (focus) { + widget->GotFocus(); + widget->SetActive(true); + } else { + if (browser_impl_.get()) + browser_impl_->CancelContextMenu(); + + widget->SetActive(false); + widget->Blur(); + } +} + +void CefRenderWidgetHostViewOSR::HoldResize() { + if (!hold_resize_) + hold_resize_ = true; +} + +void CefRenderWidgetHostViewOSR::ReleaseResize() { + if (!hold_resize_) + return; + + hold_resize_ = false; + if (pending_resize_) { + pending_resize_ = false; + CEF_POST_TASK(CEF_UIT, + base::Bind(&CefRenderWidgetHostViewOSR::WasResized, + weak_ptr_factory_.GetWeakPtr())); + } +} + +void CefRenderWidgetHostViewOSR::OnPaint( + const gfx::Rect& damage_rect, + int bitmap_width, + int bitmap_height, + void* bitmap_pixels) { + TRACE_EVENT0("libcef", "CefRenderWidgetHostViewOSR::OnPaint"); + + // Don't execute WasResized while the OnPaint callback is pending. + HoldResize(); + + gfx::Rect rect_in_bitmap(0, 0, bitmap_width, bitmap_height); + rect_in_bitmap.Intersect(damage_rect); + + CefRenderHandler::RectList rcList; + rcList.push_back(CefRect(rect_in_bitmap.x(), rect_in_bitmap.y(), + rect_in_bitmap.width(), rect_in_bitmap.height())); + + browser_impl_->GetClient()->GetRenderHandler()->OnPaint( + browser_impl_.get(), + IsPopupWidget() ? PET_POPUP : PET_VIEW, + rcList, + bitmap_pixels, + bitmap_width, + bitmap_height); + + ReleaseResize(); +} + +void CefRenderWidgetHostViewOSR::SetFrameRate() { + DCHECK(browser_impl_.get()); + if (!browser_impl_.get()) + return; + + // Only set the frame rate one time. + if (frame_rate_threshold_ms_ != 0) + return; + + int frame_rate = browser_impl_->settings().windowless_frame_rate; + if (frame_rate < 1) + frame_rate = kDefaultFrameRate; + else if (frame_rate > kMaximumFrameRate) + frame_rate = kMaximumFrameRate; + frame_rate_threshold_ms_ = 1000 / frame_rate; + + // Configure the VSync interval for the browser process. + compositor_->vsync_manager()->SetAuthoritativeVSyncInterval( + base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms_)); + + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kEnableBeginFrameScheduling)) { + DCHECK(!begin_frame_timer_.get()); + begin_frame_timer_.reset(new CefBeginFrameTimer( + frame_rate_threshold_ms_, + base::Bind(&CefRenderWidgetHostViewOSR::OnBeginFrameTimerTick, + weak_ptr_factory_.GetWeakPtr()))); + } +} + +void CefRenderWidgetHostViewOSR::SetDeviceScaleFactor() { + if (browser_impl_.get()) { + CefScreenInfo screen_info( + kDefaultScaleFactor, 0, 0, false, CefRect(), CefRect()); + if (browser_impl_->GetClient()->GetRenderHandler()->GetScreenInfo( + browser_impl_.get(), screen_info)) { + scale_factor_ = screen_info.device_scale_factor; + return; + } + } + + scale_factor_ = kDefaultScaleFactor; +} + +void CefRenderWidgetHostViewOSR::ResizeRootLayer() { + SetFrameRate(); + SetDeviceScaleFactor(); + + gfx::Size size; + if (!IsPopupWidget()) + size = GetViewBounds().size(); + else + size = popup_position_.size(); + + if (size == root_layer_->bounds().size()) + return; + + const gfx::Size& size_in_pixels = + gfx::ConvertSizeToPixel(scale_factor_, size); + + root_layer_->SetBounds(gfx::Rect(size)); + compositor_->SetScaleAndSize(scale_factor_, size_in_pixels); +} + +bool CefRenderWidgetHostViewOSR::IsFramePending() { + if (!IsShowing()) + return false; + + if (begin_frame_timer_.get()) + return begin_frame_timer_->IsActive(); + else if (copy_frame_generator_.get()) + return copy_frame_generator_->frame_pending(); + + return false; +} + +void CefRenderWidgetHostViewOSR::OnBeginFrameTimerTick() { + const base::TimeTicks frame_time = base::TimeTicks::Now(); + const base::TimeDelta vsync_period = + base::TimeDelta::FromMilliseconds(frame_rate_threshold_ms_); + SendBeginFrame(frame_time, vsync_period); +} + +void CefRenderWidgetHostViewOSR::SendBeginFrame(base::TimeTicks frame_time, + base::TimeDelta vsync_period) { + TRACE_EVENT1("libcef", "CefRenderWidgetHostViewOSR::SendBeginFrame", + "frame_time_us", frame_time.ToInternalValue()); + + base::TimeTicks display_time = frame_time + vsync_period; + + // TODO(brianderson): Use adaptive draw-time estimation. + base::TimeDelta estimated_browser_composite_time = + base::TimeDelta::FromMicroseconds( + (1.0f * base::Time::kMicrosecondsPerSecond) / (3.0f * 60)); + + base::TimeTicks deadline = display_time - estimated_browser_composite_time; + + render_widget_host_->Send(new ViewMsg_BeginFrame( + render_widget_host_->GetRoutingID(), + cc::BeginFrameArgs::Create(BEGINFRAME_FROM_HERE, frame_time, deadline, + vsync_period, cc::BeginFrameArgs::NORMAL))); +} + +void CefRenderWidgetHostViewOSR::CancelPopupWidget() { + DCHECK(IsPopupWidget()); + + if (render_widget_host_) + render_widget_host_->LostCapture(); + + WasHidden(); + + if (browser_impl_.get()) { + browser_impl_->GetClient()->GetRenderHandler()->OnPopupShow( + browser_impl_.get(), false); + browser_impl_ = NULL; + } + + if (parent_host_view_) { + parent_host_view_->set_popup_host_view(NULL); + parent_host_view_ = NULL; + } + + if (render_widget_host_ && !is_destroyed_) { + is_destroyed_ = true; + // Results in a call to Destroy(). + render_widget_host_->Shutdown(); + } +} + +void CefRenderWidgetHostViewOSR::OnScrollOffsetChanged() { + if (browser_impl_.get()) { + CefRefPtr handler = + browser_impl_->client()->GetRenderHandler(); + handler->OnScrollOffsetChanged(browser_impl_.get()); + } + is_scroll_offset_changed_pending_ = false; +} diff --git a/libcef/browser/render_widget_host_view_osr.h b/libcef/browser/render_widget_host_view_osr.h new file mode 100644 index 000000000..b2e83d5ed --- /dev/null +++ b/libcef/browser/render_widget_host_view_osr.h @@ -0,0 +1,368 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_RENDER_WIDGET_HOST_VIEW_OSR_H_ +#define CEF_LIBCEF_BROWSER_RENDER_WIDGET_HOST_VIEW_OSR_H_ +#pragma once + +#include + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +#include "base/memory/weak_ptr.h" +#include "content/browser/compositor/delegated_frame_host.h" +#include "content/browser/renderer_host/render_widget_host_view_base.h" +#include "ui/compositor/compositor.h" + +#if defined(OS_MACOSX) +#include "content/browser/compositor/browser_compositor_view_mac.h" +#include "ui/accelerated_widget_mac/accelerated_widget_mac.h" +#endif + +#if defined(OS_WIN) +#include "ui/gfx/win/window_impl.h" +#endif + +namespace content { +class RenderWidgetHost; +class RenderWidgetHostImpl; +class BackingStore; +} + +class CefBeginFrameTimer; +class CefBrowserHostImpl; +class CefCopyFrameGenerator; +class CefSoftwareOutputDeviceOSR; +class CefWebContentsViewOSR; + +#if defined(OS_MACOSX) +#ifdef __OBJC__ +@class CALayer; +@class NSWindow; +#else +class CALayer; +class NSWindow; +#endif +#endif + +#if defined(USE_X11) +class CefWindowX11; +#endif + +/////////////////////////////////////////////////////////////////////////////// +// CefRenderWidgetHostViewOSR +// +// An object representing the "View" of a rendered web page. This object is +// responsible for sending paint events to the the CefRenderHandler +// when window rendering is disabled. It is the implementation of the +// RenderWidgetHostView that the cross-platform RenderWidgetHost object uses +// to display the data. +// +// Comment excerpted from render_widget_host.h: +// +// "The lifetime of the RenderWidgetHostView is tied to the render process. +// If the render process dies, the RenderWidgetHostView goes away and all +// references to it must become NULL." +// +// RenderWidgetHostView class hierarchy described in render_widget_host_view.h. +/////////////////////////////////////////////////////////////////////////////// + +class CefRenderWidgetHostViewOSR + : public content::RenderWidgetHostViewBase, +#if defined(OS_MACOSX) + public ui::AcceleratedWidgetMacNSView, +#endif + public ui::CompositorDelegate, + public content::DelegatedFrameHostClient { + public: + explicit CefRenderWidgetHostViewOSR(content::RenderWidgetHost* widget); + ~CefRenderWidgetHostViewOSR() override; + + // RenderWidgetHostView implementation. + void InitAsChild(gfx::NativeView parent_view) override; + content::RenderWidgetHost* GetRenderWidgetHost() const override; + void SetSize(const gfx::Size& size) override; + void SetBounds(const gfx::Rect& rect) override; + gfx::Vector2dF GetLastScrollOffset() const override; + gfx::NativeView GetNativeView() const override; + gfx::NativeViewId GetNativeViewId() const override; + gfx::NativeViewAccessible GetNativeViewAccessible() override; + ui::TextInputClient* GetTextInputClient() override; + void Focus() override; + bool HasFocus() const override; + bool IsSurfaceAvailableForCopy() const override; + void Show() override; + void Hide() override; + bool IsShowing() override; + gfx::Rect GetViewBounds() const override; + void SetBackgroundColor(SkColor color) override; + bool LockMouse() override; + void UnlockMouse() override; + +#if defined(OS_MACOSX) + void SetActive(bool active) override; + void SetWindowVisibility(bool visible) override; + void WindowFrameChanged() override; + void ShowDefinitionForSelection() override; + bool SupportsSpeech() const override; + void SpeakSelection() override; + bool IsSpeaking() const override; + void StopSpeaking() override; +#endif // defined(OS_MACOSX) + + // RenderWidgetHostViewBase implementation. + void OnSwapCompositorFrame( + uint32 output_surface_id, + scoped_ptr frame) override; + void InitAsPopup(content::RenderWidgetHostView* parent_host_view, + const gfx::Rect& pos) override; + void InitAsFullscreen( + content::RenderWidgetHostView* reference_host_view) override; + void WasShown() override; + void WasHidden() override; + void MovePluginWindows( + const std::vector& moves) override; + void Blur() override; + void UpdateCursor(const content::WebCursor& cursor) override; + void SetIsLoading(bool is_loading) override; + void TextInputTypeChanged(ui::TextInputType type, + ui::TextInputMode mode, + bool can_compose_inline, + int flags) override; + void ImeCancelComposition() override; + void RenderProcessGone(base::TerminationStatus status, + int error_code) override; + void Destroy() override; + void SetTooltipText(const base::string16& tooltip_text) override; + void SelectionChanged(const base::string16& text, + size_t offset, + const gfx::Range& range) override; + gfx::Size GetRequestedRendererSize() const override; + gfx::Size GetPhysicalBackingSize() const override; + void SelectionBoundsChanged( + const ViewHostMsg_SelectionBounds_Params& params) override; + void CopyFromCompositingSurface( + const gfx::Rect& src_subrect, + const gfx::Size& dst_size, + content::ReadbackRequestCallback& callback, + const SkColorType color_type) override; + void CopyFromCompositingSurfaceToVideoFrame( + const gfx::Rect& src_subrect, + const scoped_refptr& target, + const base::Callback& callback) override; + bool CanCopyToVideoFrame() const override; + bool CanSubscribeFrame() const override; + void BeginFrameSubscription( + scoped_ptr subscriber) + override; + void EndFrameSubscription() override; + void AcceleratedSurfaceInitialized(int route_id) override; + bool HasAcceleratedSurface(const gfx::Size& desired_size) override; + void GetScreenInfo(blink::WebScreenInfo* results) override; + gfx::Rect GetBoundsInRootWindow() override; + gfx::GLSurfaceHandle GetCompositingSurface() override; + content::BrowserAccessibilityManager* + CreateBrowserAccessibilityManager( + content::BrowserAccessibilityDelegate* delegate) override; + +#if defined(TOOLKIT_VIEWS) || defined(USE_AURA) + void ShowDisambiguationPopup(const gfx::Rect& rect_pixels, + const SkBitmap& zoomed_bitmap) override; +#endif + +#if defined(OS_MACOSX) + bool PostProcessEventForPluginIme( + const content::NativeWebKeyboardEvent& event) override; +#endif + +#if defined(OS_MACOSX) || defined(USE_AURA) + void ImeCompositionRangeChanged( + const gfx::Range& range, + const std::vector& character_bounds) override; +#endif + +#if defined(OS_WIN) + void SetParentNativeViewAccessible( + gfx::NativeViewAccessible accessible_parent) override; + gfx::NativeViewId GetParentForWindowlessPlugin() const override; +#endif + +#if defined(OS_MACOSX) + // AcceleratedWidgetMacNSView implementation. + NSView* AcceleratedWidgetGetNSView() const override; + bool AcceleratedWidgetShouldIgnoreBackpressure() const override; + void AcceleratedWidgetSwapCompleted( + const std::vector& latency_info) override; + void AcceleratedWidgetHitError() override; +#endif // defined(OS_MACOSX) + + bool OnMessageReceived(const IPC::Message& msg) override; + + // Message handlers. + void OnSetNeedsBeginFrames(bool enabled); + + // ui::CompositorDelegate implementation. + scoped_ptr CreateSoftwareOutputDevice( + ui::Compositor* compositor) override; + + // DelegatedFrameHostClient implementation. + ui::Compositor* GetCompositor() const override; + ui::Layer* GetLayer() override; + content::RenderWidgetHostImpl* GetHost() override; + bool IsVisible() override; + scoped_ptr CreateResizeLock( + bool defer_compositor_lock) override; + gfx::Size DesiredFrameSize() override; + float CurrentDeviceScaleFactor() override; + gfx::Size ConvertViewSizeToPixel(const gfx::Size& size) override; + content::DelegatedFrameHost* GetDelegatedFrameHost() const override; + + bool InstallTransparency(); + + void WasResized(); + void OnScreenInfoChanged(); + void Invalidate(CefBrowserHost::PaintElementType type); + void SendKeyEvent(const content::NativeWebKeyboardEvent& event); + void SendMouseEvent(const blink::WebMouseEvent& event); + void SendMouseWheelEvent(const blink::WebMouseWheelEvent& event); + void SendFocusEvent(bool focus); + + void HoldResize(); + void ReleaseResize(); + + void OnPaint(const gfx::Rect& damage_rect, + int bitmap_width, + int bitmap_height, + void* bitmap_pixels); + + bool IsPopupWidget() const { + return popup_type_ != blink::WebPopupTypeNone; + } + +#if defined(OS_MACOSX) + NSTextInputContext* GetNSTextInputContext(); + void HandleKeyEventBeforeTextInputClient(CefEventHandle keyEvent); + void HandleKeyEventAfterTextInputClient(CefEventHandle keyEvent); + + bool GetCachedFirstRectForCharacterRange(gfx::Range range, gfx::Rect* rect, + gfx::Range* actual_range) const; +#endif // defined(OS_MACOSX) + + CefRefPtr browser_impl() const { return browser_impl_; } + void set_browser_impl(CefRefPtr browser) { + browser_impl_ = browser; + } + + void set_popup_host_view(CefRenderWidgetHostViewOSR* popup_view) { + popup_host_view_ = popup_view; + } + + ui::Compositor* compositor() const { return compositor_.get(); } + content::RenderWidgetHostImpl* render_widget_host() const + { return render_widget_host_; } + + private: + void SetFrameRate(); + void SetDeviceScaleFactor(); + void ResizeRootLayer(); + + // Returns a best guess whether a frame is currently pending. + bool IsFramePending(); + + // Called by CefBeginFrameTimer to send a BeginFrame request. + void OnBeginFrameTimerTick(); + void SendBeginFrame(base::TimeTicks frame_time, + base::TimeDelta vsync_period); + + void CancelPopupWidget(); + + void OnScrollOffsetChanged(); + +#if defined(OS_MACOSX) + // Returns composition character boundary rectangle. The |range| is + // composition based range. Also stores |actual_range| which is corresponding + // to actually used range for returned rectangle. + gfx::Rect GetFirstRectForCompositionRange(const gfx::Range& range, + gfx::Range* actual_range) const; + + // Converts from given whole character range to composition oriented range. If + // the conversion failed, return gfx::Range::InvalidRange. + gfx::Range ConvertCharacterRangeToCompositionRange( + const gfx::Range& request_range) const; + + // Returns true if there is line break in |range| and stores line breaking + // point to |line_breaking_point|. The |line_break_point| is valid only if + // this function returns true. + static bool GetLineBreakIndex(const std::vector& bounds, + const gfx::Range& range, + size_t* line_break_point); + + void DestroyNSTextInputOSR(); +#endif // defined(OS_MACOSX) + + void PlatformCreateCompositorWidget(); + void PlatformDestroyCompositorWidget(); + + float scale_factor_; + int frame_rate_threshold_ms_; + + scoped_ptr delegated_frame_host_; + scoped_ptr compositor_; + gfx::AcceleratedWidget compositor_widget_; + scoped_ptr root_layer_; + +#if defined(OS_WIN) + scoped_ptr window_; +#elif defined(OS_MACOSX) + NSWindow* window_; + CALayer* background_layer_; + scoped_ptr browser_compositor_; +#elif defined(USE_X11) + CefWindowX11* window_; +#endif + + // Used to control the VSync rate in subprocesses when BeginFrame scheduling + // is enabled. + scoped_ptr begin_frame_timer_; + + // Used for direct rendering from the compositor when GPU compositing is + // disabled. This object is owned by the compositor. + CefSoftwareOutputDeviceOSR* software_output_device_; + + // Used for managing copy requests when GPU compositing is enabled. + scoped_ptr copy_frame_generator_; + + bool hold_resize_; + bool pending_resize_; + + // The associated Model. While |this| is being Destroyed, + // |render_widget_host_| is NULL and the message loop is run one last time + // Message handlers must check for a NULL |render_widget_host_|. + content::RenderWidgetHostImpl* render_widget_host_; + CefRenderWidgetHostViewOSR* parent_host_view_; + CefRenderWidgetHostViewOSR* popup_host_view_; + + CefRefPtr browser_impl_; + + bool is_showing_; + bool is_destroyed_; + gfx::Rect popup_position_; + + // The last scroll offset of the view. + gfx::Vector2dF last_scroll_offset_; + bool is_scroll_offset_changed_pending_; + +#if defined(OS_MACOSX) + NSTextInputContext* text_input_context_osr_mac_; +#endif + + base::WeakPtrFactory weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(CefRenderWidgetHostViewOSR); +}; + +#endif // CEF_LIBCEF_BROWSER_RENDER_WIDGET_HOST_VIEW_OSR_H_ + diff --git a/libcef/browser/render_widget_host_view_osr_linux.cc b/libcef/browser/render_widget_host_view_osr_linux.cc new file mode 100644 index 000000000..26cc247ab --- /dev/null +++ b/libcef/browser/render_widget_host_view_osr_linux.cc @@ -0,0 +1,25 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/render_widget_host_view_osr.h" + +#include + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/window_x11.h" + +#include "ui/gfx/x/x11_types.h" + +void CefRenderWidgetHostViewOSR::PlatformCreateCompositorWidget() { + // Create a hidden 1x1 window. It will delete itself on close. + window_ = new CefWindowX11(NULL, None, gfx::Rect(0, 0, 1, 1)); + compositor_widget_ = window_->xwindow(); +} + +void CefRenderWidgetHostViewOSR::PlatformDestroyCompositorWidget() { + DCHECK(window_); + window_->Close(); + compositor_widget_ = gfx::kNullAcceleratedWidget; +} diff --git a/libcef/browser/render_widget_host_view_osr_mac.mm b/libcef/browser/render_widget_host_view_osr_mac.mm new file mode 100644 index 000000000..3fcb842e8 --- /dev/null +++ b/libcef/browser/render_widget_host_view_osr_mac.mm @@ -0,0 +1,322 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/render_widget_host_view_osr.h" + +#import + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/text_input_client_osr_mac.h" + +#include "base/compiler_specific.h" +#include "ui/events/latency_info.h" + +namespace { + +CefTextInputClientOSRMac* GetInputClientFromContext( + const NSTextInputContext* context) { + if (!context) + return NULL; + return reinterpret_cast([context client]); +} + +} // namespace + +void CefRenderWidgetHostViewOSR::SetActive(bool active) { +} + +void CefRenderWidgetHostViewOSR::SetWindowVisibility(bool visible) { + if (visible) + WasShown(); + else + WasHidden(); +} + +void CefRenderWidgetHostViewOSR::WindowFrameChanged() { +} + +void CefRenderWidgetHostViewOSR::ShowDefinitionForSelection() { +} + +bool CefRenderWidgetHostViewOSR::SupportsSpeech() const { + return false; +} + +void CefRenderWidgetHostViewOSR::SpeakSelection() { +} + +bool CefRenderWidgetHostViewOSR::IsSpeaking() const { + return false; +} + +void CefRenderWidgetHostViewOSR::StopSpeaking() { +} + +void CefRenderWidgetHostViewOSR::TextInputTypeChanged(ui::TextInputType type, + ui::TextInputMode mode, + bool can_compose_inline, + int flags) { + [NSApp updateWindows]; +} + +void CefRenderWidgetHostViewOSR::ImeCancelComposition() { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + if (client) + [client cancelComposition]; +} + +bool CefRenderWidgetHostViewOSR::PostProcessEventForPluginIme( + const content::NativeWebKeyboardEvent& event) { + return false; +} + +void CefRenderWidgetHostViewOSR::ImeCompositionRangeChanged( + const gfx::Range& range, + const std::vector& character_bounds) { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + if (!client) + return; + + client->markedRange_ = range.ToNSRange(); + client->composition_range_ = range; + client->composition_bounds_ = character_bounds; +} + +NSView* CefRenderWidgetHostViewOSR::AcceleratedWidgetGetNSView() const { + return [window_ contentView]; +} + +bool CefRenderWidgetHostViewOSR::AcceleratedWidgetShouldIgnoreBackpressure() + const { + return true; +} + +void CefRenderWidgetHostViewOSR::AcceleratedWidgetSwapCompleted( + const std::vector& all_latency_info) { + if (!render_widget_host_) + return; + for (auto latency_info : all_latency_info) { + latency_info.AddLatencyNumber( + ui::INPUT_EVENT_LATENCY_TERMINATED_FRAME_SWAP_COMPONENT, 0, 0); + render_widget_host_->FrameSwapped(latency_info); + } +} + +void CefRenderWidgetHostViewOSR::AcceleratedWidgetHitError() { + // Request a new frame be drawn. + browser_compositor_->compositor()->ScheduleFullRedraw(); +} + +CefTextInputContext CefRenderWidgetHostViewOSR::GetNSTextInputContext() { + if (!text_input_context_osr_mac_) { + CefTextInputClientOSRMac* text_input_client_osr_mac = + [[CefTextInputClientOSRMac alloc] initWithRenderWidgetHostViewOSR: + this]; + + text_input_context_osr_mac_ = [[NSTextInputContext alloc] initWithClient: + text_input_client_osr_mac]; + } + + return text_input_context_osr_mac_; +} + +void CefRenderWidgetHostViewOSR::HandleKeyEventBeforeTextInputClient( + CefEventHandle keyEvent) { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + if (client) + [client HandleKeyEventBeforeTextInputClient: keyEvent]; +} + +void CefRenderWidgetHostViewOSR::HandleKeyEventAfterTextInputClient( + CefEventHandle keyEvent) { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + if (client) + [client HandleKeyEventAfterTextInputClient: keyEvent]; +} + +bool CefRenderWidgetHostViewOSR::GetCachedFirstRectForCharacterRange( + gfx::Range range, gfx::Rect* rect, gfx::Range* actual_range) const { + DCHECK(rect); + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + + // If requested range is same as caret location, we can just return it. + if (selection_range_.is_empty() && gfx::Range(range) == selection_range_) { + if (actual_range) + *actual_range = range; + *rect = client->caret_rect_; + return true; + } + + const gfx::Range request_range_in_composition = + ConvertCharacterRangeToCompositionRange(gfx::Range(range)); + if (request_range_in_composition == gfx::Range::InvalidRange()) + return false; + + // If firstRectForCharacterRange in WebFrame is failed in renderer, + // ImeCompositionRangeChanged will be sent with empty vector. + if (client->composition_bounds_.empty()) + return false; + + DCHECK_EQ(client->composition_bounds_.size(), + client->composition_range_.length()); + + gfx::Range ui_actual_range; + *rect = GetFirstRectForCompositionRange(request_range_in_composition, + &ui_actual_range); + if (actual_range) { + *actual_range = gfx::Range( + client->composition_range_.start() + ui_actual_range.start(), + client->composition_range_.start() + ui_actual_range.end()).ToNSRange(); + } + return true; +} + +gfx::Rect CefRenderWidgetHostViewOSR::GetFirstRectForCompositionRange( + const gfx::Range& range, gfx::Range* actual_range) const { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + + DCHECK(client); + DCHECK(actual_range); + DCHECK(!client->composition_bounds_.empty()); + DCHECK_LE(range.start(), client->composition_bounds_.size()); + DCHECK_LE(range.end(), client->composition_bounds_.size()); + + if (range.is_empty()) { + *actual_range = range; + if (range.start() == client->composition_bounds_.size()) { + return gfx::Rect(client->composition_bounds_[range.start() - 1].right(), + client->composition_bounds_[range.start() - 1].y(), + 0, + client->composition_bounds_[range.start() - 1].height()); + } else { + return gfx::Rect(client->composition_bounds_[range.start()].x(), + client->composition_bounds_[range.start()].y(), + 0, + client->composition_bounds_[range.start()].height()); + } + } + + size_t end_idx; + if (!GetLineBreakIndex(client->composition_bounds_, + range, &end_idx)) { + end_idx = range.end(); + } + *actual_range = gfx::Range(range.start(), end_idx); + gfx::Rect rect = client->composition_bounds_[range.start()]; + for (size_t i = range.start() + 1; i < end_idx; ++i) { + rect.Union(client->composition_bounds_[i]); + } + return rect; +} + +gfx::Range CefRenderWidgetHostViewOSR::ConvertCharacterRangeToCompositionRange( + const gfx::Range& request_range) const { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + DCHECK(client); + + if (client->composition_range_.is_empty()) + return gfx::Range::InvalidRange(); + + if (request_range.is_reversed()) + return gfx::Range::InvalidRange(); + + if (request_range.start() < client->composition_range_.start() + || request_range.start() > client->composition_range_.end() + || request_range.end() > client->composition_range_.end()) + return gfx::Range::InvalidRange(); + + return gfx::Range(request_range.start() - client->composition_range_.start(), + request_range.end() - client->composition_range_.start()); +} + +bool CefRenderWidgetHostViewOSR::GetLineBreakIndex( + const std::vector& bounds, + const gfx::Range& range, + size_t* line_break_point) { + DCHECK(line_break_point); + if (range.start() >= bounds.size() || range.is_reversed() || range.is_empty()) + return false; + + // We can't check line breaking completely from only rectangle array. Thus we + // assume the line breaking as the next character's y offset is larger than + // a threshold. Currently the threshold is determined as minimum y offset plus + // 75% of maximum height. + const size_t loop_end_idx = std::min(bounds.size(), range.end()); + int max_height = 0; + int min_y_offset = kint32max; + for (size_t idx = range.start(); idx < loop_end_idx; ++idx) { + max_height = std::max(max_height, bounds[idx].height()); + min_y_offset = std::min(min_y_offset, bounds[idx].y()); + } + int line_break_threshold = min_y_offset + (max_height * 3 / 4); + for (size_t idx = range.start(); idx < loop_end_idx; ++idx) { + if (bounds[idx].y() > line_break_threshold) { + *line_break_point = idx; + return true; + } + } + return false; +} + +void CefRenderWidgetHostViewOSR::DestroyNSTextInputOSR() { + CefTextInputClientOSRMac* client = GetInputClientFromContext( + text_input_context_osr_mac_); + if (client) { + [client release]; + client = NULL; + } + + [text_input_context_osr_mac_ release]; + text_input_context_osr_mac_ = NULL; +} + +void CefRenderWidgetHostViewOSR::PlatformCreateCompositorWidget() { + // Create a borderless non-visible 1x1 window. + window_ = [[NSWindow alloc] initWithContentRect:NSMakeRect(0, 0, 1, 1) + styleMask:NSBorderlessWindowMask + backing:NSBackingStoreBuffered + defer:NO]; + + // Create a CALayer which is used by BrowserCompositorViewMac for rendering. + background_layer_ = [[[CALayer alloc] init] retain]; + [background_layer_ setBackgroundColor:CGColorGetConstantColor(kCGColorClear)]; + NSView* content_view = [window_ contentView]; + [content_view setLayer:background_layer_]; + [content_view setWantsLayer:YES]; + + browser_compositor_ = content::BrowserCompositorMac::Create(); + compositor_.reset(browser_compositor_->compositor()); + compositor_->SetRootLayer(root_layer_.get()); + browser_compositor_->accelerated_widget_mac()->SetNSView(this); + browser_compositor_->compositor()->SetVisible(true); + + DCHECK(compositor_); +} + +void CefRenderWidgetHostViewOSR::PlatformDestroyCompositorWidget() { + DCHECK(window_); + + // Compositor is owned by and will be freed by BrowserCompositorMac. + ui::Compositor* compositor = compositor_.release(); + ALLOW_UNUSED_LOCAL(compositor); + + [window_ close]; + window_ = nil; + [background_layer_ release]; + background_layer_ = nil; + + browser_compositor_->accelerated_widget_mac()->ResetNSView(); + browser_compositor_->compositor()->SetVisible(false); + browser_compositor_->compositor()->SetScaleAndSize(1.0, gfx::Size(0, 0)); + browser_compositor_->compositor()->SetRootLayer(NULL); + content::BrowserCompositorMac::Recycle(browser_compositor_.Pass()); +} diff --git a/libcef/browser/render_widget_host_view_osr_win.cc b/libcef/browser/render_widget_host_view_osr_win.cc new file mode 100644 index 000000000..48e9829d3 --- /dev/null +++ b/libcef/browser/render_widget_host_view_osr_win.cc @@ -0,0 +1,59 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/render_widget_host_view_osr.h" +#include "libcef/browser/browser_host_impl.h" + +namespace { + +class CefCompositorHostWin : public gfx::WindowImpl { + public: + CefCompositorHostWin() { + // Create a hidden 1x1 borderless window. + set_window_style(WS_POPUP | WS_SYSMENU); + Init(NULL, gfx::Rect(0, 0, 1, 1)); + } + + ~CefCompositorHostWin() override { + DestroyWindow(hwnd()); + } + + private: + CR_BEGIN_MSG_MAP_EX(CompositorHostWin) + CR_MSG_WM_PAINT(OnPaint) + CR_END_MSG_MAP() + + void OnPaint(HDC dc) { + ValidateRect(hwnd(), NULL); + } + + DISALLOW_COPY_AND_ASSIGN(CefCompositorHostWin); +}; + +} // namespace + +void CefRenderWidgetHostViewOSR::SetParentNativeViewAccessible( + gfx::NativeViewAccessible accessible_parent) { +} + +gfx::NativeViewId + CefRenderWidgetHostViewOSR::GetParentForWindowlessPlugin() const { + if (browser_impl_.get()) { + return reinterpret_cast( + browser_impl_->GetWindowHandle()); + } + return NULL; +} + +void CefRenderWidgetHostViewOSR::PlatformCreateCompositorWidget() { + DCHECK(!window_); + window_.reset(new CefCompositorHostWin()); + compositor_widget_ = window_->hwnd(); +} + +void CefRenderWidgetHostViewOSR::PlatformDestroyCompositorWidget() { + window_.reset(NULL); + compositor_widget_ = gfx::kNullAcceleratedWidget; +} diff --git a/libcef/browser/request_context_impl.cc b/libcef/browser/request_context_impl.cc new file mode 100644 index 000000000..b2557c5c6 --- /dev/null +++ b/libcef/browser/request_context_impl.cc @@ -0,0 +1,112 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/request_context_impl.h" +#include "libcef/browser/browser_context_proxy.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" +#include "base/atomic_sequence_num.h" +#include "base/logging.h" + +namespace { + +void RemoveContextRef(CefBrowserContext* browser_context) { + CefContentBrowserClient::Get()->RemoveBrowserContextReference( + browser_context); +} + +base::StaticAtomicSequenceNumber g_next_id; + +} // namespace + +// Static functions + +CefRefPtr CefRequestContext::GetGlobalContext() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return NULL; + } + + return new CefRequestContextImpl( + CefContentBrowserClient::Get()->browser_context()); +} + +CefRefPtr CefRequestContext::CreateContext( + CefRefPtr handler) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return NULL; + } + + return new CefRequestContextImpl(handler); +} + +// CefBrowserContextImpl + +CefRequestContextImpl::CefRequestContextImpl( + CefBrowserContext* browser_context) + : browser_context_(browser_context), + unique_id_(0) { + DCHECK(browser_context); + if (!IsGlobal()) { + CEF_REQUIRE_UIT(); + CefBrowserContextProxy* proxy = + static_cast(browser_context); + handler_ = proxy->handler(); + CefContentBrowserClient::Get()->AddBrowserContextReference(browser_context); + } +} + +CefRequestContextImpl::CefRequestContextImpl( + CefRefPtr handler) + : browser_context_(NULL), + handler_(handler), + unique_id_(g_next_id.GetNext()) { +} + +CefRequestContextImpl::~CefRequestContextImpl() { + if (browser_context_) { + if (CEF_CURRENTLY_ON_UIT()) + RemoveContextRef(browser_context_); + else + CEF_POST_TASK(CEF_UIT, base::Bind(RemoveContextRef, browser_context_)); + } +} + +CefBrowserContext* CefRequestContextImpl::GetOrCreateBrowserContext() { + CEF_REQUIRE_UIT(); + if (!browser_context_) { + browser_context_ = + CefContentBrowserClient::Get()->CreateBrowserContextProxy(handler_); + } + return browser_context_; +} + +bool CefRequestContextImpl::IsSame(CefRefPtr other) { + CefRequestContextImpl* impl = + static_cast(other.get()); + if (!impl) + return false; + + // Compare CefBrowserContext points if one has been associated. + if (browser_context_ && impl->browser_context_) + return (browser_context_ == impl->browser_context_); + else if (browser_context_ || impl->browser_context_) + return false; + + // Otherwise compare unique IDs. + return (unique_id_ == impl->unique_id_); +} + +bool CefRequestContextImpl::IsGlobal() { + return (browser_context_ == + CefContentBrowserClient::Get()->browser_context()); +} + +CefRefPtr CefRequestContextImpl::GetHandler() { + return handler_; +} diff --git a/libcef/browser/request_context_impl.h b/libcef/browser/request_context_impl.h new file mode 100644 index 000000000..346005e8e --- /dev/null +++ b/libcef/browser/request_context_impl.h @@ -0,0 +1,37 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_REQUEST_CONTEXT_IMPL_H_ +#define CEF_LIBCEF_REQUEST_CONTEXT_IMPL_H_ +#pragma once + +#include "include/cef_request_context.h" + +class CefBrowserContext; + +class CefRequestContextImpl : public CefRequestContext { + public: + explicit CefRequestContextImpl(CefBrowserContext* browser_context); + explicit CefRequestContextImpl(CefRefPtr handler); + ~CefRequestContextImpl() override; + + CefBrowserContext* GetOrCreateBrowserContext(); + + bool IsSame(CefRefPtr other) override; + bool IsGlobal() override; + CefRefPtr GetHandler() override; + + protected: + CefBrowserContext* browser_context_; + CefRefPtr handler_; + + // Used to uniquely identify CefRequestContext objects before an associated + // CefBrowserContext has been created. + int unique_id_; + + IMPLEMENT_REFCOUNTING(CefRequestContextImpl); + DISALLOW_COPY_AND_ASSIGN(CefRequestContextImpl); +}; + +#endif // CEF_LIBCEF_REQUEST_CONTEXT_IMPL_H_ diff --git a/libcef/browser/resource_dispatcher_host_delegate.cc b/libcef/browser/resource_dispatcher_host_delegate.cc new file mode 100644 index 000000000..b64721eaa --- /dev/null +++ b/libcef/browser/resource_dispatcher_host_delegate.cc @@ -0,0 +1,120 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/resource_dispatcher_host_delegate.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/origin_whitelist_impl.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/request_impl.h" + +#include "base/memory/scoped_vector.h" +#include "components/navigation_interception/intercept_navigation_resource_throttle.h" +#include "components/navigation_interception/navigation_params.h" +#include "content/public/browser/resource_request_info.h" +#include "content/public/common/resource_response.h" +#include "net/http/http_response_headers.h" +#include "net/url_request/url_request.h" + +namespace { + +bool NavigationOnUIThread( + int64 frame_id, + CefRefPtr request, + content::WebContents* source, + const navigation_interception::NavigationParams& params) { + CEF_REQUIRE_UIT(); + + bool ignore_navigation = false; + + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForContents(source); + DCHECK(browser.get()); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr frame; + if (frame_id >= 0) + frame = browser->GetFrame(frame_id); + DCHECK(frame.get()); + if (frame.get()) { + ignore_navigation = handler->OnBeforeBrowse( + browser.get(), frame, request.get(), params.is_redirect()); + } + } + } + } + + return ignore_navigation; +} + +} // namespace + +CefResourceDispatcherHostDelegate::CefResourceDispatcherHostDelegate() { +} + +CefResourceDispatcherHostDelegate::~CefResourceDispatcherHostDelegate() { +} + +void CefResourceDispatcherHostDelegate::RequestBeginning( + net::URLRequest* request, + content::ResourceContext* resource_context, + content::AppCacheService* appcache_service, + content::ResourceType resource_type, + ScopedVector* throttles) { + if (resource_type == content::ResourceType::RESOURCE_TYPE_MAIN_FRAME || + resource_type == content::ResourceType::RESOURCE_TYPE_SUB_FRAME) { + int64 frame_id = -1; + + // ResourceRequestInfo will not exist for requests originating from + // WebURLLoader in the render process. + const content::ResourceRequestInfo* info = + content::ResourceRequestInfo::ForRequest(request); + if (info) + frame_id = info->GetRenderFrameID(); + + if (frame_id >= 0) { + CefRefPtr cef_request(new CefRequestImpl); + cef_request->Set(request); + cef_request->SetReadOnly(true); + + content::ResourceThrottle* throttle = + new navigation_interception::InterceptNavigationResourceThrottle( + request, + base::Bind(&NavigationOnUIThread, frame_id, cef_request)); + throttles->push_back(throttle); + } + } +} + +bool CefResourceDispatcherHostDelegate::HandleExternalProtocol( + const GURL& url, + int child_id, + int route_id) { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForView(child_id, route_id); + if (browser.get()) + browser->HandleExternalProtocol(url); + return false; +} + +void CefResourceDispatcherHostDelegate::OnRequestRedirected( + const GURL& redirect_url, + net::URLRequest* request, + content::ResourceContext* resource_context, + content::ResourceResponse* response) { + const GURL& active_url = request->url(); + if (active_url.is_valid() && redirect_url.is_valid() && + active_url.GetOrigin() != redirect_url.GetOrigin() && + HasCrossOriginWhitelistEntry(active_url, redirect_url)) { + if (!response->head.headers.get()) + response->head.headers = new net::HttpResponseHeaders(std::string()); + + // Add CORS headers to support XMLHttpRequest redirects. + response->head.headers->AddHeader("Access-Control-Allow-Origin: " + + active_url.scheme() + "://" + active_url.host()); + response->head.headers->AddHeader("Access-Control-Allow-Credentials: true"); + } +} diff --git a/libcef/browser/resource_dispatcher_host_delegate.h b/libcef/browser/resource_dispatcher_host_delegate.h new file mode 100644 index 000000000..cc9c0bff6 --- /dev/null +++ b/libcef/browser/resource_dispatcher_host_delegate.h @@ -0,0 +1,39 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ +#define CEF_LIBCEF_BROWSER_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ +#pragma once + +#include "base/compiler_specific.h" +#include "content/public/browser/resource_dispatcher_host_delegate.h" + +// Implements ResourceDispatcherHostDelegate. +class CefResourceDispatcherHostDelegate + : public content::ResourceDispatcherHostDelegate { + public: + CefResourceDispatcherHostDelegate(); + ~CefResourceDispatcherHostDelegate() override; + + // ResourceDispatcherHostDelegate methods. + void RequestBeginning( + net::URLRequest* request, + content::ResourceContext* resource_context, + content::AppCacheService* appcache_service, + content::ResourceType resource_type, + ScopedVector* throttles) override; + bool HandleExternalProtocol(const GURL& url, + int child_id, + int route_id) override; + void OnRequestRedirected( + const GURL& redirect_url, + net::URLRequest* request, + content::ResourceContext* resource_context, + content::ResourceResponse* response) override; + + private: + DISALLOW_COPY_AND_ASSIGN(CefResourceDispatcherHostDelegate); +}; + +#endif // CEF_LIBCEF_BROWSER_RESOURCE_DISPATCHER_HOST_DELEGATE_H_ diff --git a/libcef/browser/resource_request_job.cc b/libcef/browser/resource_request_job.cc new file mode 100644 index 000000000..d35a1996e --- /dev/null +++ b/libcef/browser/resource_request_job.cc @@ -0,0 +1,574 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/resource_request_job.h" + +#include +#include + +#include "include/cef_callback.h" +#include "libcef/browser/cookie_manager_impl.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/request_impl.h" +#include "libcef/common/response_impl.h" + +#include "base/logging.h" +#include "net/base/io_buffer.h" +#include "net/base/load_flags.h" +#include "net/base/mime_util.h" +#include "net/http/http_response_headers.h" +#include "net/url_request/http_user_agent_settings.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" + +using net::URLRequestStatus; + +namespace { + +bool SetHeaderIfMissing(CefRequest::HeaderMap& headerMap, + const std::string& name, + const std::string& value) { + if (value.empty()) + return false; + + CefRequest::HeaderMap::const_iterator it = headerMap.find(name); + if (it == headerMap.end()) { + headerMap.insert(std::make_pair(name, value)); + return true; + } + + return false; +} + +} // namespace + +// Client callback for asynchronous response continuation. +class CefResourceRequestJobCallback : public CefCallback { + public: + enum Type { + HEADERS_AVAILABLE, + BYTES_AVAILABLE, + }; + + explicit CefResourceRequestJobCallback(CefResourceRequestJob* job, Type type) + : job_(job), + type_(type), + dest_(NULL), + dest_size_(0) {} + + void Continue() override { + // Continue asynchronously. + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefResourceRequestJobCallback::ContinueOnIOThread, this)); + } + + void Cancel() override { + // Cancel asynchronously. + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefResourceRequestJobCallback::CancelOnIOThread, this)); + } + + void Detach() { + CEF_REQUIRE_IOT(); + job_ = NULL; + } + + void SetDestination(net::IOBuffer* dest, int dest_size) { + CEF_REQUIRE_IOT(); + // Should not be called multiple times while IO is pending. + DCHECK(!dest_); + + dest_ = dest; + dest_size_ = dest_size; + } + + private: + void ContinueOnIOThread() { + CEF_REQUIRE_IOT(); + + // Return early if the callback has already been detached. + if (!job_) + return; + + if (type_ == HEADERS_AVAILABLE) { + // Callback for headers available. + if (!job_->has_response_started()) { + // Send header information. + job_->SendHeaders(); + } + + // This type of callback only ever needs to be called once. + Detach(); + } else if (type_ == BYTES_AVAILABLE) { + // Callback for bytes available. + if (job_->has_response_started() && + job_->GetStatus().is_io_pending()) { + // Read the bytes. They should be available but, if not, wait again. + int bytes_read = 0; + if (job_->ReadRawData(dest_, dest_size_, &bytes_read)) { + // Must clear the members here because they may be reset as a result + // of calling NotifyReadComplete. + dest_size_ = 0; + dest_ = NULL; + + // Clear the IO_PENDING status. + job_->SetStatus(URLRequestStatus()); + + // Notify about the available bytes. If bytes_read > 0 then + // ReadRawData may be called from URLRequest::Read. If bytes_read == 0 + // then Kill will be called from the URLRequest destructor. + job_->NotifyReadComplete(bytes_read); + } else if (!job_->GetStatus().is_io_pending()) { + // Failed due to an error. + NOTREACHED() << + "ReadRawData returned false without setting IO as pending"; + job_->NotifyDone(URLRequestStatus()); + Detach(); + } + } + } + } + + void CancelOnIOThread() { + CEF_REQUIRE_IOT(); + + if (job_) + job_->Kill(); + } + + CefResourceRequestJob* job_; + Type type_; + + net::IOBuffer* dest_; + int dest_size_; + + IMPLEMENT_REFCOUNTING(CefResourceRequestJobCallback); +}; + +CefResourceRequestJob::CefResourceRequestJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + CefRefPtr handler) + : net::URLRequestJob(request, network_delegate), + handler_(handler), + done_(false), + remaining_bytes_(0), + response_cookies_save_index_(0), + weak_factory_(this) { +} + +CefResourceRequestJob::~CefResourceRequestJob() { +} + +void CefResourceRequestJob::Start() { + CEF_REQUIRE_IOT(); + + request_start_time_ = base::Time::Now(); + cef_request_ = CefRequest::Create(); + + // Populate the request data. + static_cast(cef_request_.get())->Set(request_); + + // Add default headers if not already specified. + const net::URLRequestContext* context = request_->context(); + if (context) { + CefRequest::HeaderMap headerMap; + cef_request_->GetHeaderMap(headerMap); + bool changed = false; + + const net::HttpUserAgentSettings* ua_settings = + context->http_user_agent_settings(); + if (ua_settings) { + if (SetHeaderIfMissing(headerMap, + net::HttpRequestHeaders::kAcceptLanguage, + ua_settings->GetAcceptLanguage())) { + changed = true; + } + + if (SetHeaderIfMissing(headerMap, + net::HttpRequestHeaders::kUserAgent, + ua_settings->GetUserAgent())) { + changed = true; + } + } + + if (changed) + cef_request_->SetHeaderMap(headerMap); + } + + AddCookieHeaderAndStart(); +} + +void CefResourceRequestJob::Kill() { + CEF_REQUIRE_IOT(); + + if (!done_) { + // Notify the handler that the request has been canceled. + handler_->Cancel(); + } + + if (callback_.get()) { + callback_->Detach(); + callback_ = NULL; + } + + net::URLRequestJob::Kill(); +} + +// This method will be called by URLRequestJob::Read and our callback. +// It can indicate the following states: +// 1. If the request is complete set |bytes_read| == 0 and return true. The +// caller is then responsible for calling NotifyReadComplete. ReadRawData +// should not be called again. +// 2. If data is available synchronously set |bytes_read| > 0 and return true. +// The caller is then responsible for calling NotifyReadComplete. ReadRawData +// may be called again by URLRequestJob::Read. +// 3. If data is not available now but may be available asynchronously set +// status to IO_PENDING and return false. When executed asynchronously the +// callback will again call ReadRawData. If data is returned at that time the +// callback will clear the status and call NotifyReadComplete. +bool CefResourceRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size, + int* bytes_read) { + CEF_REQUIRE_IOT(); + + DCHECK_NE(dest_size, 0); + DCHECK(bytes_read); + + if (remaining_bytes_ == 0) { + // No more data to read. + *bytes_read = 0; + done_ = true; + return true; + } else if (remaining_bytes_ > 0 && remaining_bytes_ < dest_size) { + // The handler knows the content size beforehand. + dest_size = static_cast(remaining_bytes_); + } + + if (!callback_.get()) { + // Create the bytes available callback that will be used until the request + // is completed. + callback_ = new CefResourceRequestJobCallback(this, + CefResourceRequestJobCallback::BYTES_AVAILABLE); + } + + // Read response data from the handler. + bool rv = handler_->ReadResponse(dest->data(), dest_size, *bytes_read, + callback_.get()); + if (!rv) { + // The handler has indicated completion of the request. + *bytes_read = 0; + done_ = true; + return true; + } else if (*bytes_read == 0) { + // Continue reading asynchronously. May happen multiple times in a row so + // only set IO pending the first time. + if (!GetStatus().is_io_pending()) { + SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); + callback_->SetDestination(dest, dest_size); + } + return false; + } else if (*bytes_read > dest_size) { + // Normalize the return value. + *bytes_read = dest_size; + } + + if (remaining_bytes_ > 0) + remaining_bytes_ -= *bytes_read; + + // Continue calling this method. + return true; +} + +void CefResourceRequestJob::GetResponseInfo(net::HttpResponseInfo* info) { + CEF_REQUIRE_IOT(); + + info->headers = GetResponseHeaders(); +} + +void CefResourceRequestJob::GetLoadTimingInfo( + net::LoadTimingInfo* load_timing_info) const { + // If haven't made it far enough to receive any headers, don't return + // anything. This makes for more consistent behavior in the case of errors. + if (!response_.get() || receive_headers_end_.is_null()) + return; + load_timing_info->request_start_time = request_start_time_; + load_timing_info->receive_headers_end = receive_headers_end_; +} + +bool CefResourceRequestJob::GetResponseCookies( + std::vector* cookies) { + CEF_REQUIRE_IOT(); + + cookies->clear(); + FetchResponseCookies(cookies); + return true; +} + +bool CefResourceRequestJob::IsRedirectResponse(GURL* location, + int* http_status_code) { + CEF_REQUIRE_IOT(); + + if (redirect_url_.is_valid()) { + // Redirect to the new URL. + *http_status_code = 303; + location->Swap(&redirect_url_); + return true; + } + + if (response_.get()) { + // Check for HTTP 302 or HTTP 303 redirect. + int status = response_->GetStatus(); + if (status == 302 || status == 303) { + CefResponse::HeaderMap headerMap; + response_->GetHeaderMap(headerMap); + CefRequest::HeaderMap::iterator iter = headerMap.find("Location"); + if (iter != headerMap.end()) { + GURL new_url = GURL(std::string(iter->second)); + *http_status_code = status; + location->Swap(&new_url); + return true; + } + } + } + + return false; +} + +bool CefResourceRequestJob::GetMimeType(std::string* mime_type) const { + CEF_REQUIRE_IOT(); + + if (response_.get()) + *mime_type = response_->GetMimeType(); + return true; +} + +void CefResourceRequestJob::SendHeaders() { + CEF_REQUIRE_IOT(); + + // Clear the headers available callback. + callback_ = NULL; + + // We may have been orphaned... + if (!request()) + return; + + response_ = new CefResponseImpl(); + remaining_bytes_ = 0; + + // Set the response mime type if it can be determined from the file extension. + if (request_->url().has_path()) { + const std::string& path = request_->url().path(); + size_t found = path.find_last_of("."); + if (found != std::string::npos) { + std::string suggest_mime_type; + if (net::GetWellKnownMimeTypeFromExtension( + base::FilePath::FromUTF8Unsafe(path.substr(found + 1)).value(), + &suggest_mime_type)) { + response_->SetMimeType(suggest_mime_type); + } + } + } + + CefString redirectUrl; + + // Get header information from the handler. + handler_->GetResponseHeaders(response_, remaining_bytes_, redirectUrl); + receive_headers_end_ = base::TimeTicks::Now(); + if (!redirectUrl.empty()) { + std::string redirectUrlStr = redirectUrl; + redirect_url_ = GURL(redirectUrlStr); + } + + if (remaining_bytes_ > 0) + set_expected_content_size(remaining_bytes_); + + // Continue processing the request. + SaveCookiesAndNotifyHeadersComplete(); +} + +void CefResourceRequestJob::AddCookieHeaderAndStart() { + // No matter what, we want to report our status as IO pending since we will + // be notifying our consumer asynchronously via OnStartCompleted. + SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); + + // If the request was destroyed, then there is no more work to do. + if (!request_) + return; + + net::CookieStore* cookie_store = + request_->context()->cookie_store(); + if (cookie_store && + !(request_->load_flags() & net::LOAD_DO_NOT_SEND_COOKIES)) { + net::CookieMonster* cookie_monster = cookie_store->GetCookieMonster(); + if (cookie_monster) { + cookie_monster->GetAllCookiesForURLAsync( + request_->url(), + base::Bind(&CefResourceRequestJob::CheckCookiePolicyAndLoad, + weak_factory_.GetWeakPtr())); + } else { + DoLoadCookies(); + } + } else { + DoStartTransaction(); + } +} + +void CefResourceRequestJob::DoLoadCookies() { + net::CookieOptions options; + options.set_include_httponly(); + request_->context()->cookie_store()->GetCookiesWithOptionsAsync( + request_->url(), options, + base::Bind(&CefResourceRequestJob::OnCookiesLoaded, + weak_factory_.GetWeakPtr())); +} + +void CefResourceRequestJob::CheckCookiePolicyAndLoad( + const net::CookieList& cookie_list) { + bool can_get_cookies = CanGetCookies(cookie_list); + if (can_get_cookies) { + net::CookieList::const_iterator it = cookie_list.begin(); + for (; it != cookie_list.end(); ++it) { + CefCookie cookie; + if (!CefCookieManagerImpl::GetCefCookie(*it, cookie) || + !handler_->CanGetCookie(cookie)) { + can_get_cookies = false; + break; + } + } + } + + if (can_get_cookies) + DoLoadCookies(); + else + DoStartTransaction(); +} + +void CefResourceRequestJob::OnCookiesLoaded(const std::string& cookie_line) { + if (!cookie_line.empty()) { + CefRequest::HeaderMap headerMap; + cef_request_->GetHeaderMap(headerMap); + headerMap.insert( + std::make_pair(net::HttpRequestHeaders::kCookie, cookie_line)); + cef_request_->SetHeaderMap(headerMap); + } + DoStartTransaction(); +} + +void CefResourceRequestJob::DoStartTransaction() { + // We may have been canceled while retrieving cookies. + if (GetStatus().is_success()) { + StartTransaction(); + } else { + NotifyCanceled(); + } +} + +void CefResourceRequestJob::StartTransaction() { + // Create the callback that will be used to notify when header information is + // available. + callback_ = new CefResourceRequestJobCallback(this, + CefResourceRequestJobCallback::HEADERS_AVAILABLE); + + // Protect against deletion of this object. + base::WeakPtr weak_ptr(weak_factory_.GetWeakPtr()); + + // Handler can decide whether to process the request. + bool rv = handler_->ProcessRequest(cef_request_, callback_.get()); + if (weak_ptr.get() && !rv) { + // Cancel the request. + NotifyCanceled(); + } +} + +net::HttpResponseHeaders* CefResourceRequestJob::GetResponseHeaders() { + DCHECK(response_.get()); + if (!response_headers_.get()) { + CefResponseImpl* responseImpl = + static_cast(response_.get()); + response_headers_ = responseImpl->GetResponseHeaders(); + } + return response_headers_.get(); +} + +void CefResourceRequestJob::SaveCookiesAndNotifyHeadersComplete() { + if (request_->load_flags() & net::LOAD_DO_NOT_SAVE_COOKIES) { + SetStatus(URLRequestStatus()); // Clear the IO_PENDING status + NotifyHeadersComplete(); + return; + } + + response_cookies_.clear(); + response_cookies_save_index_ = 0; + + FetchResponseCookies(&response_cookies_); + + // Now, loop over the response cookies, and attempt to persist each. + SaveNextCookie(); +} + +void CefResourceRequestJob::SaveNextCookie() { + if (response_cookies_save_index_ == response_cookies_.size()) { + response_cookies_.clear(); + response_cookies_save_index_ = 0; + SetStatus(URLRequestStatus()); // Clear the IO_PENDING status + NotifyHeadersComplete(); + return; + } + + // No matter what, we want to report our status as IO pending since we will + // be notifying our consumer asynchronously via OnStartCompleted. + SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0)); + + net::CookieOptions options; + options.set_include_httponly(); + bool can_set_cookie = CanSetCookie( + response_cookies_[response_cookies_save_index_], &options); + if (can_set_cookie) { + CefCookie cookie; + if (CefCookieManagerImpl::GetCefCookie(request_->url(), + response_cookies_[response_cookies_save_index_], cookie)) { + can_set_cookie = handler_->CanSetCookie(cookie); + } else { + can_set_cookie = false; + } + } + + if (can_set_cookie) { + request_->context()->cookie_store()->SetCookieWithOptionsAsync( + request_->url(), response_cookies_[response_cookies_save_index_], + options, base::Bind(&CefResourceRequestJob::OnCookieSaved, + weak_factory_.GetWeakPtr())); + return; + } + + CookieHandled(); +} + +void CefResourceRequestJob::OnCookieSaved(bool cookie_status) { + CookieHandled(); +} + +void CefResourceRequestJob::CookieHandled() { + response_cookies_save_index_++; + // We may have been canceled within OnSetCookie. + if (GetStatus().is_success()) { + SaveNextCookie(); + } else { + NotifyCanceled(); + } +} + +void CefResourceRequestJob::FetchResponseCookies( + std::vector* cookies) { + const std::string name = "Set-Cookie"; + std::string value; + + void* iter = NULL; + net::HttpResponseHeaders* headers = GetResponseHeaders(); + while (headers->EnumerateHeader(&iter, name, &value)) { + if (!value.empty()) + cookies->push_back(value); + } +} diff --git a/libcef/browser/resource_request_job.h b/libcef/browser/resource_request_job.h new file mode 100644 index 000000000..df32f2b6c --- /dev/null +++ b/libcef/browser/resource_request_job.h @@ -0,0 +1,84 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_RESOURCE_REQUEST_JOB_H_ +#define CEF_LIBCEF_BROWSER_RESOURCE_REQUEST_JOB_H_ + +#include + +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_request_handler.h" + +#include "net/cookies/cookie_monster.h" +#include "net/url_request/url_request_job.h" + +namespace net { +class HttpResponseHeaders; +class URLRequest; +} + +class CefResourceRequestJobCallback; + +class CefResourceRequestJob : public net::URLRequestJob { + public: + CefResourceRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + CefRefPtr handler); + ~CefResourceRequestJob() override; + + private: + // net::URLRequestJob methods. + void Start() override; + void Kill() override; + bool ReadRawData(net::IOBuffer* dest, int dest_size, int* bytes_read) override; + void GetResponseInfo(net::HttpResponseInfo* info) override; + void GetLoadTimingInfo( + net::LoadTimingInfo* load_timing_info) const override; + bool GetResponseCookies(std::vector* cookies) override; + bool IsRedirectResponse(GURL* location, int* http_status_code) + override; + bool GetMimeType(std::string* mime_type) const override; + + void SendHeaders(); + + // Used for sending cookies with the request. + void AddCookieHeaderAndStart(); + void DoLoadCookies(); + void CheckCookiePolicyAndLoad(const net::CookieList& cookie_list); + void OnCookiesLoaded(const std::string& cookie_line); + void DoStartTransaction(); + void StartTransaction(); + + // Used for saving cookies returned as part of the response. + net::HttpResponseHeaders* GetResponseHeaders(); + void SaveCookiesAndNotifyHeadersComplete(); + void SaveNextCookie(); + void OnCookieSaved(bool cookie_status); + void CookieHandled(); + void FetchResponseCookies(std::vector* cookies); + + CefRefPtr handler_; + bool done_; + CefRefPtr response_; + GURL redirect_url_; + int64 remaining_bytes_; + CefRefPtr cef_request_; + CefRefPtr callback_; + scoped_refptr response_headers_; + std::vector response_cookies_; + size_t response_cookies_save_index_; + base::Time request_start_time_; + base::TimeTicks receive_headers_end_; + + // Must be the last member. + base::WeakPtrFactory weak_factory_; + + friend class CefResourceRequestJobCallback; + + DISALLOW_COPY_AND_ASSIGN(CefResourceRequestJob); +}; + +#endif // CEF_LIBCEF_BROWSER_RESOURCE_REQUEST_JOB_H_ diff --git a/libcef/browser/scheme_handler.cc b/libcef/browser/scheme_handler.cc new file mode 100644 index 000000000..342d12517 --- /dev/null +++ b/libcef/browser/scheme_handler.cc @@ -0,0 +1,86 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/scheme_handler.h" + +#include + +#include "libcef/browser/chrome_scheme_handler.h" +#include "libcef/browser/devtools_scheme_handler.h" +#include "libcef/common/scheme_registration.h" + +#include "base/threading/sequenced_worker_pool.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/common/url_constants.h" +#include "net/url_request/data_protocol_handler.h" +#include "net/url_request/file_protocol_handler.h" +#include "net/url_request/ftp_protocol_handler.h" +#include "net/url_request/url_request_job_factory_impl.h" +#include "url/url_constants.h" + +namespace scheme { + +void InstallInternalProtectedHandlers( + net::URLRequestJobFactoryImpl* job_factory, + content::ProtocolHandlerMap* protocol_handlers, + net::FtpTransactionFactory* ftp_transaction_factory) { + protocol_handlers->insert( + std::make_pair(url::kDataScheme, + linked_ptr( + new net::DataProtocolHandler))); + protocol_handlers->insert( + std::make_pair(url::kFileScheme, + linked_ptr( + new net::FileProtocolHandler( + content::BrowserThread::GetBlockingPool()-> + GetTaskRunnerWithShutdownBehavior( + base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))))); +#if !defined(DISABLE_FTP_SUPPORT) + protocol_handlers->insert( + std::make_pair(url::kFtpScheme, + linked_ptr( + new net::FtpProtocolHandler(ftp_transaction_factory)))); +#endif + + for (content::ProtocolHandlerMap::iterator it = + protocol_handlers->begin(); + it != protocol_handlers->end(); + ++it) { + const std::string& scheme = it->first; + scoped_ptr protocol_handler; + + if (scheme == content::kChromeDevToolsScheme) { + // Don't use the default "chrome-devtools" handler. + continue; + } else if (scheme == content::kChromeUIScheme) { + // Filter the URLs that are passed to the default "chrome" handler so as + // not to interfere with CEF's "chrome" handler. + protocol_handler.reset( + scheme::WrapChromeProtocolHandler( + make_scoped_ptr(it->second.release())).release()); + } else { + protocol_handler.reset(it->second.release()); + } + + // Make sure IsInternalProtectedScheme() stays synchronized with what + // Chromium is actually giving us. + DCHECK(IsInternalProtectedScheme(scheme)); + + bool set_protocol = job_factory->SetProtocolHandler( + scheme, protocol_handler.release()); + DCHECK(set_protocol); + } +} + +void RegisterInternalHandlers() { + scheme::RegisterChromeHandler(); + scheme::RegisterChromeDevToolsHandler(); +} + +void DidFinishLoad(CefRefPtr frame, const GURL& validated_url) { + if (validated_url.scheme() == content::kChromeUIScheme) + scheme::DidFinishChromeLoad(frame, validated_url); +} + +} // namespace scheme diff --git a/libcef/browser/scheme_handler.h b/libcef/browser/scheme_handler.h new file mode 100644 index 000000000..062c5a24f --- /dev/null +++ b/libcef/browser/scheme_handler.h @@ -0,0 +1,36 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_SCHEME_HANDLER_H_ +#define CEF_LIBCEF_BROWSER_SCHEME_HANDLER_H_ +#pragma once + +#include "include/cef_frame.h" + +#include "content/public/browser/content_browser_client.h" +#include "url/gurl.h" + +namespace net { +class FtpTransactionFactory; +class URLRequestJobFactoryImpl; +} + +namespace scheme { + +// Install the internal scheme handlers provided by Chromium that cannot be +// overridden. +void InstallInternalProtectedHandlers( + net::URLRequestJobFactoryImpl* job_factory, + content::ProtocolHandlerMap* protocol_handlers, + net::FtpTransactionFactory* ftp_transaction_factory); + +// Register the internal scheme handlers that can be overridden. +void RegisterInternalHandlers(); + +// Used to fire any asynchronous content updates. +void DidFinishLoad(CefRefPtr frame, const GURL& validated_url); + +} // namespace scheme + +#endif // CEF_LIBCEF_BROWSER_SCHEME_HANDLER_H_ diff --git a/libcef/browser/scheme_impl.cc b/libcef/browser/scheme_impl.cc new file mode 100644 index 000000000..216a5b3c3 --- /dev/null +++ b/libcef/browser/scheme_impl.cc @@ -0,0 +1,362 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2006-2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include + +#include "include/cef_browser.h" +#include "include/cef_scheme.h" +#include "libcef/browser/browser_context.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/resource_request_job.h" +#include "libcef/browser/scheme_handler.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_context_getter.h" +#include "libcef/common/request_impl.h" +#include "libcef/common/response_impl.h" +#include "libcef/common/scheme_registration.h" +#include "libcef/common/upload_data.h" + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "base/strings/string_util.h" +#include "base/synchronization/lock.h" +#include "net/base/completion_callback.h" +#include "net/base/io_buffer.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_util.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_filter.h" +#include "net/url_request/url_request_http_job.h" +#include "net/url_request/url_request_job.h" +#include "net/url_request/url_request_job_factory_impl.h" +#include "url/third_party/mozilla/url_parse.h" +#include "url/url_util.h" + +using net::URLRequestStatus; + +namespace { + +bool IsStandardScheme(const std::string& scheme) { + url::Component scheme_comp(0, scheme.length()); + return url::IsStandard(scheme.c_str(), scheme_comp); +} + +// Copied from net/url_request/url_request_job_manager.cc. +struct SchemeToFactory { + const char* scheme; + net::URLRequest::ProtocolFactory* factory; +}; +static const SchemeToFactory kBuiltinFactories[] = { + { "http", net::URLRequestHttpJob::Factory }, + { "https", net::URLRequestHttpJob::Factory }, +}; + +bool IsBuiltinScheme(const std::string& scheme) { + for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) + if (LowerCaseEqualsASCII(scheme, kBuiltinFactories[i].scheme)) + return true; + return false; +} + +net::URLRequestJob* GetBuiltinSchemeRequestJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const std::string& scheme) { + // See if the request should be handled by a built-in protocol factory. + for (size_t i = 0; i < arraysize(kBuiltinFactories); ++i) { + if (scheme == kBuiltinFactories[i].scheme) { + net::URLRequestJob* job = + (kBuiltinFactories[i].factory)(request, network_delegate, scheme); + DCHECK(job); // The built-in factories are not expected to fail! + return job; + } + } + + return NULL; +} + +std::string ToLower(const std::string& str) { + std::string str_lower = str; + std::transform(str_lower.begin(), str_lower.end(), str_lower.begin(), + towlower); + return str; +} + +// Class that manages the CefSchemeHandlerFactory instances. +class CefUrlRequestManager { + protected: + // Class used for creating URLRequestJob instances. The lifespan of this + // object is managed by URLRequestJobFactory. + class ProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler { + public: + explicit ProtocolHandler(const std::string& scheme) + : scheme_(scheme) {} + + // From net::URLRequestJobFactory::ProtocolHandler + net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const override { + CEF_REQUIRE_IOT(); + return CefUrlRequestManager::GetInstance()->GetRequestJob( + request, network_delegate, scheme_); + } + + private: + std::string scheme_; + }; + + public: + CefUrlRequestManager() {} + + // Retrieve the singleton instance. + static CefUrlRequestManager* GetInstance(); + + bool AddFactory(const std::string& scheme, + const std::string& domain, + CefRefPtr factory) { + if (!factory.get()) { + RemoveFactory(scheme, domain); + return true; + } + + CEF_REQUIRE_IOT(); + + std::string scheme_lower = ToLower(scheme); + std::string domain_lower = ToLower(domain); + + // Hostname is only supported for standard schemes. + if (!IsStandardScheme(scheme_lower)) + domain_lower.clear(); + + SetProtocolHandlerIfNecessary(scheme_lower, true); + + handler_map_[make_pair(scheme_lower, domain_lower)] = factory; + + return true; + } + + void RemoveFactory(const std::string& scheme, + const std::string& domain) { + CEF_REQUIRE_IOT(); + + std::string scheme_lower = ToLower(scheme); + std::string domain_lower = ToLower(domain); + + // Hostname is only supported for standard schemes. + if (!IsStandardScheme(scheme_lower)) + domain_lower.clear(); + + HandlerMap::iterator iter = + handler_map_.find(make_pair(scheme_lower, domain_lower)); + if (iter != handler_map_.end()) { + handler_map_.erase(iter); + + SetProtocolHandlerIfNecessary(scheme_lower, false); + } + } + + // Clear all the existing URL handlers and unregister the ProtocolFactory. + void ClearFactories() { + CEF_REQUIRE_IOT(); + + net::URLRequestJobFactoryImpl* job_factory = GetJobFactoryImpl(); + + // Create a unique set of scheme names. + std::set schemes; + for (HandlerMap::const_iterator i = handler_map_.begin(); + i != handler_map_.end(); ++i) { + schemes.insert(i->first.first); + } + + for (std::set::const_iterator scheme = schemes.begin(); + scheme != schemes.end(); ++scheme) { + const std::string& scheme_name = *scheme; + if (!scheme::IsInternalProtectedScheme(scheme_name)) { + bool set_protocol = job_factory->SetProtocolHandler(scheme_name, NULL); + DCHECK(set_protocol); + } + } + + handler_map_.clear(); + } + + // Helper for chaining ProtocolHandler implementations. + net::URLRequestJob* GetRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate) { + CEF_REQUIRE_IOT(); + return GetRequestJob(request, network_delegate, request->url().scheme()); + } + + private: + net::URLRequestJobFactoryImpl* GetJobFactoryImpl() { + return static_cast( + CefContentBrowserClient::Get()->request_context().get())-> + job_factory_impl(); + } + + // Add or remove the protocol handler if necessary. |scheme| will already be + // in lower case. + void SetProtocolHandlerIfNecessary(const std::string& scheme, bool add) { + // Don't modify a protocol handler for internal protected schemes or if the + // protocol handler is still needed by other registered factories. + if (scheme::IsInternalProtectedScheme(scheme) || HasFactory(scheme)) + return; + + net::URLRequestJobFactoryImpl* job_factory = GetJobFactoryImpl(); + bool set_protocol = job_factory->SetProtocolHandler( + scheme, + (add ? new ProtocolHandler(scheme) : NULL)); + DCHECK(set_protocol); + } + + // Returns true if any factory currently exists for |scheme|. |scheme| will + // already be in lower case. + bool HasFactory(const std::string& scheme) { + if (handler_map_.empty()) + return false; + + for (HandlerMap::const_iterator i = handler_map_.begin(); + i != handler_map_.end(); ++i) { + if (scheme == i->first.first) + return true; + } + + return false; + } + + // Retrieve the matching handler factory, if any. |scheme| will already be in + // lower case. + CefRefPtr GetHandlerFactory( + net::URLRequest* request, const std::string& scheme) { + CefRefPtr factory; + + if (request->url().is_valid() && IsStandardScheme(scheme)) { + // Check for a match with a domain first. + const std::string& domain = request->url().host(); + + HandlerMap::iterator i = handler_map_.find(make_pair(scheme, domain)); + if (i != handler_map_.end()) + factory = i->second; + } + + if (!factory.get()) { + // Check for a match with no specified domain. + HandlerMap::iterator i = + handler_map_.find(make_pair(scheme, std::string())); + if (i != handler_map_.end()) + factory = i->second; + } + + return factory; + } + + // Create the job that will handle the request. |scheme| will already be in + // lower case. + net::URLRequestJob* GetRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const std::string& scheme) { + net::URLRequestJob* job = NULL; + CefRefPtr factory = + GetHandlerFactory(request, scheme); + if (factory.get()) { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForRequest(request); + CefRefPtr frame; + if (browser.get()) + frame = browser->GetFrameForRequest(request); + + // Populate the request data. + CefRefPtr requestPtr(new CefRequestImpl()); + requestPtr->Set(request); + + // Call the handler factory to create the handler for the request. + CefRefPtr handler = + factory->Create(browser.get(), frame, scheme, requestPtr.get()); + if (handler.get()) + job = new CefResourceRequestJob(request, network_delegate, handler); + } + + if (!job && IsBuiltinScheme(scheme)) { + // Give the built-in scheme handler a chance to handle the request. + job = GetBuiltinSchemeRequestJob(request, network_delegate, scheme); + } + +#ifndef NDEBUG + if (job) + DLOG(INFO) << "CefUrlRequestManager hit for " << request->url().spec(); +#endif + + return job; + } + + // Map (scheme, domain) to factories. Will only be accessed on the IO thread. + typedef std::map, + CefRefPtr > HandlerMap; + HandlerMap handler_map_; + + DISALLOW_EVIL_CONSTRUCTORS(CefUrlRequestManager); +}; + +base::LazyInstance g_manager = LAZY_INSTANCE_INITIALIZER; + +CefUrlRequestManager* CefUrlRequestManager::GetInstance() { + return g_manager.Pointer(); +} + +} // namespace + + +bool CefRegisterSchemeHandlerFactory( + const CefString& scheme_name, + const CefString& domain_name, + CefRefPtr factory) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) + return false; + + if (CEF_CURRENTLY_ON(CEF_IOT)) { + return CefUrlRequestManager::GetInstance()->AddFactory(scheme_name, + domain_name, + factory); + } else { + CEF_POST_TASK(CEF_IOT, + base::Bind(base::IgnoreResult(&CefRegisterSchemeHandlerFactory), + scheme_name, domain_name, factory)); + return true; + } +} + +bool CefClearSchemeHandlerFactories() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) + return false; + + if (CEF_CURRENTLY_ON(CEF_IOT)) { + CefUrlRequestManager::GetInstance()->ClearFactories(); + + // Register internal scheme handlers. + scheme::RegisterInternalHandlers(); + } else { + CEF_POST_TASK(CEF_IOT, + base::Bind(base::IgnoreResult(&CefClearSchemeHandlerFactories))); + } + + return true; +} + +namespace scheme { + +net::URLRequestJob* GetRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate) { + return CefUrlRequestManager::GetInstance()->GetRequestJob( + request, network_delegate); +} + +} // namespace scheme diff --git a/libcef/browser/scheme_impl.h b/libcef/browser/scheme_impl.h new file mode 100644 index 000000000..5b66ef9a1 --- /dev/null +++ b/libcef/browser/scheme_impl.h @@ -0,0 +1,24 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_SCHEME_IMPL_H_ +#define CEF_LIBCEF_BROWSER_SCHEME_IMPL_H_ +#pragma once + +namespace net { +class NetworkDelegate; +class URLRequest; +class URLRequestJob; +} + +namespace scheme { + +// Helper for chaining net::URLRequestJobFactory::ProtocolHandler +// implementations. +net::URLRequestJob* GetRequestJob(net::URLRequest* request, + net::NetworkDelegate* network_delegate); + +} // namespace scheme + +#endif // CEF_LIBCEF_BROWSER_SCHEME_IMPL_H_ diff --git a/libcef/browser/software_output_device_osr.cc b/libcef/browser/software_output_device_osr.cc new file mode 100644 index 000000000..65aaca7ed --- /dev/null +++ b/libcef/browser/software_output_device_osr.cc @@ -0,0 +1,123 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/software_output_device_osr.h" + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/render_widget_host_view_osr.h" +#include "libcef/browser/thread_util.h" + +#include "third_party/skia/include/core/SkDevice.h" +#include "ui/compositor/compositor.h" +#include "ui/gfx/skia_util.h" + +CefSoftwareOutputDeviceOSR::CefSoftwareOutputDeviceOSR( + ui::Compositor* compositor, + bool transparent, + const OnPaintCallback& callback) + : transparent_(transparent), + callback_(callback), + active_(false) { + CEF_REQUIRE_UIT(); + DCHECK(!callback_.is_null()); +} + +CefSoftwareOutputDeviceOSR::~CefSoftwareOutputDeviceOSR() { + CEF_REQUIRE_UIT(); +} + +void CefSoftwareOutputDeviceOSR::Resize(const gfx::Size& viewport_pixel_size, + float scale_factor) { + CEF_REQUIRE_UIT(); + + scale_factor_ = scale_factor; + + if (viewport_pixel_size_ == viewport_pixel_size) + return; + + viewport_pixel_size_ = viewport_pixel_size; + + canvas_.reset(NULL); + bitmap_.reset(new SkBitmap); + bitmap_->allocN32Pixels(viewport_pixel_size.width(), + viewport_pixel_size.height(), + !transparent_); + if (bitmap_->drawsNothing()) { + NOTREACHED(); + bitmap_.reset(NULL); + return; + } + + if (transparent_) + bitmap_->eraseARGB(0, 0, 0, 0); + + canvas_.reset(new SkCanvas(*bitmap_.get())); +} + +SkCanvas* CefSoftwareOutputDeviceOSR::BeginPaint(const gfx::Rect& damage_rect) { + CEF_REQUIRE_UIT(); + DCHECK(canvas_.get()); + DCHECK(bitmap_.get()); + + damage_rect_ = damage_rect; + + return canvas_.get(); +} + +void CefSoftwareOutputDeviceOSR::EndPaint(cc::SoftwareFrameData* frame_data) { + CEF_REQUIRE_UIT(); + DCHECK(canvas_.get()); + DCHECK(bitmap_.get()); + DCHECK(frame_data); + + if (!bitmap_.get()) + return; + + cc::SoftwareOutputDevice::EndPaint(frame_data); + + if (active_) + OnPaint(damage_rect_); +} + +void CefSoftwareOutputDeviceOSR::CopyToPixels(const gfx::Rect& rect, + void* pixels) { + CEF_REQUIRE_UIT(); + DCHECK(canvas_.get()); + SkImageInfo info = SkImageInfo::MakeN32Premul(rect.width(), rect.height()); + canvas_->readPixels(info, pixels, info.minRowBytes(), rect.x(), rect.y()); +} + +void CefSoftwareOutputDeviceOSR::SetActive(bool active) { + if (active == active_) + return; + active_ = active; + + // Call OnPaint immediately if deactivated while a damage rect is pending. + if (!active_ && !pending_damage_rect_.IsEmpty()) + OnPaint(pending_damage_rect_); +} + +void CefSoftwareOutputDeviceOSR::Invalidate(const gfx::Rect& damage_rect) { + if (pending_damage_rect_.IsEmpty()) + pending_damage_rect_ = damage_rect; + else + pending_damage_rect_.Union(damage_rect); +} + +void CefSoftwareOutputDeviceOSR::OnPaint(const gfx::Rect& damage_rect) { + gfx::Rect rect = damage_rect; + if (!pending_damage_rect_.IsEmpty()) { + rect.Union(pending_damage_rect_); + pending_damage_rect_.SetRect(0, 0, 0, 0); + } + + rect.Intersect(gfx::Rect(viewport_pixel_size_)); + if (rect.IsEmpty()) + return; + + SkAutoLockPixels bitmap_pixels_lock(*bitmap_.get()); + callback_.Run(rect, bitmap_->width(), bitmap_->height(), + bitmap_->getPixels()); +} diff --git a/libcef/browser/software_output_device_osr.h b/libcef/browser/software_output_device_osr.h new file mode 100644 index 000000000..de6a1aff6 --- /dev/null +++ b/libcef/browser/software_output_device_osr.h @@ -0,0 +1,56 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_SOFTWARE_OUTPUT_DEVICE_OSR_H_ +#define CEF_LIBCEF_BROWSER_SOFTWARE_OUTPUT_DEVICE_OSR_H_ + +#include "base/callback.h" +#include "base/memory/scoped_ptr.h" +#include "cc/output/software_output_device.h" + +namespace ui { +class Compositor; +} + +// Device implementation for direct software rendering via DelegatedFrameHost. +// All Rect/Size values are in pixels. +class CefSoftwareOutputDeviceOSR : public cc::SoftwareOutputDevice { + public: + typedef base::Callback + OnPaintCallback; + + CefSoftwareOutputDeviceOSR(ui::Compositor* compositor, + bool transparent, + const OnPaintCallback& callback); + ~CefSoftwareOutputDeviceOSR() override; + + // cc::SoftwareOutputDevice implementation. + void Resize(const gfx::Size& viewport_pixel_size, + float scale_factor) override; + SkCanvas* BeginPaint(const gfx::Rect& damage_rect) override; + void EndPaint(cc::SoftwareFrameData* frame_data) override; + void CopyToPixels(const gfx::Rect& rect, void* pixels) override; + + void SetActive(bool active); + + // Include |damage_rect| the next time OnPaint is called. + void Invalidate(const gfx::Rect& damage_rect); + + // Deliver the OnPaint notification immediately. + void OnPaint(const gfx::Rect& damage_rect); + + private: + const bool transparent_; + const OnPaintCallback callback_; + + bool active_; + scoped_ptr canvas_; + scoped_ptr bitmap_; + gfx::Rect pending_damage_rect_; + + DISALLOW_COPY_AND_ASSIGN(CefSoftwareOutputDeviceOSR); +}; + +#endif // CEF_LIBCEF_BROWSER_SOFTWARE_OUTPUT_DEVICE_OSR_H_ diff --git a/libcef/browser/speech_recognition_manager_delegate.cc b/libcef/browser/speech_recognition_manager_delegate.cc new file mode 100644 index 000000000..2ced9b341 --- /dev/null +++ b/libcef/browser/speech_recognition_manager_delegate.cc @@ -0,0 +1,229 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/speech_recognition_manager_delegate.h" + +#include +#include + +#include "libcef/common/cef_switches.h" + +#include "base/bind.h" +#include "base/command_line.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/notification_observer.h" +#include "content/public/browser/notification_registrar.h" +#include "content/public/browser/notification_source.h" +#include "content/public/browser/notification_types.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/speech_recognition_manager.h" +#include "content/public/browser/speech_recognition_session_context.h" +#include "content/public/browser/web_contents.h" +#include "content/public/common/speech_recognition_error.h" +#include "content/public/common/speech_recognition_result.h" + +using content::BrowserThread; +using content::SpeechRecognitionManager; +using content::WebContents; + +// Simple utility to get notified when a WebContents is closed or crashes. +// Both the callback site and the callback thread are passed by the caller in +// the constructor. There is no restriction on the constructor, however this +// class must be destroyed on the UI thread, due to the NotificationRegistrar +// dependency. +class CefSpeechRecognitionManagerDelegate::WebContentsWatcher + : public base::RefCountedThreadSafe, + public content::NotificationObserver { + public: + typedef base::Callback + WebContentsClosedCallback; + + WebContentsWatcher(WebContentsClosedCallback web_contents_closed_callback, + BrowserThread::ID callback_thread) + : web_contents_closed_callback_(web_contents_closed_callback), + callback_thread_(callback_thread) { + } + + // Starts monitoring the WebContents corresponding to the given + // |render_process_id|, |render_view_id| pair, invoking + // |web_contents_closed_callback_| if closed/unloaded. + void Watch(int render_process_id, int render_view_id) { + if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { + BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( + &WebContentsWatcher::Watch, this, render_process_id, render_view_id)); + return; + } + + WebContents* web_contents = NULL; + content::RenderViewHost* render_view_host = + content::RenderViewHost::FromID(render_process_id, render_view_id); + if (render_view_host) + web_contents = WebContents::FromRenderViewHost(render_view_host); + DCHECK(web_contents); + + // Avoid multiple registrations on |registrar_| for the same |web_contents|. + if (registered_web_contents_.find(web_contents) != + registered_web_contents_.end()) { + return; + } + registered_web_contents_.insert(web_contents); + + // Lazy initialize the registrar. + if (!registrar_.get()) + registrar_.reset(new content::NotificationRegistrar()); + + registrar_->Add(this, + content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, + content::Source(web_contents)); + } + + // content::NotificationObserver implementation. + void Observe(int type, + const content::NotificationSource& source, + const content::NotificationDetails& details) override { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, type); + + WebContents* web_contents = content::Source(source).ptr(); + int render_process_id = web_contents->GetRenderProcessHost()->GetID(); + int render_view_id = web_contents->GetRenderViewHost()->GetRoutingID(); + + registrar_->Remove(this, + content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, + content::Source(web_contents)); + registered_web_contents_.erase(web_contents); + + BrowserThread::PostTask(callback_thread_, FROM_HERE, base::Bind( + web_contents_closed_callback_, render_process_id, render_view_id)); + } + + private: + friend class base::RefCountedThreadSafe; + + ~WebContentsWatcher() override { + // Must be destroyed on the UI thread due to |registrar_| non thread-safety. + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + } + + // Lazy-initialized and used on the UI thread to handle web contents + // notifications (tab closing). + scoped_ptr registrar_; + + // Keeps track of which WebContent(s) have been registered, in order to avoid + // double registrations on |registrar_| + std::set registered_web_contents_; + + // Callback used to notify, on the thread specified by |callback_thread_| the + // closure of a registered tab. + WebContentsClosedCallback web_contents_closed_callback_; + content::BrowserThread::ID callback_thread_; + + DISALLOW_COPY_AND_ASSIGN(WebContentsWatcher); +}; + +CefSpeechRecognitionManagerDelegate +::CefSpeechRecognitionManagerDelegate() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + filter_profanities_ = + command_line->HasSwitch(switches::kEnableProfanityFilter); +} + +CefSpeechRecognitionManagerDelegate +::~CefSpeechRecognitionManagerDelegate() { +} + +void CefSpeechRecognitionManagerDelegate::WebContentsClosedCallback( + int render_process_id, int render_view_id) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + + SpeechRecognitionManager* manager = SpeechRecognitionManager::GetInstance(); + // |manager| becomes NULL if a browser shutdown happens between the post of + // this task (from the UI thread) and this call (on the IO thread). In this + // case we just return. + if (!manager) + return; + + manager->AbortAllSessionsForRenderView(render_process_id, render_view_id); +} + +void CefSpeechRecognitionManagerDelegate::OnRecognitionStart( + int session_id) { + const content::SpeechRecognitionSessionContext& context = + SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id); + + // Register callback to auto abort session on tab closure. + // |web_contents_watcher_| is lazyly istantiated on the first call. + if (!web_contents_watcher_.get()) { + web_contents_watcher_ = new WebContentsWatcher( + base::Bind( + &CefSpeechRecognitionManagerDelegate::WebContentsClosedCallback, + base::Unretained(this)), + BrowserThread::IO); + } + web_contents_watcher_->Watch(context.render_process_id, + context.render_view_id); +} + +void CefSpeechRecognitionManagerDelegate::OnAudioStart(int session_id) { +} + +void CefSpeechRecognitionManagerDelegate::OnEnvironmentEstimationComplete( + int session_id) { +} + +void CefSpeechRecognitionManagerDelegate::OnSoundStart(int session_id) { +} + +void CefSpeechRecognitionManagerDelegate::OnSoundEnd(int session_id) { +} + +void CefSpeechRecognitionManagerDelegate::OnAudioEnd(int session_id) { +} + +void CefSpeechRecognitionManagerDelegate::OnRecognitionResults( + int session_id, const content::SpeechRecognitionResults& result) { +} + +void CefSpeechRecognitionManagerDelegate::OnRecognitionError( + int session_id, const content::SpeechRecognitionError& error) { +} + +void CefSpeechRecognitionManagerDelegate::OnAudioLevelsChange( + int session_id, float volume, float noise_volume) { +} + +void CefSpeechRecognitionManagerDelegate::OnRecognitionEnd(int session_id) { +} + +void CefSpeechRecognitionManagerDelegate::GetDiagnosticInformation( + bool* can_report_metrics, + std::string* hardware_info) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); +} + +void CefSpeechRecognitionManagerDelegate::CheckRecognitionIsAllowed( + int session_id, + base::Callback callback) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + + const content::SpeechRecognitionSessionContext& context = + SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id); + + // Make sure that initiators properly set the |render_process_id| field. + DCHECK_NE(context.render_process_id, 0); + + callback.Run(false, true); +} + +content::SpeechRecognitionEventListener* +CefSpeechRecognitionManagerDelegate::GetEventListener() { + return this; +} + +bool CefSpeechRecognitionManagerDelegate::FilterProfanities( + int render_process_id) { + return filter_profanities_; +} diff --git a/libcef/browser/speech_recognition_manager_delegate.h b/libcef/browser/speech_recognition_manager_delegate.h new file mode 100644 index 000000000..cfc2e8232 --- /dev/null +++ b/libcef/browser/speech_recognition_manager_delegate.h @@ -0,0 +1,63 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_SPEECH_RECOGNITION_MANAGER_DELEGATE_H_ +#define CEF_LIBCEF_BROWSER_SPEECH_RECOGNITION_MANAGER_DELEGATE_H_ + +#include "base/compiler_specific.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "content/public/browser/speech_recognition_event_listener.h" +#include "content/public/browser/speech_recognition_manager_delegate.h" + + +// This is CEF's implementation of the SpeechRecognitionManagerDelegate +// interface. Based on chrome/browser/speech/ +// chrome_speech_recognition_manager_delegate.[cc|h] +class CefSpeechRecognitionManagerDelegate + : NON_EXPORTED_BASE(public content::SpeechRecognitionManagerDelegate), + public content::SpeechRecognitionEventListener { + public: + CefSpeechRecognitionManagerDelegate(); + ~CefSpeechRecognitionManagerDelegate() override; + + protected: + // SpeechRecognitionEventListener methods. + void OnRecognitionStart(int session_id) override; + void OnAudioStart(int session_id) override; + void OnEnvironmentEstimationComplete(int session_id) override; + void OnSoundStart(int session_id) override; + void OnSoundEnd(int session_id) override; + void OnAudioEnd(int session_id) override; + void OnRecognitionEnd(int session_id) override; + void OnRecognitionResults( + int session_id, const content::SpeechRecognitionResults& result) override; + void OnRecognitionError( + int session_id, const content::SpeechRecognitionError& error) override; + void OnAudioLevelsChange(int session_id, float volume, + float noise_volume) override; + + // SpeechRecognitionManagerDelegate methods. + void GetDiagnosticInformation(bool* can_report_metrics, + std::string* hardware_info) override; + void CheckRecognitionIsAllowed( + int session_id, + base::Callback callback) override; + content::SpeechRecognitionEventListener* GetEventListener() override; + bool FilterProfanities(int render_process_id) override; + + private: + class WebContentsWatcher; + + // Callback called by |web_contents_watcher_| on the IO thread to signal + // web contents closure. + void WebContentsClosedCallback(int render_process_id, int render_view_id); + + scoped_refptr web_contents_watcher_; + bool filter_profanities_; + + DISALLOW_COPY_AND_ASSIGN(CefSpeechRecognitionManagerDelegate); +}; + +#endif // CEF_LIBCEF_BROWSER_SPEECH_RECOGNITION_MANAGER_DELEGATE_H_ diff --git a/libcef/browser/stream_impl.cc b/libcef/browser/stream_impl.cc new file mode 100644 index 000000000..6d30aec0c --- /dev/null +++ b/libcef/browser/stream_impl.cc @@ -0,0 +1,318 @@ +// Copyright (c) 2008 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/stream_impl.h" +#include +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/threading/thread_restrictions.h" + +// Static functions + +CefRefPtr CefStreamReader::CreateForFile( + const CefString& fileName) { + DCHECK(!fileName.empty()); + + // TODO(cef): Do not allow file IO on all threads (issue #1187). + base::ThreadRestrictions::ScopedAllowIO allow_io; + + CefRefPtr reader; + FILE* file = base::OpenFile(base::FilePath(fileName), "rb"); + if (file) + reader = new CefFileReader(file, true); + return reader; +} + +CefRefPtr CefStreamReader::CreateForData(void* data, + size_t size) { + DCHECK(data != NULL); + DCHECK(size > 0); // NOLINT(readability/check) + CefRefPtr reader; + if (data && size > 0) + reader = new CefBytesReader(data, size, true); + return reader; +} + +CefRefPtr CefStreamReader::CreateForHandler( + CefRefPtr handler) { + DCHECK(handler.get()); + CefRefPtr reader; + if (handler.get()) + reader = new CefHandlerReader(handler); + return reader; +} + +CefRefPtr CefStreamWriter::CreateForFile( + const CefString& fileName) { + DCHECK(!fileName.empty()); + + // TODO(cef): Do not allow file IO on all threads (issue #1187). + base::ThreadRestrictions::ScopedAllowIO allow_io; + + CefRefPtr writer; + FILE* file = base::OpenFile(base::FilePath(fileName), "wb"); + if (file) + writer = new CefFileWriter(file, true); + return writer; +} + +CefRefPtr CefStreamWriter::CreateForHandler( + CefRefPtr handler) { + DCHECK(handler.get()); + CefRefPtr writer; + if (handler.get()) + writer = new CefHandlerWriter(handler); + return writer; +} + + +// CefFileReader + +CefFileReader::CefFileReader(FILE* file, bool close) + : close_(close), file_(file) { +} + +CefFileReader::~CefFileReader() { + base::AutoLock lock_scope(lock_); + if (close_) + base::CloseFile(file_); +} + +size_t CefFileReader::Read(void* ptr, size_t size, size_t n) { + base::AutoLock lock_scope(lock_); + return fread(ptr, size, n, file_); +} + +int CefFileReader::Seek(int64 offset, int whence) { + base::AutoLock lock_scope(lock_); +#if defined(OS_WIN) + return _fseeki64(file_, offset, whence); +#else + return fseek(file_, offset, whence); +#endif +} + +int64 CefFileReader::Tell() { + base::AutoLock lock_scope(lock_); +#if defined(OS_WIN) + return _ftelli64(file_); +#else + return ftell(file_); +#endif +} + +int CefFileReader::Eof() { + base::AutoLock lock_scope(lock_); + return feof(file_); +} + + +// CefFileWriter + +CefFileWriter::CefFileWriter(FILE* file, bool close) + : file_(file), + close_(close) { +} + +CefFileWriter::~CefFileWriter() { + base::AutoLock lock_scope(lock_); + if (close_) + base::CloseFile(file_); +} + +size_t CefFileWriter::Write(const void* ptr, size_t size, size_t n) { + base::AutoLock lock_scope(lock_); + return (size_t)fwrite(ptr, size, n, file_); +} + +int CefFileWriter::Seek(int64 offset, int whence) { + base::AutoLock lock_scope(lock_); + return fseek(file_, offset, whence); +} + +int64 CefFileWriter::Tell() { + base::AutoLock lock_scope(lock_); + return ftell(file_); +} + +int CefFileWriter::Flush() { + base::AutoLock lock_scope(lock_); + return fflush(file_); +} + + +// CefBytesReader + +CefBytesReader::CefBytesReader(void* data, int64 datasize, bool copy) + : data_(NULL), + datasize_(0), + copy_(false), + offset_(0) { + SetData(data, datasize, copy); +} + +CefBytesReader::~CefBytesReader() { + SetData(NULL, 0, false); +} + +size_t CefBytesReader::Read(void* ptr, size_t size, size_t n) { + base::AutoLock lock_scope(lock_); + size_t s = (datasize_ - offset_) / size; + size_t ret = (n < s ? n : s); + memcpy(ptr, (reinterpret_cast(data_)) + offset_, ret * size); + offset_ += ret * size; + return ret; +} + +int CefBytesReader::Seek(int64 offset, int whence) { + int rv = -1L; + base::AutoLock lock_scope(lock_); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > datasize_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { + int64 offset_abs = std::abs(offset); + if (offset_abs > datasize_) + break; + offset_ = datasize_ - offset_abs; + rv = 0; + break; + } + case SEEK_SET: + if (offset > datasize_ || offset < 0) + break; + offset_ = offset; + rv = 0; + break; + } + + return rv; +} + +int64 CefBytesReader::Tell() { + base::AutoLock lock_scope(lock_); + return offset_; +} + +int CefBytesReader::Eof() { + base::AutoLock lock_scope(lock_); + return (offset_ >= datasize_); +} + +void CefBytesReader::SetData(void* data, int64 datasize, bool copy) { + base::AutoLock lock_scope(lock_); + if (copy_) + free(data_); + + copy_ = copy; + offset_ = 0; + datasize_ = datasize; + + if (copy) { + data_ = malloc(datasize); + DCHECK(data_ != NULL); + if (data_) + memcpy(data_, data, datasize); + } else { + data_ = data; + } +} + + +// CefBytesWriter + +CefBytesWriter::CefBytesWriter(size_t grow) + : grow_(grow), + datasize_(grow), + offset_(0) { + DCHECK(grow > 0); // NOLINT(readability/check) + data_ = malloc(grow); + DCHECK(data_ != NULL); +} + +CefBytesWriter::~CefBytesWriter() { + base::AutoLock lock_scope(lock_); + if (data_) + free(data_); +} + +size_t CefBytesWriter::Write(const void* ptr, size_t size, size_t n) { + base::AutoLock lock_scope(lock_); + size_t rv; + if (offset_ + static_cast(size * n) >= datasize_ && + Grow(size * n) == 0) { + rv = 0; + } else { + memcpy(reinterpret_cast(data_) + offset_, ptr, size * n); + offset_ += size * n; + rv = n; + } + + return rv; +} + +int CefBytesWriter::Seek(int64 offset, int whence) { + int rv = -1L; + base::AutoLock lock_scope(lock_); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > datasize_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { + int64 offset_abs = std::abs(offset); + if (offset_abs > datasize_) + break; + offset_ = datasize_ - offset_abs; + rv = 0; + break; + } + case SEEK_SET: + if (offset > datasize_ || offset < 0) + break; + offset_ = offset; + rv = 0; + break; + } + + return rv; +} + +int64 CefBytesWriter::Tell() { + base::AutoLock lock_scope(lock_); + return offset_; +} + +int CefBytesWriter::Flush() { + return 0; +} + +std::string CefBytesWriter::GetDataString() { + base::AutoLock lock_scope(lock_); + std::string str(reinterpret_cast(data_), offset_); + return str; +} + +size_t CefBytesWriter::Grow(size_t size) { + base::AutoLock lock_scope(lock_); + size_t rv; + size_t s = (size > grow_ ? size : grow_); + void* tmp = realloc(data_, datasize_ + s); + DCHECK(tmp != NULL); + if (tmp) { + data_ = tmp; + datasize_ += s; + rv = datasize_; + } else { + rv = 0; + } + + return rv; +} diff --git a/libcef/browser/stream_impl.h b/libcef/browser/stream_impl.h new file mode 100644 index 000000000..0d5a97673 --- /dev/null +++ b/libcef/browser/stream_impl.h @@ -0,0 +1,171 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_STREAM_IMPL_H_ +#define CEF_LIBCEF_BROWSER_STREAM_IMPL_H_ +#pragma once + +#include "include/cef_stream.h" + +#include +#include + +#include "base/synchronization/lock.h" + +// Implementation of CefStreamReader for files. +class CefFileReader : public CefStreamReader { + public: + CefFileReader(FILE* file, bool close); + ~CefFileReader() override; + + size_t Read(void* ptr, size_t size, size_t n) override; + int Seek(int64 offset, int whence) override; + int64 Tell() override; + int Eof() override; + bool MayBlock() override { return true; } + + protected: + bool close_; + FILE* file_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefFileReader); +}; + +// Implementation of CefStreamWriter for files. +class CefFileWriter : public CefStreamWriter { + public: + CefFileWriter(FILE* file, bool close); + ~CefFileWriter() override; + + size_t Write(const void* ptr, size_t size, size_t n) override; + int Seek(int64 offset, int whence) override; + int64 Tell() override; + int Flush() override; + bool MayBlock() override { return true; } + + protected: + FILE* file_; + bool close_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefFileWriter); +}; + +// Implementation of CefStreamReader for byte buffers. +class CefBytesReader : public CefStreamReader { + public: + CefBytesReader(void* data, int64 datasize, bool copy); + ~CefBytesReader() override; + + size_t Read(void* ptr, size_t size, size_t n) override; + int Seek(int64 offset, int whence) override; + int64 Tell() override; + int Eof() override; + bool MayBlock() override { return false; } + + void SetData(void* data, int64 datasize, bool copy); + + void* GetData() { return data_; } + size_t GetDataSize() { return offset_; } + + protected: + void* data_; + int64 datasize_; + bool copy_; + int64 offset_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefBytesReader); +}; + +// Implementation of CefStreamWriter for byte buffers. +class CefBytesWriter : public CefStreamWriter { + public: + explicit CefBytesWriter(size_t grow); + ~CefBytesWriter() override; + + size_t Write(const void* ptr, size_t size, size_t n) override; + int Seek(int64 offset, int whence) override; + int64 Tell() override; + int Flush() override; + bool MayBlock() override { return false; } + + void* GetData() { return data_; } + int64 GetDataSize() { return offset_; } + std::string GetDataString(); + + protected: + size_t Grow(size_t size); + + size_t grow_; + void* data_; + int64 datasize_; + int64 offset_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefBytesWriter); +}; + +// Implementation of CefStreamReader for handlers. +class CefHandlerReader : public CefStreamReader { + public: + explicit CefHandlerReader(CefRefPtr handler) + : handler_(handler) {} + + size_t Read(void* ptr, size_t size, size_t n) override { + return handler_->Read(ptr, size, n); + } + int Seek(int64 offset, int whence) override { + return handler_->Seek(offset, whence); + } + int64 Tell() override { + return handler_->Tell(); + } + int Eof() override { + return handler_->Eof(); + } + bool MayBlock() override { + return handler_->MayBlock(); + } + + protected: + CefRefPtr handler_; + + IMPLEMENT_REFCOUNTING(CefHandlerReader); +}; + +// Implementation of CefStreamWriter for handlers. +class CefHandlerWriter : public CefStreamWriter { + public: + explicit CefHandlerWriter(CefRefPtr handler) + : handler_(handler) {} + + size_t Write(const void* ptr, size_t size, size_t n) override { + return handler_->Write(ptr, size, n); + } + int Seek(int64 offset, int whence) override { + return handler_->Seek(offset, whence); + } + int64 Tell() override { + return handler_->Tell(); + } + int Flush() override { + return handler_->Flush(); + } + bool MayBlock() override { + return handler_->MayBlock(); + } + + protected: + CefRefPtr handler_; + + IMPLEMENT_REFCOUNTING(CefHandlerWriter); +}; + +#endif // CEF_LIBCEF_BROWSER_STREAM_IMPL_H_ diff --git a/libcef/browser/text_input_client_osr_mac.h b/libcef/browser/text_input_client_osr_mac.h new file mode 100644 index 000000000..5b10caab1 --- /dev/null +++ b/libcef/browser/text_input_client_osr_mac.h @@ -0,0 +1,89 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_TEXT_INPUT_CLIENT_OSR_MAC_H_ +#define CEF_LIBCEF_BROWSER_TEXT_INPUT_CLIENT_OSR_MAC_H_ +#pragma once + +#import +#include + +#include "libcef/browser/render_widget_host_view_osr.h" + +#include "base/mac/scoped_nsobject.h" +#include "base/strings/string16.h" +#include "content/browser/renderer_host/render_widget_host_impl.h" +#include "content/common/edit_command.h" +#include "third_party/WebKit/public/web/WebCompositionUnderline.h" + +// Implementation for the NSTextInputClient protocol used for enabling IME on +// mac when window rendering is disabled. + +@interface CefTextInputClientOSRMac : NSObject { + + @public + // The range of current marked text inside the whole content of the DOM node + // being edited. + NSRange markedRange_; + + // The current composition character range and its bounds. + gfx::Range composition_range_; + std::vector composition_bounds_; + + // The current caret bounds. + gfx::Rect caret_rect_; + + @private + // Represents the input-method attributes supported by this object. + base::scoped_nsobject validAttributesForMarkedText_; + + // Indicates if we are currently handling a key down event. + BOOL handlingKeyDown_; + + // Indicates if there is any marked text. + BOOL hasMarkedText_; + + // Indicates whether there was any marked text prior to handling + // the current key event. + BOOL oldHasMarkedText_; + + // Indicates if unmarkText is called or not when handling a keyboard + // event. + BOOL unmarkTextCalled_; + + // The selected range, cached from a message sent by the renderer. + NSRange selectedRange_; + + // Text to be inserted which was generated by handling a key down event. + base::string16 textToBeInserted_; + + // Marked text which was generated by handling a key down event. + base::string16 markedText_; + + // Underline information of the |markedText_|. + std::vector underlines_; + + // Indicates if doCommandBySelector method receives any edit command when + // handling a key down event. + BOOL hasEditCommands_; + + // Contains edit commands received by the -doCommandBySelector: method when + // handling a key down event, not including inserting commands, eg. insertTab, + // etc. + content::EditCommands editCommands_; + + CefRenderWidgetHostViewOSR* renderWidgetHostView_; +} + +@property(nonatomic, readonly) NSRange selectedRange; +@property(nonatomic) BOOL handlingKeyDown; + +- (id)initWithRenderWidgetHostViewOSR:(CefRenderWidgetHostViewOSR*) rwhv; +- (void)HandleKeyEventBeforeTextInputClient:(NSEvent*)keyEvent; +- (void)HandleKeyEventAfterTextInputClient:(NSEvent*)keyEvent; +- (void)cancelComposition; + +@end + +#endif // CEF_LIBCEF_BROWSER_TEXT_INPUT_CLIENT_OSR_MAC_H_ diff --git a/libcef/browser/text_input_client_osr_mac.mm b/libcef/browser/text_input_client_osr_mac.mm new file mode 100644 index 000000000..6240a4de7 --- /dev/null +++ b/libcef/browser/text_input_client_osr_mac.mm @@ -0,0 +1,359 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/text_input_client_osr_mac.h" +#include "libcef/browser/browser_host_impl.h" + +#include "base/strings/sys_string_conversions.h" +#import "content/browser/renderer_host/render_widget_host_view_mac_editcommand_helper.h" +#import "content/browser/renderer_host/text_input_client_mac.h" +#include "content/common/input_messages.h" + +namespace { + +// TODO(suzhe): Upstream this function. +blink::WebColor WebColorFromNSColor(NSColor *color) { + CGFloat r, g, b, a; + [color getRed:&r green:&g blue:&b alpha:&a]; + + return + std::max(0, std::min(static_cast(lroundf(255.0f * a)), 255)) << 24 | + std::max(0, std::min(static_cast(lroundf(255.0f * r)), 255)) << 16 | + std::max(0, std::min(static_cast(lroundf(255.0f * g)), 255)) << 8 | + std::max(0, std::min(static_cast(lroundf(255.0f * b)), 255)); +} + +// Extract underline information from an attributed string. Mostly copied from +// third_party/WebKit/Source/WebKit/mac/WebView/WebHTMLView.mm +void ExtractUnderlines(NSAttributedString* string, + std::vector* underlines) { + int length = [[string string] length]; + int i = 0; + while (i < length) { + NSRange range; + NSDictionary* attrs = [string attributesAtIndex:i + longestEffectiveRange:&range + inRange:NSMakeRange(i, length - i)]; + NSNumber *style = [attrs objectForKey: NSUnderlineStyleAttributeName]; + if (style) { + blink::WebColor color = SK_ColorBLACK; + if (NSColor *colorAttr = + [attrs objectForKey:NSUnderlineColorAttributeName]) { + color = WebColorFromNSColor( + [colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]); + } + underlines->push_back(blink::WebCompositionUnderline( + range.location, NSMaxRange(range), color, [style intValue] > 1, 0)); + } + i = range.location + range.length; + } +} + +} // namespace + +extern "C" { + extern NSString* NSTextInputReplacementRangeAttributeName; +} + +@implementation CefTextInputClientOSRMac + +@synthesize selectedRange = selectedRange_; +@synthesize handlingKeyDown = handlingKeyDown_; + +- (id)initWithRenderWidgetHostViewOSR:(CefRenderWidgetHostViewOSR*)rwhv { + self = [super init]; + renderWidgetHostView_ = rwhv; + + return self; +} + +- (NSArray*)validAttributesForMarkedText { + if (!validAttributesForMarkedText_) { + validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects: + NSUnderlineStyleAttributeName, + NSUnderlineColorAttributeName, + NSMarkedClauseSegmentAttributeName, + NSTextInputReplacementRangeAttributeName, + nil]); + } + return validAttributesForMarkedText_.get(); +} + +- (NSRange)markedRange { + return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0); +} + +- (BOOL)hasMarkedText { + return hasMarkedText_; +} + +- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange { + BOOL isAttributedString = [aString isKindOfClass:[NSAttributedString class]]; + NSString* im_text = isAttributedString ? [aString string] : aString; + if (handlingKeyDown_) { + textToBeInserted_.append(base::SysNSStringToUTF16(im_text)); + } else { + gfx::Range replacement_range(replacementRange); + + renderWidgetHostView_->render_widget_host()->ImeConfirmComposition( + base::SysNSStringToUTF16(im_text), replacement_range, false); + } + + // Inserting text will delete all marked text automatically. + hasMarkedText_ = NO; +} + +- (void)doCommandBySelector:(SEL)aSelector { + // An input method calls this function to dispatch an editing command to be + // handled by this view. + if (aSelector == @selector(noop:)) + return; + std::string command([content::RenderWidgetHostViewMacEditCommandHelper:: + CommandNameForSelector(aSelector) UTF8String]); + + // If this method is called when handling a key down event, then we need to + // handle the command in the key event handler. Otherwise we can just handle + // it here. + if (handlingKeyDown_) { + hasEditCommands_ = YES; + // We ignore commands that insert characters, because this was causing + // strange behavior (e.g. tab always inserted a tab rather than moving to + // the next field on the page). + if (!StartsWithASCII(command, "insert", false)) + editCommands_.push_back(content::EditCommand(command, "")); + } else { + renderWidgetHostView_->render_widget_host()->Send( + new InputMsg_ExecuteEditCommand( + renderWidgetHostView_->render_widget_host()->GetRoutingID(), + command, "")); + } +} + +- (void)setMarkedText:(id)aString selectedRange:(NSRange)newSelRange + replacementRange:(NSRange)replacementRange { + // An input method updates the composition string. + // We send the given text and range to the renderer so it can update the + // composition node of WebKit. + + BOOL isAttributedString = [aString isKindOfClass:[NSAttributedString class]]; + NSString* im_text = isAttributedString ? [aString string] : aString; + int length = [im_text length]; + + // |markedRange_| will get set on a callback from ImeSetComposition(). + selectedRange_ = newSelRange; + markedText_ = base::SysNSStringToUTF16(im_text); + hasMarkedText_ = (length > 0); + underlines_.clear(); + + if (isAttributedString) { + ExtractUnderlines(aString, &underlines_); + } else { + // Use a thin black underline by default. + underlines_.push_back(blink::WebCompositionUnderline(0, length, + SK_ColorBLACK, false, 0)); + } + + // If we are handling a key down event, then SetComposition() will be + // called in keyEvent: method. + // Input methods of Mac use setMarkedText calls with an empty text to cancel + // an ongoing composition. So, we should check whether or not the given text + // is empty to update the input method state. (Our input method backend can + // automatically cancels an ongoing composition when we send an empty text. + // So, it is OK to send an empty text to the renderer.) + if (!handlingKeyDown_) { + renderWidgetHostView_->render_widget_host()->ImeSetComposition( + markedText_, underlines_, newSelRange.location, + NSMaxRange(newSelRange)); + } +} + +- (void)unmarkText { + // Delete the composition node of the renderer and finish an ongoing + // composition. + // It seems an input method calls the setMarkedText method and set an empty + // text when it cancels an ongoing composition, i.e. I have never seen an + // input method calls this method. + hasMarkedText_ = NO; + markedText_.clear(); + underlines_.clear(); + + // If we are handling a key down event, then ConfirmComposition() will be + // called in keyEvent: method. + if (!handlingKeyDown_) { + renderWidgetHostView_->render_widget_host()->ImeConfirmComposition( + base::string16(), gfx::Range::InvalidRange(), false); + } else { + unmarkTextCalled_ = YES; + } +} + +- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)range + actualRange:(NSRangePointer)actualRange { + if (actualRange) + *actualRange = range; + NSAttributedString* str = content::TextInputClientMac::GetInstance()-> + GetAttributedSubstringFromRange( + renderWidgetHostView_->GetRenderWidgetHost(), range); + return str; +} + +- (NSRect)firstViewRectForCharacterRange:(NSRange)theRange + actualRange:(NSRangePointer)actualRange { + NSRect rect; + gfx::Rect gfxRect; + gfx::Range range(theRange); + gfx::Range actual_range; + if (!renderWidgetHostView_->GetCachedFirstRectForCharacterRange(range, + &gfxRect, &actual_range)) { + rect = content::TextInputClientMac::GetInstance()-> + GetFirstRectForRange(renderWidgetHostView_->GetRenderWidgetHost(), + range.ToNSRange()); + + if (actualRange) + *actualRange = range.ToNSRange(); + } else { + rect = NSRectFromCGRect(gfxRect.ToCGRect()); + } + + return rect; +} + +- (NSRect) screenRectFromViewRect:(NSRect)rect { + NSRect screenRect; + + int screenX, screenY; + renderWidgetHostView_->browser_impl()->GetClient()->GetRenderHandler()-> + GetScreenPoint(renderWidgetHostView_->browser_impl()->GetBrowser(), + rect.origin.x, rect.origin.y, screenX, screenY); + screenRect.origin = NSMakePoint(screenX, screenY); + screenRect.size = rect.size; + + return screenRect; +} + +- (NSRect)firstRectForCharacterRange:(NSRange)theRange + actualRange:(NSRangePointer)actualRange { + NSRect rect = [self firstViewRectForCharacterRange:theRange + actualRange:actualRange]; + + // Convert into screen coordinates for return. + rect = [self screenRectFromViewRect:rect]; + + if (rect.origin.y >= rect.size.height) + rect.origin.y -= rect.size.height; + else + rect.origin.y = 0; + + return rect; +} + +- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint { + // |thePoint| is in screen coordinates, but needs to be converted to WebKit + // coordinates (upper left origin). Scroll offsets will be taken care of in + // the renderer. + + CefRect view_rect; + renderWidgetHostView_->browser_impl()->GetClient()->GetRenderHandler()-> + GetViewRect(renderWidgetHostView_->browser_impl()->GetBrowser(), + view_rect); + + thePoint.x -= view_rect.x; + thePoint.y -= view_rect.y; + thePoint.y = view_rect.height - thePoint.y; + + NSUInteger index = content::TextInputClientMac::GetInstance()-> + GetCharacterIndexAtPoint(renderWidgetHostView_->GetRenderWidgetHost(), + gfx::Point(thePoint.x, thePoint.y)); + return index; +} + +- (void)HandleKeyEventBeforeTextInputClient:(NSEvent*)keyEvent { + DCHECK([keyEvent type] == NSKeyDown); + // Don't call this method recursively. + DCHECK(!handlingKeyDown_); + + oldHasMarkedText_ = hasMarkedText_; + handlingKeyDown_ = YES; + + // These variables might be set when handling the keyboard event. + // Clear them here so that we can know whether they have changed afterwards. + textToBeInserted_.clear(); + markedText_.clear(); + underlines_.clear(); + unmarkTextCalled_ = NO; + hasEditCommands_ = NO; + editCommands_.clear(); +} + +- (void)HandleKeyEventAfterTextInputClient:(NSEvent*)keyEvent { + handlingKeyDown_ = NO; + + // Then send keypress and/or composition related events. + // If there was a marked text or the text to be inserted is longer than 1 + // character, then we send the text by calling ConfirmComposition(). + // Otherwise, if the text to be inserted only contains 1 character, then we + // can just send a keypress event which is fabricated by changing the type of + // the keydown event, so that we can retain all necessary informations, such + // as unmodifiedText, etc. And we need to set event.skip_in_browser to true to + // prevent the browser from handling it again. + // Note that, |textToBeInserted_| is a UTF-16 string, but it's fine to only + // handle BMP characters here, as we can always insert non-BMP characters as + // text. + + if (!hasMarkedText_ && !oldHasMarkedText_ && + textToBeInserted_.length() <= 1) { + content::NativeWebKeyboardEvent event(keyEvent); + if (textToBeInserted_.length() == 1) { + event.type = blink::WebInputEvent::Type::Char; + event.text[0] = textToBeInserted_[0]; + event.text[1] = 0; + } + renderWidgetHostView_->SendKeyEvent(event); + } + + BOOL textInserted = NO; + if (textToBeInserted_.length() > + ((hasMarkedText_ || oldHasMarkedText_) ? 0u : 1u)) { + renderWidgetHostView_->render_widget_host()->ImeConfirmComposition( + textToBeInserted_, gfx::Range::InvalidRange(), false); + textToBeInserted_ = YES; + } + + // Updates or cancels the composition. If some text has been inserted, then + // we don't need to cancel the composition explicitly. + if (hasMarkedText_ && markedText_.length()) { + // Sends the updated marked text to the renderer so it can update the + // composition node in WebKit. + // When marked text is available, |selectedRange_| will be the range being + // selected inside the marked text. + renderWidgetHostView_->render_widget_host()->ImeSetComposition( + markedText_, underlines_, selectedRange_.location, + NSMaxRange(selectedRange_)); + } else if (oldHasMarkedText_ && !hasMarkedText_ && !textInserted) { + if (unmarkTextCalled_) { + renderWidgetHostView_->render_widget_host()->ImeConfirmComposition( + base::string16(), gfx::Range::InvalidRange(), false); + } else { + renderWidgetHostView_->render_widget_host()->ImeCancelComposition(); + } + } +} + +- (void)cancelComposition { + if (!hasMarkedText_) + return; + + // Cancel the ongoing composition. [NSInputManager markedTextAbandoned:] + // doesn't call any NSTextInput functions, such as setMarkedText or + // insertText. So, we need to send an IPC message to a renderer so it can + // delete the composition node. + NSInputManager *currentInputManager = [NSInputManager currentInputManager]; + [currentInputManager markedTextAbandoned:self]; + + hasMarkedText_ = NO; + // Should not call [self unmarkText] here, because it'll send unnecessary + // cancel composition IPC message to the renderer. +} + +@end diff --git a/libcef/browser/thread_util.h b/libcef/browser/thread_util.h new file mode 100644 index 000000000..2faf57128 --- /dev/null +++ b/libcef/browser/thread_util.h @@ -0,0 +1,49 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_THREAD_UTIL_H_ +#define CEF_LIBCEF_BROWSER_THREAD_UTIL_H_ +#pragma once + +#include "base/location.h" +#include "base/logging.h" +#include "content/public/browser/browser_thread.h" + +#define CEF_UIT content::BrowserThread::UI +#define CEF_IOT content::BrowserThread::IO +#define CEF_FILET content::BrowserThread::FILE + +#define CEF_CURRENTLY_ON(id) content::BrowserThread::CurrentlyOn(id) +#define CEF_CURRENTLY_ON_UIT() CEF_CURRENTLY_ON(CEF_UIT) +#define CEF_CURRENTLY_ON_IOT() CEF_CURRENTLY_ON(CEF_IOT) +#define CEF_CURRENTLY_ON_FILET() CEF_CURRENTLY_ON(CEF_FILET) + +#define CEF_REQUIRE(id) DCHECK(CEF_CURRENTLY_ON(id)) +#define CEF_REQUIRE_UIT() CEF_REQUIRE(CEF_UIT) +#define CEF_REQUIRE_IOT() CEF_REQUIRE(CEF_IOT) +#define CEF_REQUIRE_FILET() CEF_REQUIRE(CEF_FILET) + +#define CEF_REQUIRE_RETURN(id, var) \ + if (!CEF_CURRENTLY_ON(id)) { \ + NOTREACHED() << "called on invalid thread"; \ + return var; \ + } +#define CEF_REQUIRE_UIT_RETURN(var) CEF_REQUIRE_RETURN(CEF_UIT, var) +#define CEF_REQUIRE_IOT_RETURN(var) CEF_REQUIRE_RETURN(CEF_IOT, var) + +#define CEF_REQUIRE_RETURN_VOID(id) \ + if (!CEF_CURRENTLY_ON(id)) { \ + NOTREACHED() << "called on invalid thread"; \ + return; \ + } +#define CEF_REQUIRE_UIT_RETURN_VOID() CEF_REQUIRE_RETURN_VOID(CEF_UIT) +#define CEF_REQUIRE_IOT_RETURN_VOID() CEF_REQUIRE_RETURN_VOID(CEF_IOT) + +#define CEF_POST_TASK(id, task) \ + content::BrowserThread::PostTask(id, FROM_HERE, task) +#define CEF_POST_DELAYED_TASK(id, task, delay_ms) \ + content::BrowserThread::PostDelayedTask(id, FROM_HERE, task, \ + base::TimeDelta::FromMilliseconds(delay_ms)) + +#endif // CEF_LIBCEF_BROWSER_THREAD_UTIL_H_ diff --git a/libcef/browser/trace_impl.cc b/libcef/browser/trace_impl.cc new file mode 100644 index 000000000..580fee688 --- /dev/null +++ b/libcef/browser/trace_impl.cc @@ -0,0 +1,52 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "include/cef_trace.h" +#include "libcef/browser/trace_subscriber.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" + +#include "base/time/time.h" + +bool CefBeginTracing(const CefString& categories, + CefRefPtr callback) { + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return false; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + CefTraceSubscriber* subscriber = CefContext::Get()->GetTraceSubscriber(); + if (!subscriber) + return false; + + return subscriber->BeginTracing(categories, callback); +} + +bool CefEndTracing(const CefString& tracing_file, + CefRefPtr callback) { + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return false; + } + + if (!CEF_CURRENTLY_ON_UIT()) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + CefTraceSubscriber* subscriber = CefContext::Get()->GetTraceSubscriber(); + if (!subscriber) + return false; + + return subscriber->EndTracing(base::FilePath(tracing_file), callback); +} + +int64 CefNowFromSystemTraceTime() { + return base::TimeTicks::NowFromSystemTraceTime().ToInternalValue(); +} diff --git a/libcef/browser/trace_subscriber.cc b/libcef/browser/trace_subscriber.cc new file mode 100644 index 000000000..8db2992e9 --- /dev/null +++ b/libcef/browser/trace_subscriber.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/trace_subscriber.h" +#include "include/cef_trace.h" +#include "libcef/browser/thread_util.h" + +#include "base/debug/trace_event.h" +#include "base/files/file_util.h" +#include "content/public/browser/tracing_controller.h" + +namespace { + +// Create the temporary file and then execute |callback| on the thread +// represented by |message_loop_proxy|. +void CreateTemporaryFileOnFileThread( + scoped_refptr message_loop_proxy, + base::Callback callback) { + CEF_REQUIRE_FILET(); + base::FilePath file_path; + if (!base::CreateTemporaryFile(&file_path)) + LOG(ERROR) << "Failed to create temporary file."; + message_loop_proxy->PostTask(FROM_HERE, base::Bind(callback, file_path)); +} + +} // namespace + +using content::TracingController; + +CefTraceSubscriber::CefTraceSubscriber() + : collecting_trace_data_(false), + weak_factory_(this) { + CEF_REQUIRE_UIT(); +} + +CefTraceSubscriber::~CefTraceSubscriber() { + CEF_REQUIRE_UIT(); + if (collecting_trace_data_) + TracingController::GetInstance()->DisableRecording(NULL); +} + +bool CefTraceSubscriber::BeginTracing( + const std::string& categories, + CefRefPtr callback) { + CEF_REQUIRE_UIT(); + + if (collecting_trace_data_) + return false; + + collecting_trace_data_ = true; + + TracingController::EnableRecordingDoneCallback done_callback; + if (callback.get()) { + done_callback = + base::Bind(&CefCompletionCallback::OnComplete, callback.get()); + } + + TracingController::GetInstance()->EnableRecording( + base::debug::CategoryFilter(categories), + base::debug::TraceOptions(), + done_callback); + return true; +} + +bool CefTraceSubscriber::EndTracing( + const base::FilePath& tracing_file, + CefRefPtr callback) { + CEF_REQUIRE_UIT(); + + if (!collecting_trace_data_) + return false; + + if (!callback.get()) { + // Discard the trace data. + collecting_trace_data_ = false; + TracingController::GetInstance()->DisableRecording(NULL); + return true; + } + + if (tracing_file.empty()) { + // Create a new temporary file path on the FILE thread, then continue. + CEF_POST_TASK(CEF_FILET, + base::Bind(CreateTemporaryFileOnFileThread, + base::MessageLoop::current()->message_loop_proxy(), + base::Bind(&CefTraceSubscriber::ContinueEndTracing, + weak_factory_.GetWeakPtr(), callback))); + return true; + } + + base::Closure result_callback = + base::Bind(&CefTraceSubscriber::OnTracingFileResult, + weak_factory_.GetWeakPtr(), callback, tracing_file); + + TracingController::GetInstance()->DisableRecording( + TracingController::CreateFileSink(tracing_file, result_callback)); + return true; +} + +void CefTraceSubscriber::ContinueEndTracing( + CefRefPtr callback, + const base::FilePath& tracing_file) { + CEF_REQUIRE_UIT(); + if (!tracing_file.empty()) + EndTracing(tracing_file, callback); +} + +void CefTraceSubscriber::OnTracingFileResult( + CefRefPtr callback, + const base::FilePath& tracing_file) { + CEF_REQUIRE_UIT(); + + collecting_trace_data_ = false; + + callback->OnEndTracingComplete(tracing_file.value()); +} diff --git a/libcef/browser/trace_subscriber.h b/libcef/browser/trace_subscriber.h new file mode 100644 index 000000000..86d7c05e4 --- /dev/null +++ b/libcef/browser/trace_subscriber.h @@ -0,0 +1,37 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_TRACE_SUBSCRIBER_H_ +#define CEF_LIBCEF_BROWSER_TRACE_SUBSCRIBER_H_ +#pragma once + +#include "include/cef_trace.h" + +#include "base/files/file_path.h" +#include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" + +// May only be accessed on the browser process UI thread. +class CefTraceSubscriber { + public: + CefTraceSubscriber(); + virtual ~CefTraceSubscriber(); + + bool BeginTracing(const std::string& categories, + CefRefPtr callback); + bool EndTracing(const base::FilePath& tracing_file, + CefRefPtr callback); + + private: + void ContinueEndTracing(CefRefPtr callback, + const base::FilePath& tracing_file); + void OnTracingFileResult(CefRefPtr callback, + const base::FilePath& tracing_file); + + bool collecting_trace_data_; + base::WeakPtrFactory weak_factory_; +}; + +#endif // CEF_LIBCEF_BROWSER_TRACE_SUBSCRIBER_H_ diff --git a/libcef/browser/url_network_delegate.cc b/libcef/browser/url_network_delegate.cc new file mode 100644 index 000000000..df7916a62 --- /dev/null +++ b/libcef/browser/url_network_delegate.cc @@ -0,0 +1,184 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/url_network_delegate.h" + +#include + +#include "include/cef_urlrequest.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_user_data.h" +#include "libcef/common/request_impl.h" + +#include "net/base/net_errors.h" +#include "net/url_request/url_request.h" + +namespace { + +class CefAuthCallbackImpl : public CefAuthCallback { + public: + CefAuthCallbackImpl(const net::NetworkDelegate::AuthCallback& callback, + net::AuthCredentials* credentials) + : callback_(callback), + credentials_(credentials) { + } + ~CefAuthCallbackImpl() override { + if (!callback_.is_null()) { + // The auth callback is still pending. Cancel it now. + if (CEF_CURRENTLY_ON_IOT()) { + CancelNow(callback_); + } else { + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefAuthCallbackImpl::CancelNow, callback_)); + } + } + } + + void Continue(const CefString& username, + const CefString& password) override { + if (CEF_CURRENTLY_ON_IOT()) { + if (!callback_.is_null()) { + credentials_->Set(username, password); + callback_.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefAuthCallbackImpl::Continue, this, username, password)); + } + } + + void Cancel() override { + if (CEF_CURRENTLY_ON_IOT()) { + if (!callback_.is_null()) { + CancelNow(callback_); + callback_.Reset(); + } + } else { + CEF_POST_TASK(CEF_IOT, base::Bind(&CefAuthCallbackImpl::Cancel, this)); + } + } + + void Disconnect() { + callback_.Reset(); + } + + private: + static void CancelNow(const net::NetworkDelegate::AuthCallback& callback) { + CEF_REQUIRE_IOT(); + callback.Run(net::NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION); + } + + net::NetworkDelegate::AuthCallback callback_; + net::AuthCredentials* credentials_; + + IMPLEMENT_REFCOUNTING(CefAuthCallbackImpl); +}; + +} // namespace + +CefNetworkDelegate::CefNetworkDelegate() { +} + +CefNetworkDelegate::~CefNetworkDelegate() { +} + +int CefNetworkDelegate::OnBeforeURLRequest( + net::URLRequest* request, + const net::CompletionCallback& callback, + GURL* new_url) { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForRequest(request); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr frame = browser->GetFrameForRequest(request); + + GURL old_url = request->url(); + + // Populate the request data. + CefRefPtr requestPtr(new CefRequestImpl()); + requestPtr->Set(request); + + // Give the client an opportunity to cancel the request. + if (handler->OnBeforeResourceLoad(browser.get(), frame, + requestPtr.get())) { + return net::ERR_ABORTED; + } + + GURL url = GURL(std::string(requestPtr->GetURL())); + if (old_url != url) + new_url ->Swap(&url); + + requestPtr->Get(request); + } + } + } + + return net::OK; +} + +net::NetworkDelegate::AuthRequiredResponse CefNetworkDelegate::OnAuthRequired( + net::URLRequest* request, + const net::AuthChallengeInfo& auth_info, + const AuthCallback& callback, + net::AuthCredentials* credentials) { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForRequest(request); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr frame = browser->GetFrameForRequest(request); + + CefRefPtr callbackPtr( + new CefAuthCallbackImpl(callback, credentials)); + if (handler->GetAuthCredentials(browser.get(), + frame, + auth_info.is_proxy, + auth_info.challenger.host(), + auth_info.challenger.port(), + auth_info.realm, + auth_info.scheme, + callbackPtr.get())) { + return AUTH_REQUIRED_RESPONSE_IO_PENDING; + } else { + callbackPtr->Disconnect(); + } + } + } + } + + CefURLRequestUserData* user_data = + (CefURLRequestUserData*)request->GetUserData( + CefURLRequestUserData::kUserDataKey); + if (user_data) { + CefRefPtr client = user_data->GetClient(); + if (client.get()) { + CefRefPtr callbackPtr( + new CefAuthCallbackImpl(callback, credentials)); + if (client->GetAuthCredentials(auth_info.is_proxy, + auth_info.challenger.host(), + auth_info.challenger.port(), + auth_info.realm, + auth_info.scheme, + callbackPtr.get())) { + return AUTH_REQUIRED_RESPONSE_IO_PENDING; + } else { + callbackPtr->Disconnect(); + } + } + } + + return AUTH_REQUIRED_RESPONSE_NO_ACTION; +} + +bool CefNetworkDelegate::OnCanAccessFile(const net::URLRequest& request, + const base::FilePath& path) const { + return true; +} diff --git a/libcef/browser/url_network_delegate.h b/libcef/browser/url_network_delegate.h new file mode 100644 index 000000000..bfb32d210 --- /dev/null +++ b/libcef/browser/url_network_delegate.h @@ -0,0 +1,34 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_URL_NETWORK_DELEGATE_H_ +#define CEF_LIBCEF_BROWSER_URL_NETWORK_DELEGATE_H_ +#pragma once + +#include "net/base/network_delegate_impl.h" + +// Used for intercepting resource requests, redirects and responses. The single +// instance of this class is managed by CefURLRequestContextGetter. +class CefNetworkDelegate : public net::NetworkDelegateImpl { + public: + CefNetworkDelegate(); + ~CefNetworkDelegate() override; + + private: + // net::NetworkDelegate methods. + int OnBeforeURLRequest(net::URLRequest* request, + const net::CompletionCallback& callback, + GURL* new_url) override; + AuthRequiredResponse OnAuthRequired( + net::URLRequest* request, + const net::AuthChallengeInfo& auth_info, + const AuthCallback& callback, + net::AuthCredentials* credentials) override; + bool OnCanAccessFile(const net::URLRequest& request, + const base::FilePath& path) const; + + DISALLOW_COPY_AND_ASSIGN(CefNetworkDelegate); +}; + +#endif // CEF_LIBCEF_BROWSER_URL_NETWORK_DELEGATE_H_ diff --git a/libcef/browser/url_request_context_getter.cc b/libcef/browser/url_request_context_getter.cc new file mode 100644 index 000000000..fcd54c2b3 --- /dev/null +++ b/libcef/browser/url_request_context_getter.cc @@ -0,0 +1,399 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/url_request_context_getter.h" + +#if defined(OS_WIN) +#include +#endif +#include +#include + +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/browser/scheme_handler.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_network_delegate.h" +#include "libcef/browser/url_request_context_proxy.h" +#include "libcef/browser/url_request_interceptor.h" +#include "libcef/common/cef_switches.h" +#include "libcef/common/content_client.h" + +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/stl_util.h" +#include "base/strings/string_util.h" +#include "base/threading/thread_restrictions.h" +#include "base/threading/worker_pool.h" +#include "chrome/browser/net/proxy_service_factory.h" +#include "content/browser/net/sqlite_persistent_cookie_store.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/cookie_crypto_delegate.h" +#include "content/public/common/content_client.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/url_constants.h" +#include "net/cert/cert_verifier.h" +#include "net/cookies/cookie_monster.h" +#include "net/dns/host_resolver.h" +#include "net/ftp/ftp_network_layer.h" +#include "net/http/http_auth_handler_factory.h" +#include "net/http/http_cache.h" +#include "net/http/http_server_properties_impl.h" +#include "net/http/http_util.h" +#include "net/http/transport_security_state.h" +#include "net/proxy/proxy_service.h" +#include "net/ssl/channel_id_service.h" +#include "net/ssl/default_channel_id_store.h" +#include "net/ssl/ssl_config_service_defaults.h" +#include "url/url_constants.h" +#include "net/url_request/http_user_agent_settings.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_context.h" +#include "net/url_request/url_request_context_storage.h" +#include "net/url_request/url_request_intercepting_job_factory.h" +#include "net/url_request/url_request_job_factory_impl.h" +#include "net/url_request/url_request_job_manager.h" + +#if defined(USE_NSS) +#include "net/ocsp/nss_ocsp.h" +#endif + +using content::BrowserThread; + +#if defined(OS_WIN) +#pragma comment(lib, "winhttp.lib") +#endif + +namespace { + +// An implementation of |HttpUserAgentSettings| that provides a static +// HTTP Accept-Language header value and uses |content::GetUserAgent| +// to provide the HTTP User-Agent header value. +class CefHttpUserAgentSettings : public net::HttpUserAgentSettings { + public: + explicit CefHttpUserAgentSettings(const std::string& raw_language_list) + : http_accept_language_(net::HttpUtil::GenerateAcceptLanguageHeader( + raw_language_list)) { + CEF_REQUIRE_IOT(); + } + + // net::HttpUserAgentSettings implementation + std::string GetAcceptLanguage() const override { + CEF_REQUIRE_IOT(); + return http_accept_language_; + } + + std::string GetUserAgent() const override { + CEF_REQUIRE_IOT(); + return CefContentClient::Get()->GetUserAgent(); + } + + private: + const std::string http_accept_language_; + + DISALLOW_COPY_AND_ASSIGN(CefHttpUserAgentSettings); +}; + +} // namespace + +CefURLRequestContextGetter::CefURLRequestContextGetter( + base::MessageLoop* io_loop, + base::MessageLoop* file_loop, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors) + : io_loop_(io_loop), + file_loop_(file_loop), + request_interceptors_(request_interceptors.Pass()) { + // Must first be created on the UI thread. + CEF_REQUIRE_UIT(); + + std::swap(protocol_handlers_, *protocol_handlers); +} + +CefURLRequestContextGetter::~CefURLRequestContextGetter() { + CEF_REQUIRE_IOT(); + STLDeleteElements(&url_request_context_proxies_); + + // Delete the ProxyService object here so that any pending requests will be + // canceled before the associated URLRequestContext is destroyed in this + // object's destructor. + storage_->set_proxy_service(NULL); +} + +net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() { + CEF_REQUIRE_IOT(); + + if (!url_request_context_.get()) { + const base::FilePath& cache_path = CefContext::Get()->cache_path(); + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + const CefSettings& settings = CefContext::Get()->settings(); + + url_request_context_.reset(new net::URLRequestContext()); + storage_.reset( + new net::URLRequestContextStorage(url_request_context_.get())); + + bool persist_session_cookies = + (settings.persist_session_cookies || + command_line->HasSwitch(switches::kPersistSessionCookies)); + SetCookieStoragePath(cache_path, persist_session_cookies); + + storage_->set_network_delegate(new CefNetworkDelegate); + + storage_->set_channel_id_service(new net::ChannelIDService( + new net::DefaultChannelIDStore(NULL), + base::WorkerPool::GetTaskRunner(true))); + storage_->set_http_user_agent_settings( + new CefHttpUserAgentSettings("en-us,en")); + + storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL)); + storage_->set_cert_verifier(net::CertVerifier::CreateDefault()); + storage_->set_transport_security_state(new net::TransportSecurityState); + + scoped_ptr system_proxy_service; + system_proxy_service.reset( + ProxyServiceFactory::CreateProxyService( + NULL, + url_request_context_.get(), + url_request_context_->network_delegate(), + CefContentBrowserClient::Get()->proxy_config_service().release(), + *command_line, + true)); + storage_->set_proxy_service(system_proxy_service.release()); + + storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults); + + // Add support for single sign-on. + url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL)); + + std::vector supported_schemes; + supported_schemes.push_back("basic"); + supported_schemes.push_back("digest"); + supported_schemes.push_back("ntlm"); + supported_schemes.push_back("negotiate"); + + storage_->set_http_auth_handler_factory( + net::HttpAuthHandlerRegistryFactory::Create( + supported_schemes, + url_security_manager_.get(), + url_request_context_->host_resolver(), + std::string(), + false, + false)); + storage_->set_http_server_properties( + make_scoped_ptr( + new net::HttpServerPropertiesImpl)); + + net::HttpCache::DefaultBackend* main_backend = + new net::HttpCache::DefaultBackend( + cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE, + net::CACHE_BACKEND_DEFAULT, + cache_path, + 0, + BrowserThread::GetMessageLoopProxyForThread( + BrowserThread::CACHE)); + + net::HttpNetworkSession::Params network_session_params; + network_session_params.host_resolver = + url_request_context_->host_resolver(); + network_session_params.cert_verifier = + url_request_context_->cert_verifier(); + network_session_params.transport_security_state = + url_request_context_->transport_security_state(); + network_session_params.channel_id_service = + url_request_context_->channel_id_service(); + network_session_params.proxy_service = + url_request_context_->proxy_service(); + network_session_params.ssl_config_service = + url_request_context_->ssl_config_service(); + network_session_params.http_auth_handler_factory = + url_request_context_->http_auth_handler_factory(); + network_session_params.network_delegate = + url_request_context_->network_delegate(); + network_session_params.http_server_properties = + url_request_context_->http_server_properties(); + network_session_params.ignore_certificate_errors = + (settings.ignore_certificate_errors || + command_line->HasSwitch(switches::kIgnoreCertificateErrors)); + + net::HttpCache* main_cache = new net::HttpCache(network_session_params, + main_backend); + storage_->set_http_transaction_factory(main_cache); + +#if !defined(DISABLE_FTP_SUPPORT) + ftp_transaction_factory_.reset( + new net::FtpNetworkLayer(network_session_params.host_resolver)); +#endif + + scoped_ptr job_factory( + new net::URLRequestJobFactoryImpl()); + job_factory_impl_ = job_factory.get(); + + scheme::InstallInternalProtectedHandlers(job_factory.get(), + &protocol_handlers_, + ftp_transaction_factory_.get()); + protocol_handlers_.clear(); + + request_interceptors_.push_back(new CefRequestInterceptor()); + + // Set up interceptors in the reverse order. + scoped_ptr top_job_factory = + job_factory.Pass(); + for (content::URLRequestInterceptorScopedVector::reverse_iterator i = + request_interceptors_.rbegin(); + i != request_interceptors_.rend(); + ++i) { + top_job_factory.reset(new net::URLRequestInterceptingJobFactory( + top_job_factory.Pass(), make_scoped_ptr(*i))); + } + request_interceptors_.weak_clear(); + + storage_->set_job_factory(top_job_factory.release()); + +#if defined(USE_NSS) + net::SetURLRequestContextForNSSHttpIO(url_request_context_.get()); +#endif + } + + return url_request_context_.get(); +} + +scoped_refptr + CefURLRequestContextGetter::GetNetworkTaskRunner() const { + return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT); +} + +net::HostResolver* CefURLRequestContextGetter::host_resolver() { + return url_request_context_->host_resolver(); +} + +void CefURLRequestContextGetter::SetCookieStoragePath( + const base::FilePath& path, + bool persist_session_cookies) { + CEF_REQUIRE_IOT(); + + if (url_request_context_->cookie_store() && + ((cookie_store_path_.empty() && path.empty()) || + cookie_store_path_ == path)) { + // The path has not changed so don't do anything. + return; + } + + scoped_refptr persistent_store; + if (!path.empty()) { + // TODO(cef): Move directory creation to the blocking pool instead of + // allowing file IO on this thread. + base::ThreadRestrictions::ScopedAllowIO allow_io; + if (base::DirectoryExists(path) || + base::CreateDirectory(path)) { + const base::FilePath& cookie_path = path.AppendASCII("Cookies"); + persistent_store = + new content::SQLitePersistentCookieStore( + cookie_path, + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO), + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB), + persist_session_cookies, + NULL, + NULL); + } else { + NOTREACHED() << "The cookie storage directory could not be created"; + } + } + + // Set the new cookie store that will be used for all new requests. The old + // cookie store, if any, will be automatically flushed and closed when no + // longer referenced. + scoped_refptr cookie_monster = + new net::CookieMonster(persistent_store.get(), NULL); + storage_->set_cookie_store(cookie_monster.get()); + if (persistent_store.get() && persist_session_cookies) + cookie_monster->SetPersistSessionCookies(true); + cookie_store_path_ = path; + + // Restore the previously supported schemes. + SetCookieSupportedSchemes(cookie_supported_schemes_); +} + +void CefURLRequestContextGetter::SetCookieSupportedSchemes( + const std::vector& schemes) { + CEF_REQUIRE_IOT(); + + cookie_supported_schemes_ = schemes; + + if (cookie_supported_schemes_.empty()) { + cookie_supported_schemes_.push_back("http"); + cookie_supported_schemes_.push_back("https"); + } + + std::set scheme_set; + std::vector::const_iterator it = + cookie_supported_schemes_.begin(); + for (; it != cookie_supported_schemes_.end(); ++it) + scheme_set.insert(*it); + + const char** arr = new const char*[scheme_set.size()]; + std::set::const_iterator it2 = scheme_set.begin(); + for (int i = 0; it2 != scheme_set.end(); ++it2, ++i) + arr[i] = it2->c_str(); + + url_request_context_->cookie_store()->GetCookieMonster()-> + SetCookieableSchemes(arr, scheme_set.size()); + + delete [] arr; +} + +CefURLRequestContextProxy* + CefURLRequestContextGetter::CreateURLRequestContextProxy() { + CEF_REQUIRE_IOT(); + CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this); + url_request_context_proxies_.insert(proxy); + return proxy; +} + +void CefURLRequestContextGetter::ReleaseURLRequestContextProxy( + CefURLRequestContextProxy* proxy) { + CEF_REQUIRE_IOT(); + + // Don't do anything if we're currently shutting down. The proxy objects will + // be deleted when this object is destroyed. + if (CefContext::Get()->shutting_down()) + return; + + if (proxy->url_requests()->size() == 0) { + // Safe to delete the proxy. + RequestContextProxySet::iterator it = + url_request_context_proxies_.find(proxy); + DCHECK(it != url_request_context_proxies_.end()); + url_request_context_proxies_.erase(it); + delete proxy; + } else { + proxy->increment_delete_try_count(); + if (proxy->delete_try_count() <= 1) { + // Cancel the pending requests. This may result in additional tasks being + // posted on the IO thread. + std::set::iterator it = + proxy->url_requests()->begin(); + for (; it != proxy->url_requests()->end(); ++it) + const_cast(*it)->Cancel(); + + // Try to delete the proxy again later. + CEF_POST_TASK(CEF_IOT, + base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy, + this, proxy)); + } else { + NOTREACHED() << + "too many retries to delete URLRequestContext proxy object"; + } + } +} + +void CefURLRequestContextGetter::CreateProxyConfigService() { + if (proxy_config_service_.get()) + return; + + proxy_config_service_.reset( + net::ProxyService::CreateSystemProxyConfigService( + io_loop_->message_loop_proxy(), file_loop_->message_loop_proxy())); +} diff --git a/libcef/browser/url_request_context_getter.h b/libcef/browser/url_request_context_getter.h new file mode 100644 index 000000000..4230aa7de --- /dev/null +++ b/libcef/browser/url_request_context_getter.h @@ -0,0 +1,131 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_H_ +#define CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_H_ +#pragma once + +#include +#include +#include + +#include "base/compiler_specific.h" +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "content/public/browser/content_browser_client.h" +#include "net/url_request/url_request_context_getter.h" +#include "net/url_request/url_request_job_factory.h" + +namespace base { +class MessageLoop; +} + +namespace net { +class FtpTransactionFactory; +class HostResolver; +class ProxyConfigService; +class URLRequestContextStorage; +class URLRequestJobFactory; +class URLRequestJobFactoryImpl; +class URLSecurityManager; +} + +class CefURLRequestContextProxy; + +/* +// Classes used in network request processing: +// +// RC = net::URLRequestContext +// Owns various network-related objects including the global cookie manager. +// +// RCP = CefURLRequestContextProxy +// Creates the CSP and forwards requests to the objects owned by RC. +// +// CSP = CefCookieStoreProxy +// Gives the CefCookieManager associated with CefBrowserHostImpl an +// opportunity to handle cookie requests. Otherwise forwards requests via RC +// to the global cookie manager. +// +// RCG = CefURLRequestContextGetter +// Creates the RC and manages RCP lifespan. +// +// RCGP = CefURLRequestContextGetterProxy +// Causes the RCG to create and destroy browser-specific RCPs. +// +// Relationship diagram: +// ref = reference (scoped_refptr) +// own = ownership (scoped_ptr) +// ptr = raw pointer +// +// global cookie manager, etc... +// ^ +// | +// /-own-> RC <-ptr-\ +// / \ +// / /<-ptr-\ \ +// / / \ \ +// CefBrowserContext -ref-> RCG --own-> RCP --ref-> CSP +// ^ ^ / +// ref ptr / +// | / / +// CefBrowserHostImpl -ref-> RCGP----/ / +// ^ / +// \-ref--------------------------/ +*/ + +class CefURLRequestContextGetter : public net::URLRequestContextGetter { + public: + CefURLRequestContextGetter( + base::MessageLoop* io_loop, + base::MessageLoop* file_loop, + content::ProtocolHandlerMap* protocol_handlers, + content::URLRequestInterceptorScopedVector request_interceptors); + ~CefURLRequestContextGetter() override; + + // net::URLRequestContextGetter implementation. + net::URLRequestContext* GetURLRequestContext() override; + scoped_refptr + GetNetworkTaskRunner() const override; + + net::HostResolver* host_resolver(); + net::URLRequestJobFactoryImpl* job_factory_impl() const { + return job_factory_impl_; + } + + void SetCookieStoragePath(const base::FilePath& path, + bool persist_session_cookies); + void SetCookieSupportedSchemes(const std::vector& schemes); + + // Manage URLRequestContext proxy objects. It's important that proxy objects + // not be destroyed while any in-flight URLRequests exist. These methods + // manage that requirement. + CefURLRequestContextProxy* CreateURLRequestContextProxy(); + void ReleaseURLRequestContextProxy(CefURLRequestContextProxy* proxy); + + private: + void CreateProxyConfigService(); + + base::MessageLoop* io_loop_; + base::MessageLoop* file_loop_; + + scoped_ptr proxy_config_service_; + scoped_ptr storage_; + scoped_ptr url_request_context_; + scoped_ptr url_security_manager_; + scoped_ptr ftp_transaction_factory_; + content::ProtocolHandlerMap protocol_handlers_; + content::URLRequestInterceptorScopedVector request_interceptors_; + net::URLRequestJobFactoryImpl* job_factory_impl_; + + typedef std::set RequestContextProxySet; + RequestContextProxySet url_request_context_proxies_; + + base::FilePath cookie_store_path_; + std::vector cookie_supported_schemes_; + + DISALLOW_COPY_AND_ASSIGN(CefURLRequestContextGetter); +}; + +#endif // CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_H_ diff --git a/libcef/browser/url_request_context_getter_proxy.cc b/libcef/browser/url_request_context_getter_proxy.cc new file mode 100644 index 000000000..5eaaa443a --- /dev/null +++ b/libcef/browser/url_request_context_getter_proxy.cc @@ -0,0 +1,42 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/url_request_context_getter_proxy.h" +#include "libcef/browser/thread_util.h" +#include "libcef/browser/url_request_context_getter.h" +#include "libcef/browser/url_request_context_proxy.h" + +CefURLRequestContextGetterProxy::CefURLRequestContextGetterProxy( + CefRefPtr handler, + CefURLRequestContextGetter* parent) + : handler_(handler), + parent_(parent), + context_proxy_(NULL) { + DCHECK(parent); +} + +CefURLRequestContextGetterProxy::~CefURLRequestContextGetterProxy() { + CEF_REQUIRE_IOT(); + if (context_proxy_) + parent_->ReleaseURLRequestContextProxy(context_proxy_); +} + +net::URLRequestContext* + CefURLRequestContextGetterProxy::GetURLRequestContext() { + CEF_REQUIRE_IOT(); + if (!context_proxy_) { + context_proxy_ = parent_->CreateURLRequestContextProxy(); + context_proxy_->Initialize(handler_); + } + return context_proxy_; +} + +scoped_refptr + CefURLRequestContextGetterProxy::GetNetworkTaskRunner() const { + return parent_->GetNetworkTaskRunner(); +} + +net::HostResolver* CefURLRequestContextGetterProxy::GetHostResolver() const { + return parent_->host_resolver(); +} diff --git a/libcef/browser/url_request_context_getter_proxy.h b/libcef/browser/url_request_context_getter_proxy.h new file mode 100644 index 000000000..c86c26d22 --- /dev/null +++ b/libcef/browser/url_request_context_getter_proxy.h @@ -0,0 +1,46 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_PROXY_H_ +#define CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_PROXY_H_ +#pragma once + +#include "include/cef_request_context_handler.h" + +#include "base/memory/scoped_ptr.h" +#include "net/url_request/url_request_context_getter.h" + +class CefURLRequestContextGetter; +class CefURLRequestContextProxy; + +namespace net { +class HostResolver; +} + +class CefURLRequestContextGetterProxy : public net::URLRequestContextGetter { + public: + CefURLRequestContextGetterProxy(CefRefPtr handler, + CefURLRequestContextGetter* parent); + ~CefURLRequestContextGetterProxy() override; + + // net::URLRequestContextGetter implementation. + net::URLRequestContext* GetURLRequestContext() override; + scoped_refptr + GetNetworkTaskRunner() const override; + + net::HostResolver* GetHostResolver() const; + + CefRefPtr handler() const { return handler_; } + + private: + CefRefPtr handler_; + scoped_refptr parent_; + + // The |context_proxy_| object is owned by |parent_|. + CefURLRequestContextProxy* context_proxy_; + + DISALLOW_COPY_AND_ASSIGN(CefURLRequestContextGetterProxy); +}; + +#endif // CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_GETTER_PROXY_H_ diff --git a/libcef/browser/url_request_context_proxy.cc b/libcef/browser/url_request_context_proxy.cc new file mode 100644 index 000000000..fbdc551de --- /dev/null +++ b/libcef/browser/url_request_context_proxy.cc @@ -0,0 +1,173 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/url_request_context_proxy.h" + +#include + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/cookie_manager_impl.h" +#include "libcef/browser/thread_util.h" + +#include "base/logging.h" +#include "base/message_loop/message_loop_proxy.h" +#include "net/cookies/cookie_store.h" +#include "net/url_request/url_request_context_getter.h" + +namespace { + +class CefCookieStoreProxy : public net::CookieStore { + public: + CefCookieStoreProxy(net::URLRequestContext* parent, + CefRefPtr handler) + : parent_(parent), + handler_(handler) { + } + ~CefCookieStoreProxy() override { + CEF_REQUIRE_IOT(); + } + + // net::CookieStore methods. + void SetCookieWithOptionsAsync( + const GURL& url, + const std::string& cookie_line, + const net::CookieOptions& options, + const SetCookiesCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->SetCookieWithOptionsAsync(url, cookie_line, options, + callback); + } + + void GetCookiesWithOptionsAsync( + const GURL& url, const net::CookieOptions& options, + const GetCookiesCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->GetCookiesWithOptionsAsync(url, options, callback); + } + + void DeleteCookieAsync(const GURL& url, + const std::string& cookie_name, + const base::Closure& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteCookieAsync(url, cookie_name, callback); + } + + void GetAllCookiesForURLAsync( + const GURL& url, + const GetCookieListCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->GetAllCookiesForURLAsync(url, callback); + } + + void DeleteAllCreatedBetweenAsync(const base::Time& delete_begin, + const base::Time& delete_end, + const DeleteCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteAllCreatedBetweenAsync(delete_begin, delete_end, + callback); + } + + void DeleteAllCreatedBetweenForHostAsync( + const base::Time delete_begin, + const base::Time delete_end, + const GURL& url, + const DeleteCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteAllCreatedBetweenForHostAsync(delete_begin, delete_end, + url, callback); + } + + void DeleteSessionCookiesAsync(const DeleteCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteSessionCookiesAsync(callback); + } + + net::CookieMonster* GetCookieMonster() override { + scoped_refptr cookie_store = GetCookieStore(); + return cookie_store->GetCookieMonster(); + } + + scoped_ptr AddCallbackForCookie( + const GURL& url, + const std::string& name, + const CookieChangedCallback& callback) override { + scoped_refptr cookie_store = GetCookieStore(); + return cookie_store->AddCallbackForCookie(url, name, callback); + } + + private: + net::CookieStore* GetCookieStore() { + CEF_REQUIRE_IOT(); + + scoped_refptr cookie_store; + + if (handler_.get()) { + // Get the manager from the handler. + CefRefPtr manager = handler_->GetCookieManager(); + if (manager.get()) { + cookie_store = + reinterpret_cast( + manager.get())->cookie_monster(); + DCHECK(cookie_store.get()); + } + } + + if (!cookie_store.get()) { + // Use the global cookie store. + cookie_store = parent_->cookie_store(); + } + + DCHECK(cookie_store.get()); + return cookie_store.get(); + } + + // This pointer is guaranteed by the CefRequestContextProxy object. + net::URLRequestContext* parent_; + CefRefPtr handler_; + + DISALLOW_COPY_AND_ASSIGN(CefCookieStoreProxy); +}; + +} // namespace + + +CefURLRequestContextProxy::CefURLRequestContextProxy( + net::URLRequestContextGetter* parent) + : parent_(parent), + delete_try_count_(0) { +} + +CefURLRequestContextProxy::~CefURLRequestContextProxy() { + CEF_REQUIRE_IOT(); +} + +void CefURLRequestContextProxy::Initialize( + CefRefPtr handler) { + CEF_REQUIRE_IOT(); + + net::URLRequestContext* context = parent_->GetURLRequestContext(); + + // Cookie store that proxies to the browser implementation. + cookie_store_proxy_ = new CefCookieStoreProxy(context, handler); + set_cookie_store(cookie_store_proxy_.get()); + + // All other values refer to the parent request context. + set_net_log(context->net_log()); + set_host_resolver(context->host_resolver()); + set_cert_verifier(context->cert_verifier()); + set_transport_security_state(context->transport_security_state()); + set_channel_id_service(context->channel_id_service()); + set_fraudulent_certificate_reporter( + context->fraudulent_certificate_reporter()); + set_proxy_service(context->proxy_service()); + set_ssl_config_service(context->ssl_config_service()); + set_http_auth_handler_factory(context->http_auth_handler_factory()); + set_http_transaction_factory(context->http_transaction_factory()); + set_network_delegate(context->network_delegate()); + set_http_server_properties(context->http_server_properties()); + set_transport_security_state(context->transport_security_state()); + set_http_user_agent_settings(const_cast( + context->http_user_agent_settings())); + set_job_factory(context->job_factory()); +} diff --git a/libcef/browser/url_request_context_proxy.h b/libcef/browser/url_request_context_proxy.h new file mode 100644 index 000000000..06ea1f8ae --- /dev/null +++ b/libcef/browser/url_request_context_proxy.h @@ -0,0 +1,43 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_PROXY_H_ +#define CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_PROXY_H_ +#pragma once + +#include "include/cef_request_context_handler.h" + +#include "base/memory/scoped_ptr.h" +#include "net/url_request/url_request_context.h" + +class CefBrowserHostImpl; + +namespace net { +class CookieStore; +class URLRequestContextGetter; +} + +class CefURLRequestContextProxy : public net::URLRequestContext { + public: + explicit CefURLRequestContextProxy(net::URLRequestContextGetter* parent); + ~CefURLRequestContextProxy() override; + + void Initialize(CefRefPtr handler); + + // We may try to delete this proxy multiple times if URLRequests are still + // pending. Keep track of the number of tries so that they don't become + // excessive. + int delete_try_count() const { return delete_try_count_; } + void increment_delete_try_count() { delete_try_count_++; } + + private: + net::URLRequestContextGetter* parent_; + scoped_refptr cookie_store_proxy_; + + int delete_try_count_; + + DISALLOW_COPY_AND_ASSIGN(CefURLRequestContextProxy); +}; + +#endif // CEF_LIBCEF_BROWSER_URL_REQUEST_CONTEXT_PROXY_H_ diff --git a/libcef/browser/url_request_interceptor.cc b/libcef/browser/url_request_interceptor.cc new file mode 100644 index 000000000..f36bf4f38 --- /dev/null +++ b/libcef/browser/url_request_interceptor.cc @@ -0,0 +1,90 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/browser/url_request_interceptor.h" + +#include + +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/resource_request_job.h" +#include "libcef/browser/thread_util.h" +#include "libcef/common/request_impl.h" + +#include "net/url_request/url_request_redirect_job.h" + +CefRequestInterceptor::CefRequestInterceptor() { + CEF_REQUIRE_IOT(); +} + +CefRequestInterceptor::~CefRequestInterceptor() { + CEF_REQUIRE_IOT(); +} + +net::URLRequestJob* CefRequestInterceptor::MaybeInterceptRequest( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForRequest(request); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr frame = browser->GetFrameForRequest(request); + + // Populate the request data. + CefRefPtr req(CefRequest::Create()); + static_cast(req.get())->Set(request); + + // Give the client an opportunity to replace the request. + CefRefPtr resourceHandler = + handler->GetResourceHandler(browser.get(), frame, req); + if (resourceHandler.get()) + return new CefResourceRequestJob(request, network_delegate, + resourceHandler); + } + } + } + + return NULL; +} + +net::URLRequestJob* CefRequestInterceptor::MaybeInterceptRedirect( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const GURL& location) const { + CefRefPtr browser = + CefBrowserHostImpl::GetBrowserForRequest(request); + if (browser.get()) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefRefPtr frame = browser->GetFrameForRequest(request); + + // Give the client an opportunity to redirect the request. + CefString newUrlStr = location.spec(); + handler->OnResourceRedirect(browser.get(), frame, request->url().spec(), + newUrlStr); + if (newUrlStr != location.spec()) { + GURL new_url = GURL(std::string(newUrlStr)); + if (!new_url.is_empty() && new_url.is_valid()) { + return new net::URLRequestRedirectJob( + request, network_delegate, new_url, + net::URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, + "Resource Redirect"); + } + } + } + } + } + + return NULL; +} + +net::URLRequestJob* CefRequestInterceptor::MaybeInterceptResponse( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const { + return NULL; +} diff --git a/libcef/browser/url_request_interceptor.h b/libcef/browser/url_request_interceptor.h new file mode 100644 index 000000000..c6abf5dc4 --- /dev/null +++ b/libcef/browser/url_request_interceptor.h @@ -0,0 +1,33 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_INTERCEPTOR_H_ +#define CEF_LIBCEF_BROWSER_URL_REQUEST_INTERCEPTOR_H_ +#pragma once + +#include "net/url_request/url_request_interceptor.h" + +// Used for intercepting resource requests, redirects and responses. The single +// instance of this class is managed by CefURLRequestContextGetter. +class CefRequestInterceptor : public net::URLRequestInterceptor { + public: + CefRequestInterceptor(); + ~CefRequestInterceptor() override; + + // net::URLRequestInterceptor methods. + net::URLRequestJob* MaybeInterceptRequest( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const override; + net::URLRequestJob* MaybeInterceptRedirect( + net::URLRequest* request, + net::NetworkDelegate* network_delegate, + const GURL& location) const override; + net::URLRequestJob* MaybeInterceptResponse( + net::URLRequest* request, + net::NetworkDelegate* network_delegate) const override; + + DISALLOW_COPY_AND_ASSIGN(CefRequestInterceptor); +}; + +#endif // CEF_LIBCEF_BROWSER_URL_REQUEST_INTERCEPTOR_H_ diff --git a/libcef/browser/url_request_user_data.cc b/libcef/browser/url_request_user_data.cc new file mode 100644 index 000000000..c21885241 --- /dev/null +++ b/libcef/browser/url_request_user_data.cc @@ -0,0 +1,18 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/url_request_user_data.h" + +CefURLRequestUserData::CefURLRequestUserData(CefRefPtr client) + : client_(client) {} + +CefURLRequestUserData::~CefURLRequestUserData() {} + +CefRefPtr CefURLRequestUserData::GetClient() { + return client_; +} + +// static +const void* CefURLRequestUserData::kUserDataKey = + static_cast(&CefURLRequestUserData::kUserDataKey); diff --git a/libcef/browser/url_request_user_data.h b/libcef/browser/url_request_user_data.h new file mode 100644 index 000000000..b1352e71c --- /dev/null +++ b/libcef/browser/url_request_user_data.h @@ -0,0 +1,27 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_ +#define CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_ + +#include "include/cef_base.h" +#include "base/supports_user_data.h" + +#include "include/cef_urlrequest.h" + +// Used to annotate all URLRequests for which the request can be associated +// with the CefURLRequestClient. +class CefURLRequestUserData : public base::SupportsUserData::Data { + public: + CefURLRequestUserData(CefRefPtr client); + ~CefURLRequestUserData() override; + + CefRefPtr GetClient(); + static const void* kUserDataKey; + +private: + CefRefPtr client_; +}; + +#endif // CEF_LIBCEF_BROWSER_URL_REQUEST_USER_DATA_H_ diff --git a/libcef/browser/web_contents_view_osr.cc b/libcef/browser/web_contents_view_osr.cc new file mode 100644 index 000000000..d3db727e4 --- /dev/null +++ b/libcef/browser/web_contents_view_osr.cc @@ -0,0 +1,165 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/web_contents_view_osr.h" +#include "libcef/browser/browser_host_impl.h" +#include "libcef/browser/render_widget_host_view_osr.h" +#include "libcef/common/drag_data_impl.h" + +#include "content/public/browser/render_widget_host.h" + +CefWebContentsViewOSR::CefWebContentsViewOSR() + : web_contents_(NULL), + view_(NULL) { +} + +CefWebContentsViewOSR::~CefWebContentsViewOSR() { +} + +void CefWebContentsViewOSR::set_web_contents( + content::WebContents* web_contents) { + DCHECK(!web_contents_); + web_contents_ = web_contents; +} + +gfx::NativeView CefWebContentsViewOSR::GetNativeView() const { + return gfx::NativeView(); +} + +gfx::NativeView CefWebContentsViewOSR::GetContentNativeView() const { + return gfx::NativeView(); +} + +gfx::NativeWindow CefWebContentsViewOSR::GetTopLevelNativeWindow() const { + return gfx::NativeWindow(); +} + +void CefWebContentsViewOSR::GetContainerBounds(gfx::Rect* out) const { + *out = GetViewBounds(); +} + +void CefWebContentsViewOSR::SizeContents(const gfx::Size& size) { +} + +void CefWebContentsViewOSR::Focus() { +} + +void CefWebContentsViewOSR::SetInitialFocus() { +} + +void CefWebContentsViewOSR::StoreFocus() { +} + +void CefWebContentsViewOSR::RestoreFocus() { +} + +content::DropData* CefWebContentsViewOSR::GetDropData() const { + return NULL; +} + +gfx::Rect CefWebContentsViewOSR::GetViewBounds() const { + return view_ ? view_->GetViewBounds() : gfx::Rect(); +} + +void CefWebContentsViewOSR::CreateView(const gfx::Size& initial_size, + gfx::NativeView context) { +} + +content::RenderWidgetHostViewBase* CefWebContentsViewOSR::CreateViewForWidget( + content::RenderWidgetHost* render_widget_host, + bool is_guest_view_hack) { + if (render_widget_host->GetView()) { + return static_cast( + render_widget_host->GetView()); + } + + view_ = new CefRenderWidgetHostViewOSR(render_widget_host); + return view_; +} + +content::RenderWidgetHostViewBase* + CefWebContentsViewOSR::CreateViewForPopupWidget( + content::RenderWidgetHost* render_widget_host) { + return new CefRenderWidgetHostViewOSR(render_widget_host); +} + +void CefWebContentsViewOSR::SetPageTitle(const base::string16& title) { +} + +void CefWebContentsViewOSR::RenderViewCreated(content::RenderViewHost* host) { + if (view_) + view_->InstallTransparency(); +} + +void CefWebContentsViewOSR::RenderViewSwappedIn( + content::RenderViewHost* host) { +} + +void CefWebContentsViewOSR::SetOverscrollControllerEnabled(bool enabled) { +} + +#if defined(OS_MACOSX) +void CefWebContentsViewOSR::SetAllowOtherViews(bool allow) { +} + +bool CefWebContentsViewOSR::GetAllowOtherViews() const { + return false; +} + +bool CefWebContentsViewOSR::IsEventTracking() const { + return false; +} + +void CefWebContentsViewOSR::CloseTabAfterEventTracking() { +} +#endif // defined(OS_MACOSX) + +void CefWebContentsViewOSR::StartDragging( + const content::DropData& drop_data, + blink::WebDragOperationsMask allowed_ops, + const gfx::ImageSkia& image, + const gfx::Vector2d& image_offset, + const content::DragEventSourceInfo& event_info) { + CefRefPtr browser; + CefRefPtr handler; + bool handled = false; + CefRenderWidgetHostViewOSR* view = + static_cast(view_); + if (view) + browser = view->browser_impl(); + if (browser.get()) + handler = browser->GetClient()->GetRenderHandler(); + DCHECK(handler.get()); + if (handler.get()) { + CefRefPtr drag_data(new CefDragDataImpl(drop_data)); + drag_data->SetReadOnly(true); + base::MessageLoop::ScopedNestableTaskAllower allow( + base::MessageLoop::current()); + handled = handler->StartDragging(browser->GetBrowser(), + drag_data.get(), + static_cast(allowed_ops), + event_info.event_location.x(), + event_info.event_location.y()); + } + if (!handled && web_contents_) + web_contents_->SystemDragEnded(); +} + +void CefWebContentsViewOSR::UpdateDragCursor( + blink::WebDragOperation operation) { + CefRefPtr browser; + CefRefPtr handler; + CefRenderWidgetHostViewOSR* view = + static_cast(view_); + if (view) + browser = view->browser_impl(); + if (browser.get()) + handler = browser->GetClient()->GetRenderHandler(); + DCHECK(handler.get()); + if (handler.get()) { + handler->UpdateDragCursor(browser->GetBrowser(), + static_cast(operation)); + } +} diff --git a/libcef/browser/web_contents_view_osr.h b/libcef/browser/web_contents_view_osr.h new file mode 100644 index 000000000..0246c385d --- /dev/null +++ b/libcef/browser/web_contents_view_osr.h @@ -0,0 +1,75 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_WEB_CONTENTS_VIEW_OSR_H_ +#define CEF_LIBCEF_BROWSER_WEB_CONTENTS_VIEW_OSR_H_ + +#include "content/browser/renderer_host/render_view_host_delegate_view.h" +#include "content/browser/web_contents/web_contents_view.h" + +namespace content { +class WebContents; +class WebContentsViewDelegate; +} + +class CefRenderWidgetHostViewOSR; + +// An implementation of WebContentsView for off-screen rendering. +class CefWebContentsViewOSR : public content::WebContentsView, + public content::RenderViewHostDelegateView { + public: + CefWebContentsViewOSR(); + ~CefWebContentsViewOSR() override; + + void set_web_contents(content::WebContents* web_contents); + + // WebContentsView methods. + gfx::NativeView GetNativeView() const override; + gfx::NativeView GetContentNativeView() const override; + gfx::NativeWindow GetTopLevelNativeWindow() const override; + void GetContainerBounds(gfx::Rect* out) const override; + void SizeContents(const gfx::Size& size) override; + void Focus() override; + void SetInitialFocus() override; + void StoreFocus() override; + void RestoreFocus() override; + content::DropData* GetDropData() const override; + gfx::Rect GetViewBounds() const override; + void CreateView(const gfx::Size& initial_size, + gfx::NativeView context) override; + content::RenderWidgetHostViewBase* CreateViewForWidget( + content::RenderWidgetHost* render_widget_host, + bool is_guest_view_hack) override; + content::RenderWidgetHostViewBase* CreateViewForPopupWidget( + content::RenderWidgetHost* render_widget_host) override; + void SetPageTitle(const base::string16& title) override; + void RenderViewCreated(content::RenderViewHost* host) override; + void RenderViewSwappedIn(content::RenderViewHost* host) override; + void SetOverscrollControllerEnabled(bool enabled) override; + +#if defined(OS_MACOSX) + void SetAllowOtherViews(bool allow) override; + bool GetAllowOtherViews() const override; + bool IsEventTracking() const override; + void CloseTabAfterEventTracking() override; +#endif + + // RenderViewHostDelegateView methods. + void StartDragging( + const content::DropData& drop_data, + blink::WebDragOperationsMask allowed_ops, + const gfx::ImageSkia& image, + const gfx::Vector2d& image_offset, + const content::DragEventSourceInfo& event_info) override; + void UpdateDragCursor(blink::WebDragOperation operation) override; + + private: + content::WebContents* web_contents_; + CefRenderWidgetHostViewOSR* view_; + + DISALLOW_COPY_AND_ASSIGN(CefWebContentsViewOSR); +}; + +#endif // CEF_LIBCEF_BROWSER_WEB_CONTENTS_VIEW_OSR_H_ diff --git a/libcef/browser/web_plugin_impl.cc b/libcef/browser/web_plugin_impl.cc new file mode 100644 index 000000000..3cb4ecc3c --- /dev/null +++ b/libcef/browser/web_plugin_impl.cc @@ -0,0 +1,224 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/web_plugin_impl.h" +#include "libcef/browser/context.h" +#include "libcef/browser/thread_util.h" + +#include "base/bind.h" +#include "base/files/file_path.h" +#include "content/browser/plugin_service_impl.h" + +namespace { + +void PluginsCallbackImpl( + CefRefPtr visitor, + const std::vector& all_plugins) { + CEF_REQUIRE_UIT(); + + int count = 0; + int total = static_cast(all_plugins.size()); + + std::vector::const_iterator it = all_plugins.begin(); + for (; it != all_plugins.end(); ++it, ++count) { + CefRefPtr info(new CefWebPluginInfoImpl(*it)); + if (!visitor->Visit(info.get(), count, total)) + break; + } +} + +} // namespace + + +// CefWebPluginInfoImpl + +CefWebPluginInfoImpl::CefWebPluginInfoImpl( + const content::WebPluginInfo& plugin_info) + : plugin_info_(plugin_info) { +} + +CefString CefWebPluginInfoImpl::GetName() { + return plugin_info_.name; +} + +CefString CefWebPluginInfoImpl::GetPath() { + return plugin_info_.path.value(); +} + +CefString CefWebPluginInfoImpl::GetVersion() { + return plugin_info_.version; +} + +CefString CefWebPluginInfoImpl::GetDescription() { + return plugin_info_.desc; +} + + +// Global functions. + +void CefVisitWebPluginInfo(CefRefPtr visitor) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (!visitor.get()) { + NOTREACHED() << "invalid parameter"; + return; + } + + if (CEF_CURRENTLY_ON_UIT()) { + content::PluginServiceImpl::GetInstance()->GetPlugins( + base::Bind(PluginsCallbackImpl, visitor)); + } else { + // Execute on the UI thread. + CEF_POST_TASK(CEF_UIT, base::Bind(CefVisitWebPluginInfo, visitor)); + } +} + +void CefRefreshWebPlugins() { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + // No thread affinity. + content::PluginServiceImpl::GetInstance()->RefreshPlugins(); +} + +void CefAddWebPluginPath(const CefString& path) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (path.empty()) { + NOTREACHED() << "invalid parameter"; + return; + } + + // No thread affinity. + content::PluginServiceImpl::GetInstance()->AddExtraPluginPath( + base::FilePath(path)); +} + +void CefAddWebPluginDirectory(const CefString& dir) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (dir.empty()) { + NOTREACHED() << "invalid parameter"; + return; + } + + // No thread affinity. + content::PluginServiceImpl::GetInstance()->AddExtraPluginDir( + base::FilePath(dir)); +} + +void CefRemoveWebPluginPath(const CefString& path) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (path.empty()) { + NOTREACHED() << "invalid parameter"; + return; + } + + // No thread affinity. + content::PluginServiceImpl::GetInstance()->RemoveExtraPluginPath( + base::FilePath(path)); +} + +void CefUnregisterInternalWebPlugin(const CefString& path) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (path.empty()) { + NOTREACHED() << "invalid parameter"; + return; + } + + // No thread affinity. + content::PluginServiceImpl::GetInstance()->UnregisterInternalPlugin( + base::FilePath(path)); +} + +void CefForceWebPluginShutdown(const CefString& path) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (path.empty()) { + NOTREACHED() << "invalid parameter"; + return; + } + + if (CEF_CURRENTLY_ON_IOT()) { + content::PluginServiceImpl::GetInstance()->ForcePluginShutdown( + base::FilePath(path)); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, base::Bind(CefForceWebPluginShutdown, path)); + } +} + +void CefRegisterWebPluginCrash(const CefString& path) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (path.empty()) { + NOTREACHED() << "invalid parameter"; + return; + } + + if (CEF_CURRENTLY_ON_IOT()) { + content::PluginServiceImpl::GetInstance()->RegisterPluginCrash( + base::FilePath(path)); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, base::Bind(CefRegisterWebPluginCrash, path)); + } +} + +void CefIsWebPluginUnstable( + const CefString& path, + CefRefPtr callback) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return; + } + + if (path.empty() || !callback.get()) { + NOTREACHED() << "invalid parameter"; + return; + } + + if (CEF_CURRENTLY_ON_IOT()) { + callback->IsUnstable(path, + content::PluginServiceImpl::GetInstance()->IsPluginUnstable( + base::FilePath(path))); + } else { + // Execute on the IO thread. + CEF_POST_TASK(CEF_IOT, base::Bind(CefIsWebPluginUnstable, path, callback)); + } +} diff --git a/libcef/browser/web_plugin_impl.h b/libcef/browser/web_plugin_impl.h new file mode 100644 index 000000000..2a4fbee68 --- /dev/null +++ b/libcef/browser/web_plugin_impl.h @@ -0,0 +1,27 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_WEB_PLUGIN_IMPL_H_ +#define CEF_LIBCEF_BROWSER_WEB_PLUGIN_IMPL_H_ +#pragma once + +#include "include/cef_web_plugin.h" +#include "content/public/common/webplugininfo.h" + +class CefWebPluginInfoImpl : public CefWebPluginInfo { + public: + explicit CefWebPluginInfoImpl(const content::WebPluginInfo& plugin_info); + + CefString GetName() override; + CefString GetPath() override; + CefString GetVersion() override; + CefString GetDescription() override; + + private: + content::WebPluginInfo plugin_info_; + + IMPLEMENT_REFCOUNTING(CefWebPluginInfoImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_WEB_PLUGIN_IMPL_H_ diff --git a/libcef/browser/window_delegate_view.cc b/libcef/browser/window_delegate_view.cc new file mode 100644 index 000000000..491705285 --- /dev/null +++ b/libcef/browser/window_delegate_view.cc @@ -0,0 +1,65 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +#include "libcef/browser/window_delegate_view.h" + +#include "content/public/browser/web_contents.h" +#include "ui/views/background.h" +#include "ui/views/controls/webview/webview.h" +#include "ui/views/layout/fill_layout.h" +#include "ui/views/widget/widget.h" + +CefWindowDelegateView::CefWindowDelegateView(SkColor background_color) + : background_color_(background_color), + web_view_(NULL) { +} + +void CefWindowDelegateView::Init( + gfx::AcceleratedWidget parent_widget, + content::WebContents* web_contents, + const gfx::Rect& bounds) { + DCHECK(!web_view_); + web_view_ = new views::WebView(web_contents->GetBrowserContext()); + web_view_->SetWebContents(web_contents); + web_view_->SetPreferredSize(bounds.size()); + + views::Widget* widget = new views::Widget; + + // See CalculateWindowStylesFromInitParams in + // ui/views/widget/widget_hwnd_utils.cc for the conversion of |params| to + // Windows style flags. + views::Widget::InitParams params; + params.parent_widget = parent_widget; + params.bounds = bounds; + params.delegate = this; + // Set the WS_CHILD flag. + params.child = true; + // Set the WS_VISIBLE flag. + params.type = views::Widget::InitParams::TYPE_CONTROL; + // Don't set the WS_EX_COMPOSITED flag. + params.opacity = views::Widget::InitParams::OPAQUE_WINDOW; + // Tell Aura not to draw the window frame on resize. + params.remove_standard_frame = true; + + // Results in a call to InitContent(). + widget->Init(params); + + // |widget| should now be associated with |this|. + DCHECK_EQ(widget, GetWidget()); + // |widget| must be top-level for focus handling to work correctly. + DCHECK(widget->is_top_level()); +} + +void CefWindowDelegateView::InitContent() { + set_background(views::Background::CreateSolidBackground(background_color_)); + SetLayoutManager(new views::FillLayout()); + AddChildView(web_view_); +} + +void CefWindowDelegateView::ViewHierarchyChanged( + const ViewHierarchyChangedDetails& details) { + if (details.is_add && details.child == this) + InitContent(); +} + diff --git a/libcef/browser/window_delegate_view.h b/libcef/browser/window_delegate_view.h new file mode 100644 index 000000000..9b0e2f7b3 --- /dev/null +++ b/libcef/browser/window_delegate_view.h @@ -0,0 +1,50 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_WINDOW_DELEGATE_VIEW_H_ +#define CEF_LIBCEF_BROWSER_WINDOW_DELEGATE_VIEW_H_ +#pragma once + +#include "ui/views/widget/widget_delegate.h" + +namespace content { +class WebContents; +} + +namespace views { +class WebView; +} + +// Manages the views-based root window that hosts the web contents. This object +// will be deleted automatically when the associated root window is destroyed. +class CefWindowDelegateView : public views::WidgetDelegateView { + public: + explicit CefWindowDelegateView(SkColor background_color); + + // Create the Widget and associated root window. + void Init(gfx::AcceleratedWidget parent_widget, + content::WebContents* web_contents, + const gfx::Rect& bounds); + + private: + // Initialize the Widget's content. + void InitContent(); + + // WidgetDelegateView methods: + bool CanResize() const override { return true; } + bool CanMaximize() const override { return true; } + View* GetContentsView() override { return this; } + + // View methods: + void ViewHierarchyChanged( + const ViewHierarchyChangedDetails& details) override; + + private: + SkColor background_color_; + views::WebView* web_view_; + + DISALLOW_COPY_AND_ASSIGN(CefWindowDelegateView); +}; + +#endif // CEF_LIBCEF_BROWSER_WINDOW_DELEGATE_VIEW_H_ diff --git a/libcef/browser/window_x11.cc b/libcef/browser/window_x11.cc new file mode 100644 index 000000000..ef8438ecc --- /dev/null +++ b/libcef/browser/window_x11.cc @@ -0,0 +1,442 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. +// Portions copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/browser/window_x11.h" +#include "libcef/browser/thread_util.h" + +#include +#include +#include + +#include "ui/base/x/x11_util.h" +#include "ui/events/platform/x11/x11_event_source.h" +#include "ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h" +#include "ui/views/widget/desktop_aura/x11_topmost_window_finder.h" + +namespace { + +const char kAtom[] = "ATOM"; +const char kWMDeleteWindow[] = "WM_DELETE_WINDOW"; +const char kWMProtocols[] = "WM_PROTOCOLS"; +const char kNetWMPid[] = "_NET_WM_PID"; +const char kNetWMPing[] = "_NET_WM_PING"; +const char kNetWMState[] = "_NET_WM_STATE"; +const char kXdndProxy[] = "XdndProxy"; + +const char* kAtomsToCache[] = { + kAtom, + kWMDeleteWindow, + kWMProtocols, + kNetWMPid, + kNetWMPing, + kNetWMState, + kXdndProxy, + NULL +}; + +::Window FindEventTarget(const base::NativeEvent& xev) { + ::Window target = xev->xany.window; + if (xev->type == GenericEvent) + target = static_cast(xev->xcookie.data)->event; + return target; +} + +::Window FindChild(::Display* display, ::Window window) { + ::Window root; + ::Window parent; + ::Window* children; + ::Window child_window = None; + unsigned int nchildren; + if (XQueryTree(display, window, &root, &parent, &children, &nchildren)) { + DCHECK_EQ(1U, nchildren); + child_window = children[0]; + XFree(children); + } + return child_window; +} + +::Window FindToplevelParent(::Display* display, ::Window window) { + ::Window top_level_window = window; + ::Window root = None; + ::Window parent = None; + ::Window* children = NULL; + unsigned int nchildren = 0; + // Enumerate all parents of "window" to find the highest level window + // that either: + // - has a parent that does not contain the _NET_WM_PID property + // - has a parent that is the root window. + while (XQueryTree(display, window, &root, &parent, &children, &nchildren)) { + if (children) { + XFree(children); + } + + top_level_window = window; + if (!ui::PropertyExists(parent, kNetWMPid) || parent == root) { + break; + } + window = parent; + } + return top_level_window; +} +} // namespace + +CEF_EXPORT XDisplay* cef_get_xdisplay() { + if (!CEF_CURRENTLY_ON(CEF_UIT)) + return NULL; + return gfx::GetXDisplay(); +} + +CefWindowX11::CefWindowX11(CefRefPtr browser, + ::Window parent_xwindow, + const gfx::Rect& bounds) + : browser_(browser), + xdisplay_(gfx::GetXDisplay()), + parent_xwindow_(parent_xwindow), + xwindow_(0), + window_mapped_(false), + bounds_(bounds), + focus_pending_(false), + atom_cache_(xdisplay_, kAtomsToCache), + weak_ptr_factory_(this) { + if (parent_xwindow_ == None) + parent_xwindow_ = DefaultRootWindow(xdisplay_); + + XSetWindowAttributes swa; + memset(&swa, 0, sizeof(swa)); + swa.background_pixmap = None; + swa.override_redirect = false; + xwindow_ = XCreateWindow( + xdisplay_, parent_xwindow_, + bounds.x(), bounds.y(), bounds.width(), bounds.height(), + 0, // border width + CopyFromParent, // depth + InputOutput, + CopyFromParent, // visual + CWBackPixmap | CWOverrideRedirect, + &swa); + + if (ui::PlatformEventSource::GetInstance()) + ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); + + long event_mask = FocusChangeMask | StructureNotifyMask | PropertyChangeMask; + XSelectInput(xdisplay_, xwindow_, event_mask); + XFlush(xdisplay_); + + // TODO(erg): We currently only request window deletion events. We also + // should listen for activation events and anything else that GTK+ listens + // for, and do something useful. + ::Atom protocols[2]; + protocols[0] = atom_cache_.GetAtom(kWMDeleteWindow); + protocols[1] = atom_cache_.GetAtom(kNetWMPing); + XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); + + // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with + // the desktop environment. + XSetWMProperties(xdisplay_, xwindow_, NULL, NULL, NULL, 0, NULL, NULL, NULL); + + // Likewise, the X server needs to know this window's pid so it knows which + // program to kill if the window hangs. + // XChangeProperty() expects "pid" to be long. + COMPILE_ASSERT(sizeof(long) >= sizeof(pid_t), pid_t_bigger_than_long); + long pid = getpid(); + XChangeProperty(xdisplay_, + xwindow_, + atom_cache_.GetAtom(kNetWMPid), + XA_CARDINAL, + 32, + PropModeReplace, + reinterpret_cast(&pid), 1); + + // Allow subclasses to create and cache additional atoms. + atom_cache_.allow_uncached_atoms(); +} + +CefWindowX11::~CefWindowX11() { + DCHECK(!xwindow_); + if (ui::PlatformEventSource::GetInstance()) + ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); +} + +void CefWindowX11::Close() { + XEvent ev = {0}; + ev.xclient.type = ClientMessage; + ev.xclient.window = xwindow_; + ev.xclient.message_type = atom_cache_.GetAtom(kWMProtocols); + ev.xclient.format = 32; + ev.xclient.data.l[0] = atom_cache_.GetAtom(kWMDeleteWindow); + ev.xclient.data.l[1] = CurrentTime; + XSendEvent(xdisplay_, xwindow_, False, NoEventMask, &ev); +} + +void CefWindowX11::Show() { + if (xwindow_ == None) + return; + + if (!window_mapped_) { + // Before we map the window, set size hints. Otherwise, some window managers + // will ignore toplevel XMoveWindow commands. + XSizeHints size_hints; + size_hints.flags = PPosition | PWinGravity; + size_hints.x = bounds_.x(); + size_hints.y = bounds_.y(); + // Set StaticGravity so that the window position is not affected by the + // frame width when running with window manager. + size_hints.win_gravity = StaticGravity; + XSetWMNormalHints(xdisplay_, xwindow_, &size_hints); + + XMapWindow(xdisplay_, xwindow_); + + // We now block until our window is mapped. Some X11 APIs will crash and + // burn if passed |xwindow_| before the window is mapped, and XMapWindow is + // asynchronous. + if (ui::X11EventSource::GetInstance()) + ui::X11EventSource::GetInstance()->BlockUntilWindowMapped(xwindow_); + window_mapped_ = true; + + // Setup the drag and drop proxy on the top level window of the application + // to be the child of this window. + ::Window child = FindChild(xdisplay_, xwindow_); + ::Window toplevel_window = FindToplevelParent(xdisplay_, xwindow_); + DCHECK(toplevel_window); + if (child && toplevel_window) { + // Configure the drag&drop proxy property for the top-most window so + // that all drag&drop-related messages will be sent to the child + // DesktopWindowTreeHostX11. The proxy property is referenced by + // DesktopDragDropClientAuraX11::FindWindowFor. + ::Window proxy_target = gfx::kNullAcceleratedWidget; + ui::GetXIDProperty(toplevel_window, kXdndProxy, &proxy_target); + + if (proxy_target != child) { + // Set the proxy target for the top-most window. + XChangeProperty(xdisplay_, + toplevel_window, + atom_cache_.GetAtom(kXdndProxy), + XA_WINDOW, + 32, + PropModeReplace, + reinterpret_cast(&child), 1); + // Do the same for the proxy target per the spec. + XChangeProperty(xdisplay_, + child, + atom_cache_.GetAtom(kXdndProxy), + XA_WINDOW, + 32, + PropModeReplace, + reinterpret_cast(&child), 1); + } + } + } +} + +void CefWindowX11::Hide() { + if (xwindow_ == None) + return; + + if (window_mapped_) { + XWithdrawWindow(xdisplay_, xwindow_, 0); + window_mapped_ = false; + } +} + +void CefWindowX11::Focus() { + if (xwindow_ == None || !window_mapped_) + return; + + if (browser_.get()) { + ::Window child = FindChild(xdisplay_, xwindow_); + if (child && ui::IsWindowVisible(child)) { + // Give focus to the child DesktopWindowTreeHostX11. + XSetInputFocus(xdisplay_, child, RevertToParent, CurrentTime); + } + } else { + XSetInputFocus(xdisplay_, xwindow_, RevertToParent, CurrentTime); + } +} + +void CefWindowX11::SetBounds(const gfx::Rect& bounds) { + if (xwindow_ == None) + return; + + bool origin_changed = bounds_.origin() != bounds.origin(); + bool size_changed = bounds_.size() != bounds.size(); + XWindowChanges changes = {0}; + unsigned value_mask = 0; + + if (size_changed) { + changes.width = bounds.width(); + changes.height = bounds.height(); + value_mask = CWHeight | CWWidth; + } + + if (origin_changed) { + changes.x = bounds.x(); + changes.y = bounds.y(); + value_mask |= CWX | CWY; + } + + if (value_mask) + XConfigureWindow(xdisplay_, xwindow_, value_mask, &changes); +} + +gfx::Rect CefWindowX11::GetBoundsInScreen() { + int x, y; + Window child; + if (XTranslateCoordinates(xdisplay_, xwindow_, DefaultRootWindow(xdisplay_), + 0, 0, &x, &y, &child)) { + return gfx::Rect(gfx::Point(x, y), bounds_.size()); + } + return gfx::Rect(); +} + +views::DesktopWindowTreeHostX11* CefWindowX11::GetHost() { + if (browser_.get()) { + ::Window child = FindChild(xdisplay_, xwindow_); + if (child) + return views::DesktopWindowTreeHostX11::GetHostForXID(child); + } + return NULL; +} + +bool CefWindowX11::CanDispatchEvent(const ui::PlatformEvent& event) { + ::Window target = FindEventTarget(event); + return target == xwindow_; +} + +uint32_t CefWindowX11::DispatchEvent(const ui::PlatformEvent& event) { + XEvent* xev = event; + switch (xev->type) { + case ConfigureNotify: { + DCHECK_EQ(xwindow_, xev->xconfigure.event); + DCHECK_EQ(xwindow_, xev->xconfigure.window); + // It's possible that the X window may be resized by some other means + // than from within Aura (e.g. the X window manager can change the + // size). Make sure the root window size is maintained properly. + gfx::Rect bounds(xev->xconfigure.x, xev->xconfigure.y, + xev->xconfigure.width, xev->xconfigure.height); + bounds_ = bounds; + + if (browser_.get()) { + ::Window child = FindChild(xdisplay_, xwindow_); + if (child) { + // Resize the child DesktopWindowTreeHostX11 to match this window. + XWindowChanges changes = {0}; + changes.width = bounds.width(); + changes.height = bounds.height(); + XConfigureWindow(xdisplay_, child, CWHeight | CWWidth, &changes); + + browser_->NotifyMoveOrResizeStarted(); + } + } + break; + } + case ClientMessage: { + Atom message_type = xev->xclient.message_type; + if (message_type == atom_cache_.GetAtom(kWMProtocols)) { + Atom protocol = static_cast(xev->xclient.data.l[0]); + if (protocol == atom_cache_.GetAtom(kWMDeleteWindow)) { + // We have received a close message from the window manager. + if (browser_.get() && browser_->destruction_state() <= + CefBrowserHostImpl::DESTRUCTION_STATE_PENDING) { + if (browser_->destruction_state() == + CefBrowserHostImpl::DESTRUCTION_STATE_NONE) { + // Request that the browser close. + browser_->CloseBrowser(false); + } + + // Cancel the close. + } else { + // Allow the close. + XDestroyWindow(xdisplay_, xwindow_); + } + } else if (protocol == atom_cache_.GetAtom(kNetWMPing)) { + XEvent reply_event = *xev; + reply_event.xclient.window = parent_xwindow_; + + XSendEvent(xdisplay_, + reply_event.xclient.window, + False, + SubstructureRedirectMask | SubstructureNotifyMask, + &reply_event); + XFlush(xdisplay_); + } + } + break; + } + case DestroyNotify: + xwindow_ = None; + + if (browser_.get()) { + // Force the browser to be destroyed and release the reference added + // in PlatformCreateWindow(). + browser_->WindowDestroyed(); + } + + delete this; + break; + case FocusIn: + // This message is received first followed by a "_NET_ACTIVE_WINDOW" + // message sent to the root window. When X11DesktopHandler handles the + // "_NET_ACTIVE_WINDOW" message it will erroneously mark the WebView + // (hosted in a DesktopWindowTreeHostX11) as unfocused. Use a delayed + // task here to restore the WebView's focus state. + if (!focus_pending_) { + focus_pending_ = true; + CEF_POST_DELAYED_TASK(CEF_UIT, + base::Bind(&CefWindowX11::ContinueFocus, + weak_ptr_factory_.GetWeakPtr()), + 100); + } + break; + case FocusOut: + // Cancel the pending focus change if some other window has gained focus + // while waiting for the async task to run. Otherwise we can get stuck in + // a focus change loop. + if (focus_pending_) + focus_pending_ = false; + break; + case PropertyNotify: { + ::Atom changed_atom = xev->xproperty.atom; + if (changed_atom == atom_cache_.GetAtom(kNetWMState)) { + // State change event like minimize/maximize. + if (browser_.get()) { + ::Window child = FindChild(xdisplay_, xwindow_); + if (child) { + // Forward the state change to the child DesktopWindowTreeHostX11 + // window so that resource usage will be reduced while the window is + // minimized. + std::vector< ::Atom> atom_list; + if (ui::GetAtomArrayProperty(xwindow_, kNetWMState, &atom_list) && + !atom_list.empty()) { + ui::SetAtomArrayProperty(child, kNetWMState, "ATOM", atom_list); + } else { + // Set an empty list of property values to pass the check in + // DesktopWindowTreeHostX11::OnWMStateUpdated(). + XChangeProperty(xdisplay_, + child, + atom_cache_.GetAtom(kNetWMState), // name + atom_cache_.GetAtom(kAtom), // type + 32, // size in bits of items in 'value' + PropModeReplace, + NULL, + 0); // num items + } + } + } + } + break; + } + } + + return ui::POST_DISPATCH_STOP_PROPAGATION; +} + +void CefWindowX11::ContinueFocus() { + if (!focus_pending_) + return; + if (browser_.get()) + browser_->SetFocus(true); + focus_pending_ = false; +} + diff --git a/libcef/browser/window_x11.h b/libcef/browser/window_x11.h new file mode 100644 index 000000000..6554e915d --- /dev/null +++ b/libcef/browser/window_x11.h @@ -0,0 +1,78 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. +// Portions copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_WINDOW_X11_H_ +#define CEF_LIBCEF_BROWSER_WINDOW_X11_H_ +#pragma once + +#include + +#include "libcef/browser/browser_host_impl.h" + +#include "base/memory/weak_ptr.h" +#include "ui/events/platform/platform_event_dispatcher.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/x/x11_atom_cache.h" + +namespace views { +class DesktopWindowTreeHostX11; +} + +// Object wrapper for an X11 Window. +// Based on WindowTreeHostX11 and DesktopWindowTreeHostX11. +class CefWindowX11 : public ui::PlatformEventDispatcher { + public: + CefWindowX11(CefRefPtr browser, + ::Window parent_xwindow, + const gfx::Rect& bounds); + ~CefWindowX11() override; + + void Close(); + + void Show(); + void Hide(); + + void Focus(); + + void SetBounds(const gfx::Rect& bounds); + + gfx::Rect GetBoundsInScreen(); + + views::DesktopWindowTreeHostX11* GetHost(); + + // ui::PlatformEventDispatcher methods: + bool CanDispatchEvent(const ui::PlatformEvent& event) override; + uint32_t DispatchEvent(const ui::PlatformEvent& event) override; + + ::Window xwindow() const { return xwindow_; } + gfx::Rect bounds() const { return bounds_; } + + private: + void ContinueFocus(); + + CefRefPtr browser_; + + // The display and the native X window hosting the root window. + ::Display* xdisplay_; + ::Window parent_xwindow_; + ::Window xwindow_; + + // Is the window mapped to the screen? + bool window_mapped_; + + // The bounds of |xwindow_|. + gfx::Rect bounds_; + + bool focus_pending_; + + ui::X11AtomCache atom_cache_; + + // Must always be the last member. + base::WeakPtrFactory weak_ptr_factory_; + + DISALLOW_COPY_AND_ASSIGN(CefWindowX11); +}; + +#endif // CEF_LIBCEF_BROWSER_WINDOW_X11_H_ diff --git a/libcef/browser/xml_reader_impl.cc b/libcef/browser/xml_reader_impl.cc new file mode 100644 index 000000000..b66ea6326 --- /dev/null +++ b/libcef/browser/xml_reader_impl.cc @@ -0,0 +1,446 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/xml_reader_impl.h" +#include "include/cef_stream.h" +#include "base/logging.h" + +// Static functions + +// static +CefRefPtr CefXmlReader::Create(CefRefPtr stream, + EncodingType encodingType, + const CefString& URI) { + CefRefPtr impl(new CefXmlReaderImpl()); + if (!impl->Initialize(stream, encodingType, URI)) + return NULL; + return impl.get(); +} + + +// CefXmlReaderImpl + +namespace { + +/** + * xmlInputReadCallback: + * @context: an Input context + * @buffer: the buffer to store data read + * @len: the length of the buffer in bytes + * + * Callback used in the I/O Input API to read the resource + * + * Returns the number of bytes read or -1 in case of error + */ +int XMLCALL xml_read_callback(void * context, char * buffer, int len) { + CefRefPtr reader(static_cast(context)); + return reader->Read(buffer, 1, len); +} + +/** + * xmlTextReaderErrorFunc: + * @arg: the user argument + * @msg: the message + * @severity: the severity of the error + * @locator: a locator indicating where the error occured + * + * Signature of an error callback from a reader parser + */ +void XMLCALL xml_error_callback(void *arg, const char *msg, + xmlParserSeverities severity, + xmlTextReaderLocatorPtr locator) { + if (!msg) + return; + + std::string error_str(msg); + if (!error_str.empty() && error_str[error_str.length()-1] == '\n') + error_str.resize(error_str.length()-1); + + std::stringstream ss; + ss << error_str << ", line " << xmlTextReaderLocatorLineNumber(locator); + + LOG(INFO) << ss.str(); + + CefRefPtr impl(static_cast(arg)); + impl->AppendError(ss.str()); +} + +/** + * xmlStructuredErrorFunc: + * @userData: user provided data for the error callback + * @error: the error being raised. + * + * Signature of the function to use when there is an error and + * the module handles the new error reporting mechanism. + */ +void XMLCALL xml_structured_error_callback(void *userData, xmlErrorPtr error) { + if (!error->message) + return; + + std::string error_str(error->message); + if (!error_str.empty() && error_str[error_str.length()-1] == '\n') + error_str.resize(error_str.length()-1); + + std::stringstream ss; + ss << error_str << ", line " << error->line; + + LOG(INFO) << ss.str(); + + CefRefPtr impl(static_cast(userData)); + impl->AppendError(ss.str()); +} + +CefString xmlCharToString(const xmlChar* xmlStr, bool free) { + if (!xmlStr) + return CefString(); + + const char* str = reinterpret_cast(xmlStr); + CefString wstr = std::string(str); + + if (free) + xmlFree(const_cast(xmlStr)); + + return wstr; +} + +} // namespace + +CefXmlReaderImpl::CefXmlReaderImpl() + : supported_thread_id_(base::PlatformThread::CurrentId()), reader_(NULL) { +} + +CefXmlReaderImpl::~CefXmlReaderImpl() { + if (reader_ != NULL) { + if (!VerifyContext()) { + // Close() is supposed to be called directly. We'll try to free the reader + // now on the wrong thread but there's no guarantee this call won't crash. + xmlFreeTextReader(reader_); + } else { + Close(); + } + } +} + +bool CefXmlReaderImpl::Initialize(CefRefPtr stream, + EncodingType encodingType, + const CefString& URI) { + xmlCharEncoding enc = XML_CHAR_ENCODING_NONE; + switch (encodingType) { + case XML_ENCODING_UTF8: + enc = XML_CHAR_ENCODING_UTF8; + break; + case XML_ENCODING_UTF16LE: + enc = XML_CHAR_ENCODING_UTF16LE; + break; + case XML_ENCODING_UTF16BE: + enc = XML_CHAR_ENCODING_UTF16BE; + break; + case XML_ENCODING_ASCII: + enc = XML_CHAR_ENCODING_ASCII; + break; + default: + break; + } + + // Create the input buffer. + xmlParserInputBufferPtr input_buffer = xmlAllocParserInputBuffer(enc); + if (!input_buffer) + return false; + + input_buffer->context = stream.get(); + input_buffer->readcallback = xml_read_callback; + + // Create the text reader. + std::string uriStr = URI; + reader_ = xmlNewTextReader(input_buffer, uriStr.c_str()); + if (!reader_) { + // Free the input buffer. + xmlFreeParserInputBuffer(input_buffer); + return false; + } + + // Keep a reference to the stream. + stream_ = stream; + + // Register the error callbacks. + xmlTextReaderSetErrorHandler(reader_, xml_error_callback, this); + xmlTextReaderSetStructuredErrorHandler(reader_, + xml_structured_error_callback, this); + + return true; +} + +bool CefXmlReaderImpl::MoveToNextNode() { + if (!VerifyContext()) + return false; + + return xmlTextReaderRead(reader_) == 1 ? true : false; +} + +bool CefXmlReaderImpl::Close() { + if (!VerifyContext()) + return false; + + // The input buffer will be freed automatically. + xmlFreeTextReader(reader_); + reader_ = NULL; + return true; +} + +bool CefXmlReaderImpl::HasError() { + if (!VerifyContext()) + return false; + + return !error_buf_.str().empty(); +} + +CefString CefXmlReaderImpl::GetError() { + if (!VerifyContext()) + return CefString(); + + return error_buf_.str(); +} + +CefXmlReader::NodeType CefXmlReaderImpl::GetType() { + if (!VerifyContext()) + return XML_NODE_UNSUPPORTED; + + switch (xmlTextReaderNodeType(reader_)) { + case XML_READER_TYPE_ELEMENT: + return XML_NODE_ELEMENT_START; + case XML_READER_TYPE_END_ELEMENT: + return XML_NODE_ELEMENT_END; + case XML_READER_TYPE_ATTRIBUTE: + return XML_NODE_ATTRIBUTE; + case XML_READER_TYPE_TEXT: + return XML_NODE_TEXT; + case XML_READER_TYPE_SIGNIFICANT_WHITESPACE: + case XML_READER_TYPE_WHITESPACE: + return XML_NODE_WHITESPACE; + case XML_READER_TYPE_CDATA: + return XML_NODE_CDATA; + case XML_READER_TYPE_ENTITY_REFERENCE: + return XML_NODE_ENTITY_REFERENCE; + case XML_READER_TYPE_PROCESSING_INSTRUCTION: + return XML_NODE_PROCESSING_INSTRUCTION; + case XML_READER_TYPE_COMMENT: + return XML_NODE_COMMENT; + case XML_READER_TYPE_DOCUMENT_TYPE: + return XML_NODE_DOCUMENT_TYPE; + default: + break; + } + + return XML_NODE_UNSUPPORTED; +} + +int CefXmlReaderImpl::GetDepth() { + if (!VerifyContext()) + return -1; + + return xmlTextReaderDepth(reader_); +} + +CefString CefXmlReaderImpl::GetLocalName() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderConstLocalName(reader_), false); +} + +CefString CefXmlReaderImpl::GetPrefix() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderConstPrefix(reader_), false); +} + +CefString CefXmlReaderImpl::GetQualifiedName() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderConstName(reader_), false); +} + +CefString CefXmlReaderImpl::GetNamespaceURI() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderConstNamespaceUri(reader_), false); +} + +CefString CefXmlReaderImpl::GetBaseURI() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderConstBaseUri(reader_), false); +} + +CefString CefXmlReaderImpl::GetXmlLang() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderConstXmlLang(reader_), false); +} + +bool CefXmlReaderImpl::IsEmptyElement() { + if (!VerifyContext()) + return false; + + return xmlTextReaderIsEmptyElement(reader_) == 1 ? true : false; +} + +bool CefXmlReaderImpl::HasValue() { + if (!VerifyContext()) + return false; + + if (xmlTextReaderNodeType(reader_) == XML_READER_TYPE_ENTITY_REFERENCE) { + // Provide special handling to return entity reference values. + return true; + } else { + return xmlTextReaderHasValue(reader_) == 1 ? true : false; + } +} + +CefString CefXmlReaderImpl::GetValue() { + if (!VerifyContext()) + return CefString(); + + if (xmlTextReaderNodeType(reader_) == XML_READER_TYPE_ENTITY_REFERENCE) { + // Provide special handling to return entity reference values. + xmlNodePtr node = xmlTextReaderCurrentNode(reader_); + if (node->content != NULL) + return xmlCharToString(node->content, false); + return CefString(); + } else { + return xmlCharToString(xmlTextReaderConstValue(reader_), false); + } +} + +bool CefXmlReaderImpl::HasAttributes() { + if (!VerifyContext()) + return false; + + return xmlTextReaderHasAttributes(reader_) == 1 ? true : false; +} + +size_t CefXmlReaderImpl::GetAttributeCount() { + if (!VerifyContext()) + return 0; + + return xmlTextReaderAttributeCount(reader_); +} + +CefString CefXmlReaderImpl::GetAttribute(int index) { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderGetAttributeNo(reader_, index), true); +} + +CefString CefXmlReaderImpl::GetAttribute(const CefString& qualifiedName) { + if (!VerifyContext()) + return CefString(); + + std::string qualifiedNameStr = qualifiedName; + return xmlCharToString(xmlTextReaderGetAttribute(reader_, + BAD_CAST qualifiedNameStr.c_str()), true); +} + +CefString CefXmlReaderImpl::GetAttribute(const CefString& localName, + const CefString& namespaceURI) { + if (!VerifyContext()) + return CefString(); + + std::string localNameStr = localName; + std::string namespaceURIStr = namespaceURI; + return xmlCharToString(xmlTextReaderGetAttributeNs(reader_, + BAD_CAST localNameStr.c_str(), BAD_CAST namespaceURIStr.c_str()), true); +} + +CefString CefXmlReaderImpl::GetInnerXml() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderReadInnerXml(reader_), true); +} + +CefString CefXmlReaderImpl::GetOuterXml() { + if (!VerifyContext()) + return CefString(); + + return xmlCharToString(xmlTextReaderReadOuterXml(reader_), true); +} + +int CefXmlReaderImpl::GetLineNumber() { + if (!VerifyContext()) + return -1; + + return xmlTextReaderGetParserLineNumber(reader_); +} + +bool CefXmlReaderImpl::MoveToAttribute(int index) { + if (!VerifyContext()) + return false; + + return xmlTextReaderMoveToAttributeNo(reader_, index) == 1 ? true : false; +} + +bool CefXmlReaderImpl::MoveToAttribute(const CefString& qualifiedName) { + if (!VerifyContext()) + return false; + + std::string qualifiedNameStr = qualifiedName; + return xmlTextReaderMoveToAttribute(reader_, + BAD_CAST qualifiedNameStr.c_str()) == 1 ? true : false; +} + +bool CefXmlReaderImpl::MoveToAttribute(const CefString& localName, + const CefString& namespaceURI) { + if (!VerifyContext()) + return false; + + std::string localNameStr = localName; + std::string namespaceURIStr = namespaceURI; + return xmlTextReaderMoveToAttributeNs(reader_, + BAD_CAST localNameStr.c_str(), BAD_CAST namespaceURIStr.c_str()) == 1 ? + true : false; +} + +bool CefXmlReaderImpl::MoveToFirstAttribute() { + if (!VerifyContext()) + return false; + + return xmlTextReaderMoveToFirstAttribute(reader_) == 1 ? true : false; +} + +bool CefXmlReaderImpl::MoveToNextAttribute() { + if (!VerifyContext()) + return false; + + return xmlTextReaderMoveToNextAttribute(reader_) == 1 ? true : false; +} + +bool CefXmlReaderImpl::MoveToCarryingElement() { + if (!VerifyContext()) + return false; + + return xmlTextReaderMoveToElement(reader_) == 1 ? true : false; +} + +void CefXmlReaderImpl::AppendError(const CefString& error_str) { + if (!error_buf_.str().empty()) + error_buf_ << L"\n"; + error_buf_ << error_str; +} + +bool CefXmlReaderImpl::VerifyContext() { + if (base::PlatformThread::CurrentId() != supported_thread_id_) { + // This object should only be accessed from the thread that created it. + NOTREACHED(); + return false; + } + + return (reader_ != NULL); +} diff --git a/libcef/browser/xml_reader_impl.h b/libcef/browser/xml_reader_impl.h new file mode 100644 index 000000000..7afb51cb0 --- /dev/null +++ b/libcef/browser/xml_reader_impl.h @@ -0,0 +1,73 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_XML_READER_IMPL_H_ +#define CEF_LIBCEF_BROWSER_XML_READER_IMPL_H_ +#pragma once + +#include +#include + +#include "include/cef_xml_reader.h" +#include "base/threading/platform_thread.h" + +// Implementation of CefXmlReader +class CefXmlReaderImpl : public CefXmlReader { + public: + CefXmlReaderImpl(); + ~CefXmlReaderImpl() override; + + // Initialize the reader context. + bool Initialize(CefRefPtr stream, + EncodingType encodingType, const CefString& URI); + + bool MoveToNextNode() override; + bool Close() override; + bool HasError() override; + CefString GetError() override; + NodeType GetType() override; + int GetDepth() override; + CefString GetLocalName() override; + CefString GetPrefix() override; + CefString GetQualifiedName() override; + CefString GetNamespaceURI() override; + CefString GetBaseURI() override; + CefString GetXmlLang() override; + bool IsEmptyElement() override; + bool HasValue() override; + CefString GetValue() override; + bool HasAttributes() override; + size_t GetAttributeCount() override; + CefString GetAttribute(int index) override; + CefString GetAttribute(const CefString& qualifiedName) override; + CefString GetAttribute(const CefString& localName, + const CefString& namespaceURI) override; + CefString GetInnerXml() override; + CefString GetOuterXml() override; + int GetLineNumber() override; + bool MoveToAttribute(int index) override; + bool MoveToAttribute(const CefString& qualifiedName) override; + bool MoveToAttribute(const CefString& localName, + const CefString& namespaceURI) override; + bool MoveToFirstAttribute() override; + bool MoveToNextAttribute() override; + bool MoveToCarryingElement() override; + + // Add another line to the error string. + void AppendError(const CefString& error_str); + + // Verify that the reader exists and is being accessed from the correct + // thread. + bool VerifyContext(); + + protected: + base::PlatformThreadId supported_thread_id_; + CefRefPtr stream_; + xmlTextReaderPtr reader_; + std::stringstream error_buf_; + + IMPLEMENT_REFCOUNTING(CefXmlReaderImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_XML_READER_IMPL_H_ diff --git a/libcef/browser/zip_reader_impl.cc b/libcef/browser/zip_reader_impl.cc new file mode 100644 index 000000000..dca92ae36 --- /dev/null +++ b/libcef/browser/zip_reader_impl.cc @@ -0,0 +1,280 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/browser/zip_reader_impl.h" +#include +#include "include/cef_stream.h" +#include "base/logging.h" + +// Static functions + +// static +CefRefPtr CefZipReader::Create( + CefRefPtr stream) { + CefRefPtr impl(new CefZipReaderImpl()); + if (!impl->Initialize(stream)) + return NULL; + return impl.get(); +} + + +// CefZipReaderImpl + +namespace { + +voidpf ZCALLBACK zlib_open_callback OF((voidpf opaque, const void* filename, + int mode)) { + // The stream is already implicitly open so just return the pointer. + return opaque; +} + +uLong ZCALLBACK zlib_read_callback OF((voidpf opaque, voidpf stream, void* buf, + uLong size)) { + CefRefPtr reader(static_cast(opaque)); + return reader->Read(buf, 1, size); +} + +ZPOS64_T ZCALLBACK zlib_tell_callback OF((voidpf opaque, voidpf stream)) { + CefRefPtr reader(static_cast(opaque)); + return reader->Tell(); +} + +long ZCALLBACK zlib_seek_callback OF((voidpf opaque, // NOLINT(runtime/int) + voidpf stream, ZPOS64_T offset, + int origin)) { + CefRefPtr reader(static_cast(opaque)); + int whence; + switch (origin) { + case ZLIB_FILEFUNC_SEEK_CUR: + whence = SEEK_CUR; + break; + case ZLIB_FILEFUNC_SEEK_END: + whence = SEEK_END; + break; + case ZLIB_FILEFUNC_SEEK_SET: + whence = SEEK_SET; + break; + default: + NOTREACHED(); + return -1; + } + return reader->Seek(offset, whence); +} + +int ZCALLBACK zlib_close_callback OF((voidpf opaque, voidpf stream)) { + CefRefPtr reader(static_cast(opaque)); + // Release the reference added by CefZipReaderImpl::Initialize(). + reader->Release(); + return 0; +} + +int ZCALLBACK zlib_error_callback OF((voidpf opaque, voidpf stream)) { + return 0; +} + +} // namespace + +CefZipReaderImpl::CefZipReaderImpl() + : supported_thread_id_(base::PlatformThread::CurrentId()), reader_(NULL), + has_fileopen_(false), + has_fileinfo_(false), + filesize_(0), + filemodified_(0) { +} + +CefZipReaderImpl::~CefZipReaderImpl() { + if (reader_ != NULL) { + if (!VerifyContext()) { + // Close() is supposed to be called directly. We'll try to free the reader + // now on the wrong thread but there's no guarantee this call won't crash. + if (has_fileopen_) + unzCloseCurrentFile(reader_); + unzClose(reader_); + } else { + Close(); + } + } +} + +bool CefZipReaderImpl::Initialize(CefRefPtr stream) { + zlib_filefunc64_def filefunc_def; + filefunc_def.zopen64_file = zlib_open_callback; + filefunc_def.zread_file = zlib_read_callback; + filefunc_def.zwrite_file = NULL; + filefunc_def.ztell64_file = zlib_tell_callback; + filefunc_def.zseek64_file = zlib_seek_callback; + filefunc_def.zclose_file = zlib_close_callback; + filefunc_def.zerror_file = zlib_error_callback; + filefunc_def.opaque = stream.get(); + + // Add a reference that will be released by zlib_close_callback(). + stream->AddRef(); + + reader_ = unzOpen2_64("", &filefunc_def); + return (reader_ != NULL); +} + +bool CefZipReaderImpl::MoveToFirstFile() { + if (!VerifyContext()) + return false; + + if (has_fileopen_) + CloseFile(); + + has_fileinfo_ = false; + + return (unzGoToFirstFile(reader_) == UNZ_OK); +} + +bool CefZipReaderImpl::MoveToNextFile() { + if (!VerifyContext()) + return false; + + if (has_fileopen_) + CloseFile(); + + has_fileinfo_ = false; + + return (unzGoToNextFile(reader_) == UNZ_OK); +} + +bool CefZipReaderImpl::MoveToFile(const CefString& fileName, + bool caseSensitive) { + if (!VerifyContext()) + return false; + + if (has_fileopen_) + CloseFile(); + + has_fileinfo_ = false; + + std::string fileNameStr = fileName; + return (unzLocateFile(reader_, fileNameStr.c_str(), + (caseSensitive ? 1 : 2)) == UNZ_OK); +} + +bool CefZipReaderImpl::Close() { + if (!VerifyContext()) + return false; + + if (has_fileopen_) + CloseFile(); + + int result = unzClose(reader_); + reader_ = NULL; + return (result == UNZ_OK); +} + +CefString CefZipReaderImpl::GetFileName() { + if (!VerifyContext() || !GetFileInfo()) + return CefString(); + + return filename_; +} + +int64 CefZipReaderImpl::GetFileSize() { + if (!VerifyContext() || !GetFileInfo()) + return -1; + + return filesize_; +} + +time_t CefZipReaderImpl::GetFileLastModified() { + if (!VerifyContext() || !GetFileInfo()) + return 0; + + return filemodified_; +} + +bool CefZipReaderImpl::OpenFile(const CefString& password) { + if (!VerifyContext()) + return false; + + if (has_fileopen_) + CloseFile(); + + bool ret; + + if (password.empty()) { + ret = (unzOpenCurrentFile(reader_) == UNZ_OK); + } else { + std::string passwordStr = password; + ret = (unzOpenCurrentFilePassword(reader_, passwordStr.c_str()) == UNZ_OK); + } + + if (ret) + has_fileopen_ = true; + return ret; +} + +bool CefZipReaderImpl::CloseFile() { + if (!VerifyContext() || !has_fileopen_) + return false; + + has_fileopen_ = false; + has_fileinfo_ = false; + + return (unzCloseCurrentFile(reader_) == UNZ_OK); +} + +int CefZipReaderImpl::ReadFile(void* buffer, size_t bufferSize) { + if (!VerifyContext() || !has_fileopen_) + return -1; + + return unzReadCurrentFile(reader_, buffer, bufferSize); +} + +int64 CefZipReaderImpl::Tell() { + if (!VerifyContext() || !has_fileopen_) + return -1; + + return unztell64(reader_); +} + +bool CefZipReaderImpl::Eof() { + if (!VerifyContext() || !has_fileopen_) + return true; + + return (unzeof(reader_) == 1 ? true : false); +} + +bool CefZipReaderImpl::GetFileInfo() { + if (has_fileinfo_) + return true; + + char file_name[512] = {0}; + unz_file_info file_info; + memset(&file_info, 0, sizeof(file_info)); + + if (unzGetCurrentFileInfo(reader_, &file_info, file_name, sizeof(file_name), + NULL, 0, NULL, 0) != UNZ_OK) { + return false; + } + + has_fileinfo_ = true; + filename_ = std::string(file_name); + filesize_ = file_info.uncompressed_size; + + struct tm time; + memset(&time, 0, sizeof(time)); + time.tm_sec = file_info.tmu_date.tm_sec; + time.tm_min = file_info.tmu_date.tm_min; + time.tm_hour = file_info.tmu_date.tm_hour; + time.tm_mday = file_info.tmu_date.tm_mday; + time.tm_mon = file_info.tmu_date.tm_mon; + time.tm_year = file_info.tmu_date.tm_year; + filemodified_ = mktime(&time); + + return true; +} + +bool CefZipReaderImpl::VerifyContext() { + if (base::PlatformThread::CurrentId() != supported_thread_id_) { + // This object should only be accessed from the thread that created it. + NOTREACHED(); + return false; + } + + return (reader_ != NULL); +} diff --git a/libcef/browser/zip_reader_impl.h b/libcef/browser/zip_reader_impl.h new file mode 100644 index 000000000..d3a9c0968 --- /dev/null +++ b/libcef/browser/zip_reader_impl.h @@ -0,0 +1,55 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_BROWSER_ZIP_READER_IMPL_H_ +#define CEF_LIBCEF_BROWSER_ZIP_READER_IMPL_H_ +#pragma once + +#include + +#include "include/cef_zip_reader.h" +#include "base/threading/platform_thread.h" +#include "third_party/zlib/contrib/minizip/unzip.h" + +// Implementation of CefZipReader +class CefZipReaderImpl : public CefZipReader { + public: + CefZipReaderImpl(); + ~CefZipReaderImpl() override; + + // Initialize the reader context. + bool Initialize(CefRefPtr stream); + + bool MoveToFirstFile() override; + bool MoveToNextFile() override; + bool MoveToFile(const CefString& fileName, bool caseSensitive) override; + bool Close() override; + CefString GetFileName() override; + int64 GetFileSize() override; + time_t GetFileLastModified() override; + bool OpenFile(const CefString& password) override; + bool CloseFile() override; + int ReadFile(void* buffer, size_t bufferSize) override; + int64 Tell() override; + bool Eof() override; + + bool GetFileInfo(); + + // Verify that the reader exists and is being accessed from the correct + // thread. + bool VerifyContext(); + + protected: + base::PlatformThreadId supported_thread_id_; + unzFile reader_; + bool has_fileopen_; + bool has_fileinfo_; + CefString filename_; + int64 filesize_; + time_t filemodified_; + + IMPLEMENT_REFCOUNTING(CefZipReaderImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_ZIP_READER_IMPL_H_ diff --git a/libcef/common/base_impl.cc b/libcef/common/base_impl.cc new file mode 100644 index 000000000..483225dde --- /dev/null +++ b/libcef/common/base_impl.cc @@ -0,0 +1,345 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "include/internal/cef_trace_event_internal.h" +#include "include/internal/cef_logging_internal.h" +#include "include/internal/cef_thread_internal.h" + +#include "base/debug/trace_event.h" +#include "base/logging.h" +#include "base/threading/platform_thread.h" + +// The contents of this file are a compilation unit that is not called by other +// functions in the the library. Consiquently MSVS will exclude it during the +// linker stage if we don't call a stub function. +#if defined(COMPILER_MSVC) +#pragma optimize("", off) +#endif + +void base_impl_stub() {} + +#if defined(COMPILER_MSVC) +#pragma optimize("", on) +#endif + + +CEF_EXPORT void cef_trace_event_instant(const char* category, + const char* name, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_COPY_INSTANT0(category, name, TRACE_EVENT_SCOPE_THREAD); + } else if (arg2_name == NULL) { + TRACE_EVENT_COPY_INSTANT1(category, name, TRACE_EVENT_SCOPE_THREAD, + arg1_name, arg1_val); + } else { + TRACE_EVENT_COPY_INSTANT2(category, name, TRACE_EVENT_SCOPE_THREAD, + arg1_name, arg1_val, arg2_name, arg2_val); + } + } else { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_INSTANT0(category, name, TRACE_EVENT_SCOPE_THREAD); + } else if (arg2_name == NULL) { + TRACE_EVENT_INSTANT1(category, name, TRACE_EVENT_SCOPE_THREAD, + arg1_name, arg1_val); + } else { + TRACE_EVENT_INSTANT2(category, name, TRACE_EVENT_SCOPE_THREAD, + arg1_name, arg1_val, arg2_name, arg2_val); + } + } +} + +CEF_EXPORT void cef_trace_event_begin(const char* category, + const char* name, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_COPY_BEGIN0(category, name); + } else if (arg2_name == NULL) { + TRACE_EVENT_COPY_BEGIN1(category, name, arg1_name, arg1_val); + } else { + TRACE_EVENT_COPY_BEGIN2(category, name, arg1_name, arg1_val, + arg2_name, arg2_val); + } + } else { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_BEGIN0(category, name); + } else if (arg2_name == NULL) { + TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val); + } else { + TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, + arg2_name, arg2_val); + } + } +} + +CEF_EXPORT void cef_trace_event_end(const char* category, + const char* name, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_COPY_END0(category, name); + } else if (arg2_name == NULL) { + TRACE_EVENT_COPY_END1(category, name, arg1_name, arg1_val); + } else { + TRACE_EVENT_COPY_END2(category, name, arg1_name, arg1_val, + arg2_name, arg2_val); + } + } else { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_END0(category, name); + } else if (arg2_name == NULL) { + TRACE_EVENT_END1(category, name, arg1_name, arg1_val); + } else { + TRACE_EVENT_END2(category, name, arg1_name, arg1_val, + arg2_name, arg2_val); + } + } +} + +CEF_EXPORT void cef_trace_counter(const char* category, + const char* name, + const char* value1_name, + uint64 value1_val, + const char* value2_name, + uint64 value2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (value1_name == NULL && value2_name == NULL) { + TRACE_COPY_COUNTER1(category, name, value1_val); + } else { + TRACE_COPY_COUNTER2(category, name, value1_name, value1_val, + value2_name, value2_val); + } + } else { + if (value1_name == NULL && value2_name == NULL) { + TRACE_COUNTER1(category, name, value1_val); + } else { + TRACE_COUNTER2(category, name, value1_name, value1_val, + value2_name, value2_val); + } + } +} + +CEF_EXPORT void cef_trace_counter_id(const char* category, + const char* name, + uint64 id, + const char* value1_name, + uint64 value1_val, + const char* value2_name, + uint64 value2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (value1_name == NULL && value2_name == NULL) { + TRACE_COPY_COUNTER_ID1(category, name, id, value1_val); + } else { + TRACE_COPY_COUNTER_ID2(category, name, id, value1_name, + value1_val, value2_name, value2_val); + } + } else { + if (value1_name == NULL && value2_name == NULL) { + TRACE_COUNTER_ID1(category, name, id, value1_val); + } else { + TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val, + value2_name, value2_val); + } + } +} + +CEF_EXPORT void cef_trace_event_async_begin(const char* category, + const char* name, + uint64 id, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_COPY_ASYNC_BEGIN0(category, name, id); + } else if (arg2_name == NULL) { + TRACE_EVENT_COPY_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val); + } else { + TRACE_EVENT_COPY_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, + arg2_name, arg2_val); + } + } else { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_ASYNC_BEGIN0(category, name, id); + } else if (arg2_name == NULL) { + TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val); + } else { + TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, + arg2_name, arg2_val); + } + } +} + +CEF_EXPORT void cef_trace_event_async_step_into(const char* category, + const char* name, + uint64 id, + uint64 step, + const char* arg1_name, + uint64 arg1_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL) { + INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_INTO, + category, name, id, TRACE_EVENT_FLAG_COPY, "step", step); + } else { + INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_INTO, + category, name, id, TRACE_EVENT_FLAG_COPY, "step", step, + arg1_name, arg1_val); + } + } else { + if (arg1_name == NULL) { + TRACE_EVENT_ASYNC_STEP_INTO0(category, name, id, step); + } else { + TRACE_EVENT_ASYNC_STEP_INTO1(category, name, id, step, + arg1_name, arg1_val); + } + } +} + +CEF_EXPORT void cef_trace_event_async_step_past(const char* category, + const char* name, + uint64 id, + uint64 step, + const char* arg1_name, + uint64 arg1_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL) { + INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_PAST, + category, name, id, TRACE_EVENT_FLAG_COPY, "step", step); + } else { + INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP_PAST, + category, name, id, TRACE_EVENT_FLAG_COPY, "step", step, + arg1_name, arg1_val); + } + } else { + if (arg1_name == NULL) { + TRACE_EVENT_ASYNC_STEP_PAST0(category, name, id, step); + } else { + TRACE_EVENT_ASYNC_STEP_PAST1(category, name, id, step, + arg1_name, arg1_val); + } + } +} + +CEF_EXPORT void cef_trace_event_async_end(const char* category, + const char* name, + uint64 id, + const char* arg1_name, + uint64 arg1_val, + const char* arg2_name, + uint64 arg2_val, + int copy) { + DCHECK(category); + DCHECK(name); + if (!category || !name) + return; + + if (copy) { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_COPY_ASYNC_END0(category, name, id); + } else if (arg2_name == NULL) { + TRACE_EVENT_COPY_ASYNC_END1(category, name, id, arg1_name, + arg1_val); + } else { + TRACE_EVENT_COPY_ASYNC_END2(category, name, id, arg1_name, + arg1_val, arg2_name, arg2_val); + } + } else { + if (arg1_name == NULL && arg2_name == NULL) { + TRACE_EVENT_ASYNC_END0(category, name, id); + } else if (arg2_name == NULL) { + TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, + arg1_val); + } else { + TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name, + arg1_val, arg2_name, arg2_val); + } + } +} + +CEF_EXPORT int cef_get_min_log_level() { + return logging::GetMinLogLevel(); +} + +CEF_EXPORT int cef_get_vlog_level(const char* file_start, size_t N) { + return logging::GetVlogLevelHelper(file_start, N); +} + +CEF_EXPORT void cef_log(const char* file, + int line, + int severity, + const char* message) { + logging::LogMessage(file, line, severity).stream() << message; +} + +CEF_EXPORT cef_platform_thread_id_t cef_get_current_platform_thread_id() { + return base::PlatformThread::CurrentId(); +} + +CEF_EXPORT cef_platform_thread_handle_t + cef_get_current_platform_thread_handle() { +#if defined(OS_WIN) + return base::PlatformThread::CurrentId(); +#else + return base::PlatformThread::CurrentHandle().platform_handle(); +#endif +} diff --git a/libcef/common/cef_message_generator.cc b/libcef/common/cef_message_generator.cc new file mode 100644 index 000000000..6e16dc1d4 --- /dev/null +++ b/libcef/common/cef_message_generator.cc @@ -0,0 +1,33 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Get basic type definitions. +#define IPC_MESSAGE_IMPL +#include "libcef/common/cef_message_generator.h" + +// Generate constructors. +#include "ipc/struct_constructor_macros.h" +#include "libcef/common/cef_message_generator.h" + +// Generate destructors. +#include "ipc/struct_destructor_macros.h" +#include "libcef/common/cef_message_generator.h" + +// Generate param traits write methods. +#include "ipc/param_traits_write_macros.h" +namespace IPC { +#include "libcef/common/cef_message_generator.h" +} // namespace IPC + +// Generate param traits read methods. +#include "ipc/param_traits_read_macros.h" +namespace IPC { +#include "libcef/common/cef_message_generator.h" +} // namespace IPC + +// Generate param traits log methods. +#include "ipc/param_traits_log_macros.h" +namespace IPC { +#include "libcef/common/cef_message_generator.h" +} // namespace IPC diff --git a/libcef/common/cef_message_generator.h b/libcef/common/cef_message_generator.h new file mode 100644 index 000000000..124361160 --- /dev/null +++ b/libcef/common/cef_message_generator.h @@ -0,0 +1,7 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Multiply-included file, hence no include guard. + +#include "libcef/common/cef_messages.h" diff --git a/libcef/common/cef_messages.cc b/libcef/common/cef_messages.cc new file mode 100644 index 000000000..5a130c150 --- /dev/null +++ b/libcef/common/cef_messages.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/common/cef_messages.h" + +namespace IPC { + +// Extracted from chrome/common/automation_messages.cc. + +// Only the net::UploadData ParamTraits<> definition needs this definition, so +// keep this in the implementation file so we can forward declare UploadData in +// the header. +template <> +struct ParamTraits { + typedef net::UploadElement param_type; + static void Write(Message* m, const param_type& p) { + WriteParam(m, static_cast(p.type())); + switch (p.type()) { + case net::UploadElement::TYPE_BYTES: { + m->WriteData(p.bytes(), static_cast(p.bytes_length())); + break; + } + default: { + DCHECK(p.type() == net::UploadElement::TYPE_FILE); + WriteParam(m, p.file_path()); + WriteParam(m, p.file_range_offset()); + WriteParam(m, p.file_range_length()); + WriteParam(m, p.expected_file_modification_time()); + break; + } + } + } + static bool Read(const Message* m, PickleIterator* iter, param_type* r) { + int type; + if (!ReadParam(m, iter, &type)) + return false; + switch (type) { + case net::UploadElement::TYPE_BYTES: { + const char* data; + int len; + if (!iter->ReadData(&data, &len)) + return false; + r->SetToBytes(data, len); + break; + } + default: { + DCHECK(type == net::UploadElement::TYPE_FILE); + base::FilePath file_path; + uint64 offset, length; + base::Time expected_modification_time; + if (!ReadParam(m, iter, &file_path)) + return false; + if (!ReadParam(m, iter, &offset)) + return false; + if (!ReadParam(m, iter, &length)) + return false; + if (!ReadParam(m, iter, &expected_modification_time)) + return false; + r->SetToFilePathRange(file_path, offset, length, + expected_modification_time); + break; + } + } + return true; + } + static void Log(const param_type& p, std::string* l) { + l->append(""); + } +}; + +void ParamTraits >::Write(Message* m, + const param_type& p) { + WriteParam(m, p.get() != NULL); + if (p.get()) { + WriteParam(m, p->elements()); + WriteParam(m, p->identifier()); + WriteParam(m, p->is_chunked()); + WriteParam(m, p->last_chunk_appended()); + } +} + +bool ParamTraits >::Read(const Message* m, + PickleIterator* iter, + param_type* r) { + bool has_object; + if (!ReadParam(m, iter, &has_object)) + return false; + if (!has_object) + return true; + ScopedVector elements; + if (!ReadParam(m, iter, &elements)) + return false; + int64 identifier; + if (!ReadParam(m, iter, &identifier)) + return false; + bool is_chunked = false; + if (!ReadParam(m, iter, &is_chunked)) + return false; + bool last_chunk_appended = false; + if (!ReadParam(m, iter, &last_chunk_appended)) + return false; + *r = new net::UploadData; + (*r)->swap_elements(&elements); + (*r)->set_identifier(identifier); + (*r)->set_is_chunked(is_chunked); + (*r)->set_last_chunk_appended(last_chunk_appended); + return true; +} + +void ParamTraits >::Log(const param_type& p, + std::string* l) { + l->append(""); +} + +} // namespace IPC diff --git a/libcef/common/cef_messages.h b/libcef/common/cef_messages.h new file mode 100644 index 000000000..b18dbc3a9 --- /dev/null +++ b/libcef/common/cef_messages.h @@ -0,0 +1,221 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// IPC messages for CEF. +// Multiply-included message file, hence no include guard. + +#include "libcef/common/upload_data.h" + +#include "base/memory/shared_memory.h" +#include "base/values.h" +#include "content/public/common/common_param_traits.h" +#include "content/public/common/referrer.h" +#include "ipc/ipc_message_macros.h" + +// TODO(cef): Re-using the message start for extensions may be problematic in +// the future. It would be better if ipc_message_utils.h contained a value +// reserved for consumers of the content API. +// See: http://crbug.com/110911 +#define IPC_MESSAGE_START ExtensionMsgStart + + +// Common types. + +// Parameters structure for a request. +IPC_STRUCT_BEGIN(Cef_Request_Params) + // Unique request id to match requests and responses. + IPC_STRUCT_MEMBER(int, request_id) + + // Unique id of the target frame. -1 if unknown / invalid. + IPC_STRUCT_MEMBER(int64, frame_id) + + // True if the request is user-initiated instead of internal. + IPC_STRUCT_MEMBER(bool, user_initiated) + + // True if a response is expected. + IPC_STRUCT_MEMBER(bool, expect_response) + + // Message name. + IPC_STRUCT_MEMBER(std::string, name) + + // List of message arguments. + IPC_STRUCT_MEMBER(base::ListValue, arguments) +IPC_STRUCT_END() + +// Parameters structure for a response. +IPC_STRUCT_BEGIN(Cef_Response_Params) + // Unique request id to match requests and responses. + IPC_STRUCT_MEMBER(int, request_id) + + // True if a response ack is expected. + IPC_STRUCT_MEMBER(bool, expect_response_ack) + + // True on success. + IPC_STRUCT_MEMBER(bool, success) + + // Response or error string depending on the value of |success|. + IPC_STRUCT_MEMBER(std::string, response) +IPC_STRUCT_END() + +// Parameters structure for a cross-origin white list entry. +IPC_STRUCT_BEGIN(Cef_CrossOriginWhiteListEntry_Params) + IPC_STRUCT_MEMBER(std::string, source_origin) + IPC_STRUCT_MEMBER(std::string, target_protocol) + IPC_STRUCT_MEMBER(std::string, target_domain) + IPC_STRUCT_MEMBER(bool, allow_target_subdomains) +IPC_STRUCT_END() + + +// Messages sent from the browser to the renderer. + +// Parameters for a resource request. +IPC_STRUCT_BEGIN(CefMsg_LoadRequest_Params) + // The request method: GET, POST, etc. + IPC_STRUCT_MEMBER(std::string, method) + + // The requested URL. + IPC_STRUCT_MEMBER(GURL, url) + + // The URL to send in the "Referer" header field. Can be empty if there is + // no referrer. + IPC_STRUCT_MEMBER(GURL, referrer) + // One of the blink::WebReferrerPolicy values. + IPC_STRUCT_MEMBER(int, referrer_policy) + + // Identifies the frame within the RenderView that sent the request. + // -1 if unknown / invalid. + IPC_STRUCT_MEMBER(int64, frame_id) + + // Usually the URL of the document in the top-level window, which may be + // checked by the third-party cookie blocking policy. Leaving it empty may + // lead to undesired cookie blocking. Third-party cookie blocking can be + // bypassed by setting first_party_for_cookies = url, but this should ideally + // only be done if there really is no way to determine the correct value. + IPC_STRUCT_MEMBER(GURL, first_party_for_cookies) + + // Additional HTTP request headers. + IPC_STRUCT_MEMBER(std::string, headers) + + // net::URLRequest load flags (0 by default). + IPC_STRUCT_MEMBER(int, load_flags) + + // Optional upload data (may be null). + IPC_STRUCT_MEMBER(scoped_refptr, upload_data) +IPC_STRUCT_END() + +// Tell the renderer to load a request. +IPC_MESSAGE_ROUTED1(CefMsg_LoadRequest, + CefMsg_LoadRequest_Params) + +// Sent when the browser has a request for the renderer. The renderer may +// respond with a CefHostMsg_Response. +IPC_MESSAGE_ROUTED1(CefMsg_Request, + Cef_Request_Params) + +// Optional message sent in response to a CefHostMsg_Request. +IPC_MESSAGE_ROUTED1(CefMsg_Response, + Cef_Response_Params) + +// Optional Ack message sent to the browser to notify that a CefHostMsg_Response +// has been processed. +IPC_MESSAGE_ROUTED1(CefMsg_ResponseAck, + int /* request_id */) + +// Sent to child processes to add or remove a cross-origin whitelist entry. +IPC_MESSAGE_CONTROL2(CefProcessMsg_ModifyCrossOriginWhitelistEntry, + bool /* add */, + Cef_CrossOriginWhiteListEntry_Params /* params */) + +// Sent to child processes to clear the cross-origin whitelist. +IPC_MESSAGE_CONTROL0(CefProcessMsg_ClearCrossOriginWhitelist) + + +// Messages sent from the renderer to the browser. + +// Parameters for a newly created render thread. +IPC_STRUCT_BEGIN(CefProcessHostMsg_GetNewRenderThreadInfo_Params) + IPC_STRUCT_MEMBER(std::vector, + cross_origin_whitelist_entries) + + IPC_STRUCT_MEMBER(base::ListValue, extra_info) +IPC_STRUCT_END() + +// Retrieve information about a newly created render thread. +IPC_SYNC_MESSAGE_CONTROL0_1( + CefProcessHostMsg_GetNewRenderThreadInfo, + CefProcessHostMsg_GetNewRenderThreadInfo_Params /* params*/) + +// Parameters for a newly created browser window. +IPC_STRUCT_BEGIN(CefProcessHostMsg_GetNewBrowserInfo_Params) + IPC_STRUCT_MEMBER(int, browser_id) + IPC_STRUCT_MEMBER(bool, is_popup) + IPC_STRUCT_MEMBER(bool, is_windowless) +IPC_STRUCT_END() + +// Retrieve information about a newly created browser. +IPC_SYNC_MESSAGE_CONTROL2_1( + CefProcessHostMsg_GetNewBrowserInfo, + int /* render_view_routing_id */, + int /* render_frame_routing_id */, + CefProcessHostMsg_GetNewBrowserInfo_Params /* params*/) + +// Sent when a frame is identified for the first time. +IPC_MESSAGE_ROUTED3(CefHostMsg_FrameIdentified, + int64 /* frame_id */, + int64 /* parent_frame_id */, + base::string16 /* frame_name */) + +// Sent when a frame has finished loading. Based on ViewHostMsg_DidFinishLoad. +IPC_MESSAGE_ROUTED4(CefHostMsg_DidFinishLoad, + int64 /* frame_id */, + GURL /* validated_url */, + bool /* is_main_frame */, + int /* http_status_code */) + +// Sent when a new URL is about to be loaded in the main frame. Used for the +// cookie manager. +IPC_MESSAGE_ROUTED1(CefHostMsg_LoadingURLChange, + GURL /* loading_url */) + +// Sent when the renderer has a request for the browser. The browser may respond +// with a CefMsg_Response. +IPC_MESSAGE_ROUTED1(CefHostMsg_Request, + Cef_Request_Params) + +// Optional message sent in response to a CefMsg_Request. +IPC_MESSAGE_ROUTED1(CefHostMsg_Response, + Cef_Response_Params) + +// Optional Ack message sent to the browser to notify that a CefMsg_Response +// has been processed. +IPC_MESSAGE_ROUTED1(CefHostMsg_ResponseAck, + int /* request_id */) + + +// Singly-included section for struct and custom IPC traits. +#ifndef CEF_LIBCEF_COMMON_CEF_MESSAGES_H_ +#define CEF_LIBCEF_COMMON_CEF_MESSAGES_H_ + +namespace IPC { + +// Extracted from chrome/common/automation_messages.h. +template <> +struct ParamTraits > { + typedef scoped_refptr param_type; + static void Write(Message* m, const param_type& p); + static bool Read(const Message* m, PickleIterator* iter, param_type* r); + static void Log(const param_type& p, std::string* l); +}; + +} // namespace IPC + +#endif // CEF_LIBCEF_COMMON_CEF_MESSAGES_H_ + +#include "chrome/common/print_messages.h" +#include "chrome/common/spellcheck_messages.h" + +#if defined(OS_WIN) +#include "chrome/common/chrome_utility_printing_messages.h" +#endif diff --git a/libcef/common/cef_switches.cc b/libcef/common/cef_switches.cc new file mode 100644 index 000000000..898696537 --- /dev/null +++ b/libcef/common/cef_switches.cc @@ -0,0 +1,97 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/common/cef_switches.h" + +namespace switches { + +// Log file path. +const char kLogFile[] = "log-file"; + +// Severity of messages to log. +const char kLogSeverity[] = "log-severity"; +const char kLogSeverity_Verbose[] = "verbose"; +const char kLogSeverity_Info[] = "info"; +const char kLogSeverity_Warning[] = "warning"; +const char kLogSeverity_Error[] = "error"; +const char kLogSeverity_Disable[] = "disable"; + +// Path to resources directory. +const char kResourcesDirPath[] = "resources-dir-path"; + +// Path to locales directory. +const char kLocalesDirPath[] = "locales-dir-path"; + +// Path to locales directory. +const char kDisablePackLoading[] = "disable-pack-loading"; + +// Stack size for uncaught exceptions. +const char kUncaughtExceptionStackSize[] = "uncaught-exception-stack-size"; + +// Context safety implementation type. +const char kContextSafetyImplementation[] = "context-safety-implementation"; + +// Default encoding. +const char kDefaultEncoding[] = "default-encoding"; + +// Disable opening of windows via JavaScript. +const char kDisableJavascriptOpenWindows[] = + "disable-javascript-open-windows"; + +// Disable closing of windows via JavaScript. +const char kDisableJavascriptCloseWindows[] = + "disable-javascript-close-windows"; + +// Disable clipboard access via JavaScript. +const char kDisableJavascriptAccessClipboard[] = + "disable-javascript-access-clipboard"; + +// Disable DOM paste via JavaScript execCommand("paste"). +const char kDisableJavascriptDomPaste[] = "disable-javascript-dom-paste"; + +// Enable caret browsing. +const char kEnableCaretBrowsing[] = "enable-caret-browsing"; + +// Allow universal access from file URLs. +const char kAllowUniversalAccessFromFileUrls[] = + "allow-universal-access-from-files"; + +// Disable loading of images from the network. A cached image will still be +// rendered if requested. +const char kDisableImageLoading[] = "disable-image-loading"; + +// Shrink stand-alone images to fit. +const char kImageShrinkStandaloneToFit[] = "image-shrink-standalone-to-fit"; + +// Disable resizing of text areas. +const char kDisableTextAreaResize[] = "disable-text-area-resize"; + +// Disable using the tab key to advance focus to links. +const char kDisableTabToLinks[] = "disable-tab-to-links"; + +// Persist session cookies. +const char kPersistSessionCookies[] = "persist-session-cookies"; + +// Enable media (WebRTC audio/video) streaming. +const char kEnableMediaStream[] = "enable-media-stream"; + +// Enable speech input (x-webkit-speech). +const char kEnableSpeechInput[] = "enable-speech-input"; + +// Enable the speech input profanity filter. +const char kEnableProfanityFilter[] = "enable-profanity-filter"; + +// The directory breakpad should store minidumps in. +const char kCrashDumpsDir[] = "crash-dumps-dir"; + +// Disable spell checking. +const char kDisableSpellChecking[] = "disable-spell-checking"; + +// Enable the remote spelling service. +const char kEnableSpellingService[] = "enable-spelling-service"; + +// Override the default spellchecking language which comes from locales.pak. +const char kOverrideSpellCheckLang[] = "override-spell-check-lang"; + +} // namespace switches diff --git a/libcef/common/cef_switches.h b/libcef/common/cef_switches.h new file mode 100644 index 000000000..ddd96bde3 --- /dev/null +++ b/libcef/common/cef_switches.h @@ -0,0 +1,47 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +// Defines all the "cef" command-line switches. + +#ifndef CEF_LIBCEF_COMMON_CEF_SWITCHES_H_ +#define CEF_LIBCEF_COMMON_CEF_SWITCHES_H_ +#pragma once + +namespace switches { + +extern const char kLogFile[]; +extern const char kLogSeverity[]; +extern const char kLogSeverity_Verbose[]; +extern const char kLogSeverity_Info[]; +extern const char kLogSeverity_Warning[]; +extern const char kLogSeverity_Error[]; +extern const char kLogSeverity_Disable[]; +extern const char kResourcesDirPath[]; +extern const char kLocalesDirPath[]; +extern const char kDisablePackLoading[]; +extern const char kUncaughtExceptionStackSize[]; +extern const char kContextSafetyImplementation[]; +extern const char kDefaultEncoding[]; +extern const char kDisableJavascriptOpenWindows[]; +extern const char kDisableJavascriptCloseWindows[]; +extern const char kDisableJavascriptAccessClipboard[]; +extern const char kDisableJavascriptDomPaste[]; +extern const char kEnableCaretBrowsing[]; +extern const char kAllowUniversalAccessFromFileUrls[]; +extern const char kDisableImageLoading[]; +extern const char kImageShrinkStandaloneToFit[]; +extern const char kDisableTextAreaResize[]; +extern const char kDisableTabToLinks[]; +extern const char kPersistSessionCookies[]; +extern const char kEnableMediaStream[]; +extern const char kEnableSpeechInput[]; +extern const char kEnableProfanityFilter[]; +extern const char kCrashDumpsDir[]; +extern const char kDisableSpellChecking[]; +extern const char kEnableSpellingService[]; +extern const char kOverrideSpellCheckLang[]; + +} // namespace switches + +#endif // CEF_LIBCEF_COMMON_CEF_SWITCHES_H_ diff --git a/libcef/common/command_line_impl.cc b/libcef/common/command_line_impl.cc new file mode 100644 index 000000000..5444f7334 --- /dev/null +++ b/libcef/common/command_line_impl.cc @@ -0,0 +1,159 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/command_line_impl.h" + +#include "base/files/file_path.h" +#include "base/logging.h" + +CefCommandLineImpl::CefCommandLineImpl(base::CommandLine* value, + bool will_delete, + bool read_only) + : CefValueBase( + value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete, + read_only, NULL) { +} + +bool CefCommandLineImpl::IsValid() { + return !detached(); +} + +bool CefCommandLineImpl::IsReadOnly() { + return read_only(); +} + +CefRefPtr CefCommandLineImpl::Copy() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + return new CefCommandLineImpl( + new base::CommandLine(const_value().argv()), true, false); +} + +void CefCommandLineImpl::InitFromArgv(int argc, const char* const* argv) { +#if !defined(OS_WIN) + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->InitFromArgv(argc, argv); +#else + NOTREACHED() << "method not supported on this platform"; +#endif +} + +void CefCommandLineImpl::InitFromString(const CefString& command_line) { +#if defined(OS_WIN) + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->ParseFromString(command_line); +#else + NOTREACHED() << "method not supported on this platform"; +#endif +} + +void CefCommandLineImpl::Reset() { + CEF_VALUE_VERIFY_RETURN_VOID(true); + base::CommandLine::StringVector argv; + argv.push_back(mutable_value()->GetProgram().value()); + mutable_value()->InitFromArgv(argv); + + const base::CommandLine::SwitchMap& map = mutable_value()->GetSwitches(); + const_cast(&map)->clear(); +} + +void CefCommandLineImpl::GetArgv(std::vector& argv) { + CEF_VALUE_VERIFY_RETURN_VOID(false); + const base::CommandLine::StringVector& cmd_argv = const_value().argv(); + base::CommandLine::StringVector::const_iterator it = cmd_argv.begin(); + for (; it != cmd_argv.end(); ++it) + argv.push_back(*it); +} + +CefString CefCommandLineImpl::GetCommandLineString() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetCommandLineString(); +} + +CefString CefCommandLineImpl::GetProgram() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetProgram().value(); +} + +void CefCommandLineImpl::SetProgram(const CefString& program) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->SetProgram(base::FilePath(program)); +} + +bool CefCommandLineImpl::HasSwitches() { + CEF_VALUE_VERIFY_RETURN(false, false); + return (const_value().GetSwitches().size() > 0); +} + +bool CefCommandLineImpl::HasSwitch(const CefString& name) { + CEF_VALUE_VERIFY_RETURN(false, false); + return const_value().HasSwitch(name); +} + +CefString CefCommandLineImpl::GetSwitchValue(const CefString& name) { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().GetSwitchValueNative(name); +} + +void CefCommandLineImpl::GetSwitches(SwitchMap& switches) { + CEF_VALUE_VERIFY_RETURN_VOID(false); + const base::CommandLine::SwitchMap& map = const_value().GetSwitches(); + base::CommandLine::SwitchMap::const_iterator it = map.begin(); + for (; it != map.end(); ++it) + switches.insert(std::make_pair(it->first, it->second)); +} + +void CefCommandLineImpl::AppendSwitch(const CefString& name) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->AppendSwitch(name); +} + +void CefCommandLineImpl::AppendSwitchWithValue(const CefString& name, + const CefString& value) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->AppendSwitchNative(name, value); +} + +bool CefCommandLineImpl::HasArguments() { + CEF_VALUE_VERIFY_RETURN(false, false); + return (const_value().GetArgs().size() > 0); +} + +void CefCommandLineImpl::GetArguments(ArgumentList& arguments) { + CEF_VALUE_VERIFY_RETURN_VOID(false); + const base::CommandLine::StringVector& vec = const_value().GetArgs(); + base::CommandLine::StringVector::const_iterator it = vec.begin(); + for (; it != vec.end(); ++it) + arguments.push_back(*it); +} + +void CefCommandLineImpl::AppendArgument(const CefString& argument) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->AppendArgNative(argument); +} + +void CefCommandLineImpl::PrependWrapper(const CefString& wrapper) { + CEF_VALUE_VERIFY_RETURN_VOID(true); + mutable_value()->PrependWrapper(wrapper); +} + + +// CefCommandLine implementation. + +// static +CefRefPtr CefCommandLine::CreateCommandLine() { + return new CefCommandLineImpl( + new base::CommandLine(base::CommandLine::NO_PROGRAM), true, false); +} + +// static +CefRefPtr CefCommandLine::GetGlobalCommandLine() { + // Uses a singleton reference object. + static CefRefPtr commandLinePtr; + if (!commandLinePtr.get()) { + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line) + commandLinePtr = new CefCommandLineImpl(command_line, false, true); + } + return commandLinePtr.get(); +} diff --git a/libcef/common/command_line_impl.h b/libcef/common/command_line_impl.h new file mode 100644 index 000000000..b07e7f646 --- /dev/null +++ b/libcef/common/command_line_impl.h @@ -0,0 +1,51 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_COMMAND_LINE_IMPL_H_ +#define CEF_LIBCEF_COMMON_COMMAND_LINE_IMPL_H_ +#pragma once + +#include "include/cef_command_line.h" +#include "libcef/common/value_base.h" + +#include "base/command_line.h" + +// CefCommandLine implementation +class CefCommandLineImpl : + public CefValueBase { + public: + CefCommandLineImpl(base::CommandLine* value, + bool will_delete, + bool read_only); + + // CefCommandLine methods. + bool IsValid() override; + bool IsReadOnly() override; + CefRefPtr Copy() override; + void InitFromArgv(int argc, const char* const* argv) override; + void InitFromString(const CefString& command_line) override; + void Reset() override; + void GetArgv(std::vector& argv) override; + CefString GetCommandLineString() override; + CefString GetProgram() override; + void SetProgram(const CefString& program) override; + bool HasSwitches() override; + bool HasSwitch(const CefString& name) override; + CefString GetSwitchValue(const CefString& name) override; + void GetSwitches(SwitchMap& switches) override; + void AppendSwitch(const CefString& name) override; + void AppendSwitchWithValue(const CefString& name, + const CefString& value) override; + bool HasArguments() override; + void GetArguments(ArgumentList& arguments) override; + void AppendArgument(const CefString& argument) override; + void PrependWrapper(const CefString& wrapper) override; + + // Must hold the controller lock while using this value. + const base::CommandLine& command_line() { return const_value(); } + + DISALLOW_COPY_AND_ASSIGN(CefCommandLineImpl); +}; + +#endif // CEF_LIBCEF_COMMON_COMMAND_LINE_IMPL_H_ diff --git a/libcef/common/content_client.cc b/libcef/common/content_client.cc new file mode 100644 index 000000000..63e974d71 --- /dev/null +++ b/libcef/common/content_client.cc @@ -0,0 +1,260 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/common/content_client.h" +#include "include/cef_stream.h" +#include "include/cef_version.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/common/scheme_registrar_impl.h" +#include "libcef/common/scheme_registration.h" + +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/strings/string_piece.h" +#include "base/strings/stringprintf.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/pepper_plugin_info.h" +#include "content/public/common/user_agent.h" +#include "ppapi/shared_impl/ppapi_permissions.h" +#include "ui/base/resource/resource_bundle.h" + +namespace { + +CefContentClient* g_content_client = NULL; + +const char kPDFPluginName[] = "Chrome PDF Viewer"; +const char kPDFPluginMimeType[] = "application/pdf"; +const char kPDFPluginExtension[] = "pdf"; +const char kPDFPluginDescription[] = "Portable Document Format"; +const uint32 kPDFPluginPermissions = ppapi::PERMISSION_PRIVATE | + ppapi::PERMISSION_DEV; + +// Appends the known built-in plugins to the given vector. +// Based on chrome/common/chrome_content_client.cc. +void ComputeBuiltInPlugins(std::vector* plugins) { + // PDF. + // + // Once we're sandboxed, we can't know if the PDF plugin is available or not; + // but (on Linux) this function is always called once before we're sandboxed. + // So the first time through test if the file is available and then skip the + // check on subsequent calls if yes. + static bool skip_pdf_file_check = false; + base::FilePath path; + if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) { + if (skip_pdf_file_check || base::PathExists(path)) { + content::PepperPluginInfo pdf; + pdf.path = path; + pdf.name = kPDFPluginName; + // Only in-process loading is currently supported. See issue #1331. + pdf.is_out_of_process = false; + content::WebPluginMimeType pdf_mime_type(kPDFPluginMimeType, + kPDFPluginExtension, + kPDFPluginDescription); + pdf.mime_types.push_back(pdf_mime_type); + pdf.permissions = kPDFPluginPermissions; + plugins->push_back(pdf); + + skip_pdf_file_check = true; + } + } +} + +} // namespace + +CefContentClient::CefContentClient(CefRefPtr application) + : application_(application), + pack_loading_disabled_(false), + allow_pack_file_load_(false), + scheme_info_list_locked_(false) { + DCHECK(!g_content_client); + g_content_client = this; +} + +CefContentClient::~CefContentClient() { + g_content_client = NULL; +} + +// static +CefContentClient* CefContentClient::Get() { + return g_content_client; +} + +void CefContentClient::AddPepperPlugins( + std::vector* plugins) { + ComputeBuiltInPlugins(plugins); +} + +void CefContentClient::AddAdditionalSchemes( + std::vector* standard_schemes, + std::vector* savable_schemes) { + DCHECK(!scheme_info_list_locked_); + + if (application_.get()) { + CefRefPtr schemeRegistrar( + new CefSchemeRegistrarImpl()); + application_->OnRegisterCustomSchemes(schemeRegistrar.get()); + schemeRegistrar->GetStandardSchemes(standard_schemes); + + // No references to the registar should be kept. + schemeRegistrar->Detach(); + DCHECK(schemeRegistrar->VerifyRefCount()); + } + + scheme::AddInternalSchemes(standard_schemes); + + scheme_info_list_locked_ = true; +} + +std::string CefContentClient::GetUserAgent() const { + std::string product_version; + + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kUserAgent)) + return command_line->GetSwitchValueASCII(switches::kUserAgent); + + if (command_line->HasSwitch(switches::kProductVersion)) { + product_version = + command_line->GetSwitchValueASCII(switches::kProductVersion); + } else { + product_version = base::StringPrintf("Chrome/%d.%d.%d.%d", + CHROME_VERSION_MAJOR, CHROME_VERSION_MINOR, CHROME_VERSION_BUILD, + CHROME_VERSION_PATCH); + } + + return content::BuildUserAgentFromProduct(product_version); +} + +base::string16 CefContentClient::GetLocalizedString(int message_id) const { + base::string16 value = + ResourceBundle::GetSharedInstance().GetLocalizedString(message_id); + if (value.empty()) + LOG(ERROR) << "No localized string available for id " << message_id; + + return value; +} + +base::StringPiece CefContentClient::GetDataResource( + int resource_id, + ui::ScaleFactor scale_factor) const { + base::StringPiece value = + ResourceBundle::GetSharedInstance().GetRawDataResourceForScale( + resource_id, scale_factor); + if (value.empty()) + LOG(ERROR) << "No data resource available for id " << resource_id; + + return value; +} + +gfx::Image& CefContentClient::GetNativeImageNamed(int resource_id) const { + gfx::Image& value = + ResourceBundle::GetSharedInstance().GetNativeImageNamed(resource_id); + if (value.IsEmpty()) + LOG(ERROR) << "No native image available for id " << resource_id; + + return value; +} + +void CefContentClient::AddCustomScheme(const SchemeInfo& scheme_info) { + DCHECK(!scheme_info_list_locked_); + scheme_info_list_.push_back(scheme_info); + + if (CefContentBrowserClient::Get()) { + CefContentBrowserClient::Get()->RegisterCustomScheme( + scheme_info.scheme_name); + } +} + +const CefContentClient::SchemeInfoList* CefContentClient::GetCustomSchemes() { + DCHECK(scheme_info_list_locked_); + return &scheme_info_list_; +} + +bool CefContentClient::HasCustomScheme(const std::string& scheme_name) { + DCHECK(scheme_info_list_locked_); + if (scheme_info_list_.empty()) + return false; + + SchemeInfoList::const_iterator it = scheme_info_list_.begin(); + for (; it != scheme_info_list_.end(); ++it) { + if (it->scheme_name == scheme_name) + return true; + } + + return false; +} + +base::FilePath CefContentClient::GetPathForResourcePack( + const base::FilePath& pack_path, + ui::ScaleFactor scale_factor) { + // Only allow the cef pack file to load. + if (!pack_loading_disabled_ && allow_pack_file_load_) + return pack_path; + return base::FilePath(); +} + +base::FilePath CefContentClient::GetPathForLocalePack( + const base::FilePath& pack_path, + const std::string& locale) { + if (!pack_loading_disabled_) + return pack_path; + return base::FilePath(); +} + +gfx::Image CefContentClient::GetImageNamed(int resource_id) { + return gfx::Image(); +} + +gfx::Image CefContentClient::GetNativeImageNamed( + int resource_id, + ui::ResourceBundle::ImageRTL rtl) { + return gfx::Image(); +} + +base::RefCountedStaticMemory* CefContentClient::LoadDataResourceBytes( + int resource_id, + ui::ScaleFactor scale_factor) { + return NULL; +} + +bool CefContentClient::GetRawDataResource(int resource_id, + ui::ScaleFactor scale_factor, + base::StringPiece* value) { + if (application_.get()) { + CefRefPtr handler = + application_->GetResourceBundleHandler(); + if (handler.get()) { + void* data = NULL; + size_t data_size = 0; + if (handler->GetDataResource(resource_id, data, data_size)) + *value = base::StringPiece(static_cast(data), data_size); + } + } + + return (pack_loading_disabled_ || !value->empty()); +} + +bool CefContentClient::GetLocalizedString(int message_id, + base::string16* value) { + if (application_.get()) { + CefRefPtr handler = + application_->GetResourceBundleHandler(); + if (handler.get()) { + CefString cef_str; + if (handler->GetLocalizedString(message_id, cef_str)) + *value = cef_str; + } + } + + return (pack_loading_disabled_ || !value->empty()); +} + +scoped_ptr CefContentClient::GetFont( + ui::ResourceBundle::FontStyle style) { + return scoped_ptr(); +} diff --git a/libcef/common/content_client.h b/libcef/common/content_client.h new file mode 100644 index 000000000..3ff4cc22d --- /dev/null +++ b/libcef/common/content_client.h @@ -0,0 +1,92 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_CONTENT_CLIENT_H_ +#define CEF_LIBCEF_COMMON_CONTENT_CLIENT_H_ +#pragma once + +#include +#include +#include + +#include "include/cef_app.h" + +#include "base/compiler_specific.h" +#include "content/public/common/content_client.h" +#include "ui/base/resource/resource_bundle.h" + +class CefContentClient : public content::ContentClient, + public ui::ResourceBundle::Delegate { + public: + explicit CefContentClient(CefRefPtr application); + ~CefContentClient() override; + + // Returns the singleton CefContentClient instance. + static CefContentClient* Get(); + + // content::ContentClient methods. + void AddPepperPlugins( + std::vector* plugins) override; + void AddAdditionalSchemes( + std::vector* standard_schemes, + std::vector* savable_schemes) override; + std::string GetUserAgent() const override; + base::string16 GetLocalizedString(int message_id) const override; + base::StringPiece GetDataResource( + int resource_id, + ui::ScaleFactor scale_factor) const override; + gfx::Image& GetNativeImageNamed(int resource_id) const override; + + struct SchemeInfo { + std::string scheme_name; + bool is_standard; + bool is_local; + bool is_display_isolated; + }; + typedef std::list SchemeInfoList; + + // Custom scheme registration. + void AddCustomScheme(const SchemeInfo& scheme_info); + const SchemeInfoList* GetCustomSchemes(); + bool HasCustomScheme(const std::string& scheme_name); + + CefRefPtr application() const { return application_; } + + void set_pack_loading_disabled(bool val) { pack_loading_disabled_ = val; } + bool pack_loading_disabled() const { return pack_loading_disabled_; } + void set_allow_pack_file_load(bool val) { allow_pack_file_load_ = val; } + + private: + // ui::ResourceBundle::Delegate methods. + base::FilePath GetPathForResourcePack( + const base::FilePath& pack_path, + ui::ScaleFactor scale_factor) override; + base::FilePath GetPathForLocalePack( + const base::FilePath& pack_path, + const std::string& locale) override; + gfx::Image GetImageNamed(int resource_id) override; + gfx::Image GetNativeImageNamed( + int resource_id, + ui::ResourceBundle::ImageRTL rtl) override; + base::RefCountedStaticMemory* LoadDataResourceBytes( + int resource_id, + ui::ScaleFactor scale_factor) override; + bool GetRawDataResource(int resource_id, + ui::ScaleFactor scale_factor, + base::StringPiece* value) override; + bool GetLocalizedString(int message_id, + base::string16* value) override; + scoped_ptr GetFont( + ui::ResourceBundle::FontStyle style) override; + + CefRefPtr application_; + bool pack_loading_disabled_; + bool allow_pack_file_load_; + + // Custom schemes handled by the client. + SchemeInfoList scheme_info_list_; + bool scheme_info_list_locked_; +}; + +#endif // CEF_LIBCEF_COMMON_CONTENT_CLIENT_H_ diff --git a/libcef/common/crash_reporter_client.cc b/libcef/common/crash_reporter_client.cc new file mode 100644 index 000000000..48a53f728 --- /dev/null +++ b/libcef/common/crash_reporter_client.cc @@ -0,0 +1,64 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/common/crash_reporter_client.h" +#include "libcef/common/cef_switches.h" +#include "include/cef_version.h" + +#include "base/command_line.h" +#include "base/logging.h" +#include "base/files/file_path.h" +#include "base/strings/string16.h" +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" + +CefCrashReporterClient::CefCrashReporterClient() {} +CefCrashReporterClient::~CefCrashReporterClient() {} + +#if defined(OS_WIN) +void CefCrashReporterClient::GetProductNameAndVersion( + const base::FilePath& exe_path, + base::string16* product_name, + base::string16* version, + base::string16* special_build, + base::string16* channel_name) { + *product_name = base::ASCIIToUTF16("cef"); + *version = base::UTF8ToUTF16(base::StringPrintf( + "%d.%d.%d", CEF_VERSION_MAJOR, CHROME_VERSION_BUILD, CEF_REVISION)); + *special_build = base::string16(); + *channel_name = base::string16(); +} +#endif + +#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS) +#define PRODUCT_VERSION \ + MAKE_STRING(CEF_VERSION_MAJOR) "." \ + MAKE_STRING(CHROME_VERSION_BUILD) "." \ + MAKE_STRING(CEF_REVISION) + +void CefCrashReporterClient::GetProductNameAndVersion( + const char** product_name, + const char** version) { + *product_name = "cef"; + *version = PRODUCT_VERSION; +} + +base::FilePath CefCrashReporterClient::GetReporterLogFilename() { + return base::FilePath(FILE_PATH_LITERAL("uploads.log")); +} +#endif + +bool CefCrashReporterClient::GetCrashDumpLocation(base::FilePath* crash_dir) { +#if !defined(OS_WIN) + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (!command_line->HasSwitch(switches::kCrashDumpsDir)) + return false; + *crash_dir = command_line->GetSwitchValuePath(switches::kCrashDumpsDir); + return true; +#else + NOTREACHED(); + return false; +#endif +} diff --git a/libcef/common/crash_reporter_client.h b/libcef/common/crash_reporter_client.h new file mode 100644 index 000000000..0ed6d4077 --- /dev/null +++ b/libcef/common/crash_reporter_client.h @@ -0,0 +1,43 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_CRASH_REPORTER_CLIENT_H_ +#define CEF_LIBCEF_COMMON_CRASH_REPORTER_CLIENT_H_ + +#include "base/compiler_specific.h" +#include "components/crash/app/crash_reporter_client.h" + +class CefCrashReporterClient : public crash_reporter::CrashReporterClient { + public: + CefCrashReporterClient(); + ~CefCrashReporterClient() override; + +#if defined(OS_WIN) + // Returns a textual description of the product type and version to include + // in the crash report. + void GetProductNameAndVersion(const base::FilePath& exe_path, + base::string16* product_name, + base::string16* version, + base::string16* special_build, + base::string16* channel_name) override; +#endif + +#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_IOS) + // Returns a textual description of the product type and version to include + // in the crash report. + void GetProductNameAndVersion(const char** product_name, + const char** version) override; + + base::FilePath GetReporterLogFilename() override; +#endif + + // The location where minidump files should be written. Returns true if + // |crash_dir| was set. + bool GetCrashDumpLocation(base::FilePath* crash_dir) override; + +private: + DISALLOW_COPY_AND_ASSIGN(CefCrashReporterClient); +}; + +#endif // CEF_LIBCEF_COMMON_CRASH_REPORTER_CLIENT_H_ diff --git a/libcef/common/drag_data_impl.cc b/libcef/common/drag_data_impl.cc new file mode 100644 index 000000000..f5c42dfa5 --- /dev/null +++ b/libcef/common/drag_data_impl.cc @@ -0,0 +1,194 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +#include "libcef/browser/stream_impl.h" +#include "libcef/common/drag_data_impl.h" +#include "base/files/file_path.h" +#include "net/base/filename_util.h" +#include "net/base/net_util.h" + +#define CHECK_READONLY_RETURN_VOID() \ + if (read_only_) { \ + NOTREACHED() << "object is read only"; \ + return; \ + } + +CefDragDataImpl::CefDragDataImpl(const content::DropData& data) + : data_(data), + read_only_(false) { +} + +CefDragDataImpl::CefDragDataImpl() + : read_only_(false) { +} + +CefRefPtr CefDragData::Create() { + return new CefDragDataImpl(); +} + +CefRefPtr CefDragDataImpl::Clone() { + CefDragDataImpl* drag_data = NULL; + { + base::AutoLock lock_scope(lock_); + drag_data = new CefDragDataImpl(data_); + } + return drag_data; +} + +bool CefDragDataImpl::IsReadOnly() { + base::AutoLock lock_scope(lock_); + return read_only_; +} + +bool CefDragDataImpl::IsLink() { + base::AutoLock lock_scope(lock_); + return (data_.url.is_valid() && data_.file_description_filename.empty()); +} + +bool CefDragDataImpl::IsFragment() { + base::AutoLock lock_scope(lock_); + return (!data_.url.is_valid() && data_.file_description_filename.empty() && + data_.filenames.empty()); +} + +bool CefDragDataImpl::IsFile() { + base::AutoLock lock_scope(lock_); + return (!data_.file_description_filename.empty() || !data_.filenames.empty()); +} + +CefString CefDragDataImpl::GetLinkURL() { + base::AutoLock lock_scope(lock_); + return data_.url.spec(); +} + +CefString CefDragDataImpl::GetLinkTitle() { + base::AutoLock lock_scope(lock_); + return data_.url_title; +} + +CefString CefDragDataImpl::GetLinkMetadata() { + base::AutoLock lock_scope(lock_); + return data_.download_metadata; +} + +CefString CefDragDataImpl::GetFragmentText() { + base::AutoLock lock_scope(lock_); + return data_.text.is_null() ? CefString() : CefString(data_.text.string()); +} + +CefString CefDragDataImpl::GetFragmentHtml() { + base::AutoLock lock_scope(lock_); + return data_.html.is_null() ? CefString() : CefString(data_.html.string()); +} + +CefString CefDragDataImpl::GetFragmentBaseURL() { + base::AutoLock lock_scope(lock_); + return data_.html_base_url.spec(); +} + +CefString CefDragDataImpl::GetFileName() { + base::AutoLock lock_scope(lock_); + if (data_.file_description_filename.empty()) + return CefString(); + + base::FilePath file_name(CefString(data_.file_description_filename)); + // Images without ALT text will only have a file extension so we need to + // synthesize one from the provided extension and URL. + if (file_name.BaseName().RemoveExtension().empty()) { + CefString extension = file_name.Extension(); + // Retrieve the name from the URL. + CefString suggested_file_name = + net::GetSuggestedFilename(data_.url, "", "", "", "", ""); + file_name = base::FilePath(suggested_file_name).ReplaceExtension(extension); + } + return file_name.value(); +} + +size_t CefDragDataImpl::GetFileContents(CefRefPtr writer) { + base::AutoLock lock_scope(lock_); + if (data_.file_contents.empty()) + return 0; + + char* data = const_cast(data_.file_contents.c_str()); + size_t size = data_.file_contents.size(); + + if (!writer.get()) + return size; + + return writer->Write(data, 1, size); +} + +bool CefDragDataImpl::GetFileNames(std::vector& names) { + base::AutoLock lock_scope(lock_); + if (data_.filenames.empty()) + return false; + + std::vector::const_iterator it = + data_.filenames.begin(); + for (; it != data_.filenames.end(); ++it) + names.push_back(it->path.value()); + + return true; +} + +void CefDragDataImpl::SetLinkURL(const CefString& url) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.url = GURL(url.ToString()); +} + +void CefDragDataImpl::SetLinkTitle(const CefString& title) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.url_title = title.ToString16(); +} + +void CefDragDataImpl::SetLinkMetadata(const CefString& data) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.download_metadata = data.ToString16(); +} + +void CefDragDataImpl::SetFragmentText(const CefString& text) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.text = base::NullableString16(text.ToString16(), false); +} + +void CefDragDataImpl::SetFragmentHtml(const CefString& fragment) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.html = base::NullableString16(fragment.ToString16(), false); +} + +void CefDragDataImpl::SetFragmentBaseURL(const CefString& fragment) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.html_base_url = GURL(fragment.ToString()); +} + +void CefDragDataImpl::ResetFileContents() { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.file_contents.erase(); + data_.file_description_filename.erase(); +} + +void CefDragDataImpl::AddFile(const CefString& path, + const CefString& display_name) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + data_.filenames.push_back(ui::FileInfo(base::FilePath(path), + base::FilePath(display_name))); +} + +void CefDragDataImpl::SetReadOnly(bool read_only) { + base::AutoLock lock_scope(lock_); + if (read_only_ == read_only) + return; + + read_only_ = read_only; +} diff --git a/libcef/common/drag_data_impl.h b/libcef/common/drag_data_impl.h new file mode 100644 index 000000000..1c1533c0b --- /dev/null +++ b/libcef/common/drag_data_impl.h @@ -0,0 +1,65 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_ +#define CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_ +#pragma once + +#include "include/cef_drag_data.h" + +#include + +#include "base/synchronization/lock.h" +#include "content/public/common/drop_data.h" + +// Implementation of CefDragData. +class CefDragDataImpl : public CefDragData { + public: + CefDragDataImpl(); + explicit CefDragDataImpl(const content::DropData& data); + + CefRefPtr Clone() override; + bool IsReadOnly() override; + bool IsLink() override; + bool IsFragment() override; + bool IsFile() override; + CefString GetLinkURL() override; + CefString GetLinkTitle() override; + CefString GetLinkMetadata() override; + CefString GetFragmentText() override; + CefString GetFragmentHtml() override; + CefString GetFragmentBaseURL() override; + CefString GetFileName() override; + size_t GetFileContents(CefRefPtr writer) override; + bool GetFileNames(std::vector& names) override; + void SetLinkURL(const CefString& url) override; + void SetLinkTitle(const CefString& title) override; + void SetLinkMetadata(const CefString& data) override; + void SetFragmentText(const CefString& text) override; + void SetFragmentHtml(const CefString& fragment) override; + void SetFragmentBaseURL(const CefString& fragment) override; + void ResetFileContents() override; + void AddFile(const CefString& path, const CefString& display_name) override; + + // This method is not safe. Use Lock/Unlock to get mutually exclusive access. + const content::DropData& drop_data() { + return data_; + } + + void SetReadOnly(bool read_only); + + base::Lock& lock() { return lock_; } + + private: + content::DropData data_; + + // True if this object is read-only. + bool read_only_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefDragDataImpl); +}; + +#endif // CEF_LIBCEF_COMMON_DRAG_DATA_IMPL_H_ diff --git a/libcef/common/http_header_utils.cc b/libcef/common/http_header_utils.cc new file mode 100644 index 000000000..249833bc5 --- /dev/null +++ b/libcef/common/http_header_utils.cc @@ -0,0 +1,43 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/http_header_utils.h" +#include "net/http/http_response_headers.h" +#include "net/http/http_util.h" + +using net::HttpResponseHeaders; + +namespace HttpHeaderUtils { + +std::string GenerateHeaders(const HeaderMap& map) { + std::string headers; + + for (HeaderMap::const_iterator header = map.begin(); + header != map.end(); + ++header) { + const CefString& key = header->first; + const CefString& value = header->second; + + if (!key.empty()) { + // Delimit with "\r\n". + if (!headers.empty()) + headers += "\r\n"; + + headers += std::string(key) + ": " + std::string(value); + } + } + + return headers; +} + +void ParseHeaders(const std::string& header_str, HeaderMap& map) { + // Parse the request header values + for (net::HttpUtil::HeadersIterator i(header_str.begin(), + header_str.end(), "\n"); + i.GetNext(); ) { + map.insert(std::make_pair(i.name(), i.values())); + } +} + +} // namespace HttpHeaderUtils diff --git a/libcef/common/http_header_utils.h b/libcef/common/http_header_utils.h new file mode 100644 index 000000000..579b4a9cf --- /dev/null +++ b/libcef/common/http_header_utils.h @@ -0,0 +1,22 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_HTTP_HEADER_UTILS_H_ +#define CEF_LIBCEF_COMMON_HTTP_HEADER_UTILS_H_ +#pragma once + +#include + +#include "include/cef_request.h" + +namespace HttpHeaderUtils { + +typedef CefRequest::HeaderMap HeaderMap; + +std::string GenerateHeaders(const HeaderMap& map); +void ParseHeaders(const std::string& header_str, HeaderMap& map); + +}; // namespace HttpHeaderUtils + +#endif // CEF_LIBCEF_COMMON_HTTP_HEADER_UTILS_H_ diff --git a/libcef/common/main_delegate.cc b/libcef/common/main_delegate.cc new file mode 100644 index 000000000..dcc651659 --- /dev/null +++ b/libcef/common/main_delegate.cc @@ -0,0 +1,611 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/common/main_delegate.h" +#include "libcef/browser/content_browser_client.h" +#include "libcef/browser/context.h" +#include "libcef/common/cef_switches.h" +#include "libcef/common/command_line_impl.h" +#include "libcef/common/crash_reporter_client.h" +#include "libcef/renderer/content_renderer_client.h" +#include "libcef/utility/content_utility_client.h" + +#include "base/base_switches.h" +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/lazy_instance.h" +#include "base/path_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/thread.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_switches.h" +#include "content/public/browser/browser_main_runner.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/common/content_switches.h" +#include "content/public/common/main_function_params.h" +#include "ui/base/layout.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/base/ui_base_paths.h" +#include "ui/base/ui_base_switches.h" + +#if defined(OS_WIN) +#include // NOLINT(build/include_order) +#include "components/crash/app/breakpad_win.h" +#endif + +#if defined(OS_MACOSX) +#include "base/mac/os_crash_dumps.h" +#include "base/mac/bundle_locations.h" +#include "base/mac/foundation_util.h" +#include "components/crash/app/breakpad_mac.h" +#include "content/public/common/content_paths.h" +#endif + +#if defined(OS_POSIX) && !defined(OS_MACOSX) +#include "components/crash/app/breakpad_linux.h" +#endif + +namespace { + +base::LazyInstance::Leaky g_crash_reporter_client = + LAZY_INSTANCE_INITIALIZER; + +#if defined(OS_MACOSX) + +base::FilePath GetFrameworksPath() { + // Start out with the path to the running executable. + base::FilePath execPath; + PathService::Get(base::FILE_EXE, &execPath); + + // Get the main bundle path. + base::FilePath bundlePath = base::mac::GetAppBundlePath(execPath); + + // Go into the Contents/Frameworks directory. + return bundlePath.Append(FILE_PATH_LITERAL("Contents")) + .Append(FILE_PATH_LITERAL("Frameworks")); +} + +// The framework bundle path is used for loading resources, libraries, etc. +base::FilePath GetFrameworkBundlePath() { + return GetFrameworksPath().Append( + FILE_PATH_LITERAL("Chromium Embedded Framework.framework")); +} + +base::FilePath GetResourcesFilePath() { + return GetFrameworkBundlePath().Append(FILE_PATH_LITERAL("Resources")); +} + +base::FilePath GetLibrariesFilePath() { + return GetFrameworkBundlePath().Append(FILE_PATH_LITERAL("Libraries")); +} + +void OverrideFrameworkBundlePath() { + base::mac::SetOverrideFrameworkBundlePath(GetFrameworkBundlePath()); +} + +void OverrideChildProcessPath() { + // Retrieve the name of the running executable. + base::FilePath path; + PathService::Get(base::FILE_EXE, &path); + + std::string name = path.BaseName().value(); + + base::FilePath helper_path = GetFrameworksPath() + .Append(FILE_PATH_LITERAL(name+" Helper.app")) + .Append(FILE_PATH_LITERAL("Contents")) + .Append(FILE_PATH_LITERAL("MacOS")) + .Append(FILE_PATH_LITERAL(name+" Helper")); + + PathService::Override(content::CHILD_PROCESS_EXE, helper_path); +} + +#else // !defined(OS_MACOSX) + +base::FilePath GetResourcesFilePath() { + base::FilePath pak_dir; + PathService::Get(base::DIR_MODULE, &pak_dir); + return pak_dir; +} + +base::FilePath GetLibrariesFilePath() { + return GetResourcesFilePath(); +} + +#endif // !defined(OS_MACOSX) + +// File name of the internal PDF plugin on different platforms. +const base::FilePath::CharType kInternalPDFPluginFileName[] = +#if defined(OS_WIN) + FILE_PATH_LITERAL("pdf.dll"); +#elif defined(OS_MACOSX) + FILE_PATH_LITERAL("PDF.plugin"); +#else // Linux and Chrome OS + FILE_PATH_LITERAL("libpdf.so"); +#endif + +void OverridePdfPluginPath() { + base::FilePath plugin_path = GetLibrariesFilePath(); + plugin_path = plugin_path.Append(kInternalPDFPluginFileName); + PathService::Override(chrome::FILE_PDF_PLUGIN, plugin_path); +} + +// Returns true if |scale_factor| is supported by this platform. +// Same as ResourceBundle::IsScaleFactorSupported. +bool IsScaleFactorSupported(ui::ScaleFactor scale_factor) { + const std::vector& supported_scale_factors = + ui::GetSupportedScaleFactors(); + return std::find(supported_scale_factors.begin(), + supported_scale_factors.end(), + scale_factor) != supported_scale_factors.end(); +} + +// Used to run the UI on a separate thread. +class CefUIThread : public base::Thread { + public: + explicit CefUIThread(const content::MainFunctionParams& main_function_params) + : base::Thread("CefUIThread"), + main_function_params_(main_function_params) { + } + + void Init() override { +#if defined(OS_WIN) + // Initializes the COM library on the current thread. + CoInitialize(NULL); +#endif + + // Use our own browser process runner. + browser_runner_.reset(content::BrowserMainRunner::Create()); + + // Initialize browser process state. Uses the current thread's mesage loop. + int exit_code = browser_runner_->Initialize(main_function_params_); + CHECK_EQ(exit_code, -1); + } + + void CleanUp() override { + browser_runner_->Shutdown(); + browser_runner_.reset(NULL); + +#if defined(OS_WIN) + // Closes the COM library on the current thread. CoInitialize must + // be balanced by a corresponding call to CoUninitialize. + CoUninitialize(); +#endif + } + + protected: + content::MainFunctionParams main_function_params_; + scoped_ptr browser_runner_; +}; + +} // namespace + +CefMainDelegate::CefMainDelegate(CefRefPtr application) + : content_client_(application) { + // Necessary so that exported functions from base_impl.cc will be included + // in the binary. + extern void base_impl_stub(); + base_impl_stub(); +} + +CefMainDelegate::~CefMainDelegate() { +} + +bool CefMainDelegate::BasicStartupComplete(int* exit_code) { +#if defined(OS_MACOSX) + OverrideFrameworkBundlePath(); +#endif + + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + std::string process_type = + command_line->GetSwitchValueASCII(switches::kProcessType); + + if (process_type.empty()) { + // In the browser process. Populate the global command-line object. + const CefSettings& settings = CefContext::Get()->settings(); + + if (settings.command_line_args_disabled) { + // Remove any existing command-line arguments. + base::CommandLine::StringVector argv; + argv.push_back(command_line->GetProgram().value()); + command_line->InitFromArgv(argv); + + const base::CommandLine::SwitchMap& map = command_line->GetSwitches(); + const_cast(&map)->clear(); + } + + if (settings.single_process) + command_line->AppendSwitch(switches::kSingleProcess); + + bool no_sandbox = settings.no_sandbox ? true : false; + + if (settings.browser_subprocess_path.length > 0) { + base::FilePath file_path = + base::FilePath(CefString(&settings.browser_subprocess_path)); + if (!file_path.empty()) { + command_line->AppendSwitchPath(switches::kBrowserSubprocessPath, + file_path); + +#if defined(OS_WIN) + // The sandbox is not supported when using a separate subprocess + // executable on Windows. + no_sandbox = true; +#endif + } + } + + if (no_sandbox) + command_line->AppendSwitch(switches::kNoSandbox); + + if (settings.user_agent.length > 0) { + command_line->AppendSwitchASCII(switches::kUserAgent, + CefString(&settings.user_agent)); + } else if (settings.product_version.length > 0) { + command_line->AppendSwitchASCII(switches::kProductVersion, + CefString(&settings.product_version)); + } + + if (settings.locale.length > 0) { + command_line->AppendSwitchASCII(switches::kLang, + CefString(&settings.locale)); + } else if (!command_line->HasSwitch(switches::kLang)) { + command_line->AppendSwitchASCII(switches::kLang, "en-US"); + } + + if (settings.log_file.length > 0) { + base::FilePath file_path = base::FilePath(CefString(&settings.log_file)); + if (!file_path.empty()) + command_line->AppendSwitchPath(switches::kLogFile, file_path); + } + + if (settings.log_severity != LOGSEVERITY_DEFAULT) { + std::string log_severity; + switch (settings.log_severity) { + case LOGSEVERITY_VERBOSE: + log_severity = switches::kLogSeverity_Verbose; + break; + case LOGSEVERITY_INFO: + log_severity = switches::kLogSeverity_Info; + break; + case LOGSEVERITY_WARNING: + log_severity = switches::kLogSeverity_Warning; + break; + case LOGSEVERITY_ERROR: + log_severity = switches::kLogSeverity_Error; + break; + case LOGSEVERITY_DISABLE: + log_severity = switches::kLogSeverity_Disable; + break; + default: + break; + } + if (!log_severity.empty()) + command_line->AppendSwitchASCII(switches::kLogSeverity, log_severity); + } + + if (settings.javascript_flags.length > 0) { + command_line->AppendSwitchASCII(switches::kJavaScriptFlags, + CefString(&settings.javascript_flags)); + } + + if (settings.pack_loading_disabled) { + command_line->AppendSwitch(switches::kDisablePackLoading); + } else { + if (settings.resources_dir_path.length > 0) { + base::FilePath file_path = + base::FilePath(CefString(&settings.resources_dir_path)); + if (!file_path.empty()) { + command_line->AppendSwitchPath(switches::kResourcesDirPath, + file_path); + } + } + + if (settings.locales_dir_path.length > 0) { + base::FilePath file_path = + base::FilePath(CefString(&settings.locales_dir_path)); + if (!file_path.empty()) + command_line->AppendSwitchPath(switches::kLocalesDirPath, file_path); + } + } + + if (settings.remote_debugging_port >= 1024 && + settings.remote_debugging_port <= 65535) { + command_line->AppendSwitchASCII(switches::kRemoteDebuggingPort, + base::IntToString(settings.remote_debugging_port)); + } + + if (settings.uncaught_exception_stack_size > 0) { + command_line->AppendSwitchASCII(switches::kUncaughtExceptionStackSize, + base::IntToString(settings.uncaught_exception_stack_size)); + } + + if (settings.context_safety_implementation != 0) { + command_line->AppendSwitchASCII(switches::kContextSafetyImplementation, + base::IntToString(settings.context_safety_implementation)); + } + + if (settings.windowless_rendering_enabled) { +#if defined(OS_MACOSX) + // The delegated renderer is not yet enabled by default on OS X. + command_line->AppendSwitch(switches::kEnableDelegatedRenderer); +#endif + } + } + + if (content_client_.application().get()) { + // Give the application a chance to view/modify the command line. + CefRefPtr commandLinePtr( + new CefCommandLineImpl(command_line, false, false)); + content_client_.application()->OnBeforeCommandLineProcessing( + CefString(process_type), commandLinePtr.get()); + commandLinePtr->Detach(NULL); + } + + // Initialize logging. + logging::LoggingSettings log_settings; + const base::FilePath& log_file = + command_line->GetSwitchValuePath(switches::kLogFile); + log_settings.log_file = log_file.value().c_str(); + log_settings.lock_log = logging::DONT_LOCK_LOG_FILE; + log_settings.delete_old = logging::APPEND_TO_OLD_LOG_FILE; + + logging::LogSeverity log_severity = logging::LOG_INFO; + + std::string log_severity_str = + command_line->GetSwitchValueASCII(switches::kLogSeverity); + if (!log_severity_str.empty()) { + if (LowerCaseEqualsASCII(log_severity_str, + switches::kLogSeverity_Verbose)) { + log_severity = logging::LOG_VERBOSE; + } else if (LowerCaseEqualsASCII(log_severity_str, + switches::kLogSeverity_Warning)) { + log_severity = logging::LOG_WARNING; + } else if (LowerCaseEqualsASCII(log_severity_str, + switches::kLogSeverity_Error)) { + log_severity = logging::LOG_ERROR; + } else if (LowerCaseEqualsASCII(log_severity_str, + switches::kLogSeverity_Disable)) { + log_severity = LOGSEVERITY_DISABLE; + } + } + + if (log_severity == LOGSEVERITY_DISABLE) { + log_settings.logging_dest = logging::LOG_NONE; + } else { + log_settings.logging_dest = logging::LOG_TO_ALL; + logging::SetMinLogLevel(log_severity); + } + + logging::InitLogging(log_settings); + + content::SetContentClient(&content_client_); + + return false; +} + +void CefMainDelegate::PreSandboxStartup() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + const std::string& process_type = + command_line->GetSwitchValueASCII(switches::kProcessType); + + if (command_line->HasSwitch(switches::kEnableCrashReporter)) { + crash_reporter::SetCrashReporterClient(g_crash_reporter_client.Pointer()); +#if defined(OS_MACOSX) + base::mac::DisableOSCrashDumps(); + breakpad::InitCrashReporter(process_type); + breakpad::InitCrashProcessInfo(process_type); +#elif defined(OS_POSIX) && !defined(OS_MACOSX) + if (process_type != switches::kZygoteProcess) + breakpad::InitCrashReporter(process_type); +#elif defined(OS_WIN) + UINT new_flags = + SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX; + UINT existing_flags = SetErrorMode(new_flags); + SetErrorMode(existing_flags | new_flags); + breakpad::InitCrashReporter(process_type); +#endif + } + + if (!command_line->HasSwitch(switches::kProcessType)) { + // Only these paths when executing the main process. +#if defined(OS_MACOSX) + OverrideChildProcessPath(); +#endif + + // Paths used to locate spell checking dictionary files. + // TODO(cef): It may be better to use a persistent location for + // DIR_USER_DATA. See the implementation of GetDefaultUserDataDirectory in + // chrome/common/chrome_paths_*. + const base::FilePath& cache_path = CefContext::Get()->cache_path(); + PathService::Override(chrome::DIR_USER_DATA, cache_path); + PathService::OverrideAndCreateIfNeeded( + chrome::DIR_APP_DICTIONARIES, + cache_path.AppendASCII("Dictionaries"), + false, // May not be an absolute path. + true); // Create if necessary. + } + + OverridePdfPluginPath(); + + if (command_line->HasSwitch(switches::kDisablePackLoading)) + content_client_.set_pack_loading_disabled(true); + + InitializeResourceBundle(); + + if (process_type == switches::kUtilityProcess || + process_type == switches::kZygoteProcess) { + CefContentUtilityClient::PreSandboxStartup(); + } +} + +int CefMainDelegate::RunProcess( + const std::string& process_type, + const content::MainFunctionParams& main_function_params) { + if (process_type.empty()) { + const CefSettings& settings = CefContext::Get()->settings(); + if (!settings.multi_threaded_message_loop) { + // Use our own browser process runner. + browser_runner_.reset(content::BrowserMainRunner::Create()); + + // Initialize browser process state. Results in a call to + // CefBrowserMain::PreMainMessageLoopStart() which creates the UI message + // loop. + int exit_code = browser_runner_->Initialize(main_function_params); + if (exit_code >= 0) + return exit_code; + } else { + // Run the UI on a separate thread. + scoped_ptr thread; + thread.reset(new CefUIThread(main_function_params)); + base::Thread::Options options; + options.message_loop_type = base::MessageLoop::TYPE_UI; + if (!thread->StartWithOptions(options)) { + NOTREACHED() << "failed to start UI thread"; + return 1; + } + ui_thread_.swap(thread); + } + + return 0; + } + + return -1; +} + +void CefMainDelegate::ProcessExiting(const std::string& process_type) { + ResourceBundle::CleanupSharedInstance(); +} + +#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX) +void CefMainDelegate::ZygoteForked() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kEnableCrashReporter)) { + const std::string& process_type = command_line->GetSwitchValueASCII( + switches::kProcessType); + breakpad::InitCrashReporter(process_type); + } +} +#endif + +content::ContentBrowserClient* CefMainDelegate::CreateContentBrowserClient() { + browser_client_.reset(new CefContentBrowserClient); + return browser_client_.get(); +} + +content::ContentRendererClient* + CefMainDelegate::CreateContentRendererClient() { + renderer_client_.reset(new CefContentRendererClient); + return renderer_client_.get(); +} + +content::ContentUtilityClient* CefMainDelegate::CreateContentUtilityClient() { + utility_client_.reset(new CefContentUtilityClient); + return utility_client_.get(); +} + +void CefMainDelegate::ShutdownBrowser() { + if (browser_runner_.get()) { + browser_runner_->Shutdown(); + browser_runner_.reset(NULL); + } + if (ui_thread_.get()) { + // Blocks until the thread has stopped. + ui_thread_->Stop(); + ui_thread_.reset(); + } +} + +void CefMainDelegate::InitializeResourceBundle() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + base::FilePath cef_pak_file, cef_100_percent_pak_file, + cef_200_percent_pak_file, devtools_pak_file, locales_dir; + + if (!content_client_.pack_loading_disabled()) { + base::FilePath resources_dir; + if (command_line->HasSwitch(switches::kResourcesDirPath)) { + resources_dir = + command_line->GetSwitchValuePath(switches::kResourcesDirPath); + } + if (resources_dir.empty()) + resources_dir = GetResourcesFilePath(); + + if (!resources_dir.empty()) { + cef_pak_file = resources_dir.Append(FILE_PATH_LITERAL("cef.pak")); + cef_100_percent_pak_file = + resources_dir.Append(FILE_PATH_LITERAL("cef_100_percent.pak")); + cef_200_percent_pak_file = + resources_dir.Append(FILE_PATH_LITERAL("cef_200_percent.pak")); + devtools_pak_file = + resources_dir.Append(FILE_PATH_LITERAL("devtools_resources.pak")); + } + + if (command_line->HasSwitch(switches::kLocalesDirPath)) + locales_dir = command_line->GetSwitchValuePath(switches::kLocalesDirPath); + + if (!locales_dir.empty()) + PathService::Override(ui::DIR_LOCALES, locales_dir); + } + + std::string locale = command_line->GetSwitchValueASCII(switches::kLang); + DCHECK(!locale.empty()); + + const std::string loaded_locale = + ui::ResourceBundle::InitSharedInstanceWithLocale( + locale, + &content_client_, + ui::ResourceBundle::LOAD_COMMON_RESOURCES); + ResourceBundle& resource_bundle = ResourceBundle::GetSharedInstance(); + + if (!content_client_.pack_loading_disabled()) { + if (loaded_locale.empty()) + LOG(ERROR) << "Could not load locale pak for " << locale; + + content_client_.set_allow_pack_file_load(true); + + if (base::PathExists(cef_pak_file)) { + resource_bundle.AddDataPackFromPath(cef_pak_file, ui::SCALE_FACTOR_NONE); + } else { + LOG(ERROR) << "Could not load cef.pak"; + } + + // On OS X and Linux/Aura always load the 1x data pack first as the 2x data + // pack contains both 1x and 2x images. + const bool load_100_percent = +#if defined(OS_WIN) + IsScaleFactorSupported(ui::SCALE_FACTOR_100P); +#else + true; +#endif + + if (load_100_percent) { + if (base::PathExists(cef_100_percent_pak_file)) { + resource_bundle.AddDataPackFromPath( + cef_100_percent_pak_file, ui::SCALE_FACTOR_100P); + } else { + LOG(ERROR) << "Could not load cef_100_percent.pak"; + } + } + + if (IsScaleFactorSupported(ui::SCALE_FACTOR_200P)) { + if (base::PathExists(cef_200_percent_pak_file)) { + resource_bundle.AddDataPackFromPath( + cef_200_percent_pak_file, ui::SCALE_FACTOR_200P); + } else { + LOG(ERROR) << "Could not load cef_200_percent.pak"; + } + } + + if (base::PathExists(devtools_pak_file)) { + resource_bundle.AddDataPackFromPath( + devtools_pak_file, ui::SCALE_FACTOR_NONE); + } + + content_client_.set_allow_pack_file_load(false); + } +} diff --git a/libcef/common/main_delegate.h b/libcef/common/main_delegate.h new file mode 100644 index 000000000..e5089ac2e --- /dev/null +++ b/libcef/common/main_delegate.h @@ -0,0 +1,69 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_MAIN_DELEGATE_H_ +#define CEF_LIBCEF_COMMON_MAIN_DELEGATE_H_ +#pragma once + +#include + +#include "libcef/common/content_client.h" +#include "include/cef_app.h" + +#include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" +#include "content/public/app/content_main_delegate.h" + +namespace base { +class Thread; +} + +namespace content { +class BrowserMainRunner; +} + +class CefContentBrowserClient; +class CefContentRendererClient; +class CefContentUtilityClient; + +class CefMainDelegate : public content::ContentMainDelegate { + public: + explicit CefMainDelegate(CefRefPtr application); + ~CefMainDelegate() override; + + bool BasicStartupComplete(int* exit_code) override; + void PreSandboxStartup() override; + int RunProcess( + const std::string& process_type, + const content::MainFunctionParams& main_function_params) override; + void ProcessExiting(const std::string& process_type) override; +#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_MACOSX) + void ZygoteForked() override; +#endif + content::ContentBrowserClient* CreateContentBrowserClient() override; + content::ContentRendererClient* + CreateContentRendererClient() override; + content::ContentUtilityClient* CreateContentUtilityClient() override; + + // Shut down the browser runner. + void ShutdownBrowser(); + + CefContentBrowserClient* browser_client() { return browser_client_.get(); } + CefContentClient* content_client() { return &content_client_; } + + private: + void InitializeResourceBundle(); + + scoped_ptr browser_runner_; + scoped_ptr ui_thread_; + + scoped_ptr browser_client_; + scoped_ptr renderer_client_; + scoped_ptr utility_client_; + CefContentClient content_client_; + + DISALLOW_COPY_AND_ASSIGN(CefMainDelegate); +}; + +#endif // CEF_LIBCEF_COMMON_MAIN_DELEGATE_H_ diff --git a/libcef/common/net_resource_provider.cc b/libcef/common/net_resource_provider.cc new file mode 100644 index 000000000..13fbbcf62 --- /dev/null +++ b/libcef/common/net_resource_provider.cc @@ -0,0 +1,10 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/content_client.h" +#include "libcef/common/net_resource_provider.h" + +base::StringPiece NetResourceProvider(int key) { + return CefContentClient::Get()->GetDataResource(key, ui::SCALE_FACTOR_NONE); +} diff --git a/libcef/common/net_resource_provider.h b/libcef/common/net_resource_provider.h new file mode 100644 index 000000000..73e5ad75e --- /dev/null +++ b/libcef/common/net_resource_provider.h @@ -0,0 +1,14 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_NET_RESOURCE_PROVIDER_H_ +#define CEF_LIBCEF_COMMON_NET_RESOURCE_PROVIDER_H_ +#pragma once + +#include "base/strings/string_piece.h" + +// This is called indirectly by the network layer to access resources. +base::StringPiece NetResourceProvider(int key); + +#endif // CEF_LIBCEF_COMMON_NET_RESOURCE_PROVIDER_H_ diff --git a/libcef/common/process_message_impl.cc b/libcef/common/process_message_impl.cc new file mode 100644 index 000000000..e6dabd87e --- /dev/null +++ b/libcef/common/process_message_impl.cc @@ -0,0 +1,76 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/process_message_impl.h" +#include "libcef/common/cef_messages.h" +#include "libcef/common/values_impl.h" + +#include "base/logging.h" + +namespace { + +void CopyList(const base::ListValue& source, + base::ListValue& target) { + base::ListValue::const_iterator it = source.begin(); + for (; it != source.end(); ++it) + target.Append((*it)->DeepCopy()); +} + +void CopyValue(const Cef_Request_Params& source, + Cef_Request_Params& target) { + target.name = source.name; + CopyList(source.arguments, target.arguments); +} + +} // namespace + +// static +CefRefPtr CefProcessMessage::Create(const CefString& name) { + Cef_Request_Params* params = new Cef_Request_Params(); + params->name = name; + return new CefProcessMessageImpl(params, true, false); +} + +CefProcessMessageImpl::CefProcessMessageImpl(Cef_Request_Params* value, + bool will_delete, + bool read_only) + : CefValueBase( + value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete, + read_only, NULL) { +} + +bool CefProcessMessageImpl::CopyTo(Cef_Request_Params& target) { + CEF_VALUE_VERIFY_RETURN(false, false); + CopyValue(const_value(), target); + return true; +} + +bool CefProcessMessageImpl::IsValid() { + return !detached(); +} + +bool CefProcessMessageImpl::IsReadOnly() { + return read_only(); +} + +CefRefPtr CefProcessMessageImpl::Copy() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + Cef_Request_Params* params = new Cef_Request_Params(); + CopyValue(const_value(), *params); + return new CefProcessMessageImpl(params, true, false); +} + +CefString CefProcessMessageImpl::GetName() { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + return const_value().name; +} + +CefRefPtr CefProcessMessageImpl::GetArgumentList() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + return CefListValueImpl::GetOrCreateRef( + const_cast(&(const_value().arguments)), + const_cast(&const_value()), + read_only(), + controller()); +} diff --git a/libcef/common/process_message_impl.h b/libcef/common/process_message_impl.h new file mode 100644 index 000000000..30dfc72ae --- /dev/null +++ b/libcef/common/process_message_impl.h @@ -0,0 +1,35 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_PROCESS_MESSAGE_IMPL_H_ +#define CEF_LIBCEF_COMMON_PROCESS_MESSAGE_IMPL_H_ +#pragma once + +#include "include/cef_process_message.h" +#include "libcef/common/value_base.h" + +struct Cef_Request_Params; + +// CefProcessMessage implementation +class CefProcessMessageImpl + : public CefValueBase { + public: + CefProcessMessageImpl(Cef_Request_Params* value, + bool will_delete, + bool read_only); + + // Copies the underlying value to the specified |target| structure. + bool CopyTo(Cef_Request_Params& target); + + // CefProcessMessage methods. + bool IsValid() override; + bool IsReadOnly() override; + CefRefPtr Copy() override; + CefString GetName() override; + CefRefPtr GetArgumentList() override; + + DISALLOW_COPY_AND_ASSIGN(CefProcessMessageImpl); +}; + +#endif // CEF_LIBCEF_COMMON_PROCESS_MESSAGE_IMPL_H_ diff --git a/libcef/common/request_impl.cc b/libcef/common/request_impl.cc new file mode 100644 index 000000000..6a4f8be6e --- /dev/null +++ b/libcef/common/request_impl.cc @@ -0,0 +1,811 @@ +// Copyright (c) 2008-2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include + +#include "libcef/common/http_header_utils.h" +#include "libcef/common/request_impl.h" +#include "libcef/common/task_runner_impl.h" +#include "libcef/common/upload_data.h" + +#include "base/logging.h" +#include "content/public/browser/resource_request_info.h" +#include "content/public/common/resource_type.h" +#include "net/base/elements_upload_data_stream.h" +#include "net/base/upload_data_stream.h" +#include "net/base/upload_element_reader.h" +#include "net/base/upload_bytes_element_reader.h" +#include "net/base/upload_file_element_reader.h" +#include "net/http/http_request_headers.h" +#include "net/url_request/url_request.h" +#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/platform/WebURLError.h" +#include "third_party/WebKit/public/platform/WebURLRequest.h" + +namespace { + +// A subclass of net::UploadBytesElementReader that keeps the associated +// UploadElement alive until the request completes. +class BytesElementReader : public net::UploadBytesElementReader { + public: + explicit BytesElementReader(scoped_ptr element) + : net::UploadBytesElementReader(element->bytes(), + element->bytes_length()), + element_(element.Pass()) { + DCHECK_EQ(net::UploadElement::TYPE_BYTES, element_->type()); + } + + private: + scoped_ptr element_; + + DISALLOW_COPY_AND_ASSIGN(BytesElementReader); +}; + +base::TaskRunner* GetFileTaskRunner() { + scoped_refptr task_runner = + CefTaskRunnerImpl::GetTaskRunner(TID_FILE); + DCHECK(task_runner.get()); + return task_runner.get(); +} + +// A subclass of net::UploadFileElementReader that keeps the associated +// UploadElement alive until the request completes. +class FileElementReader : public net::UploadFileElementReader { + public: + explicit FileElementReader(scoped_ptr element) + : net::UploadFileElementReader( + GetFileTaskRunner(), + element->file_path(), + element->file_range_offset(), + element->file_range_length(), + element->expected_file_modification_time()), + element_(element.Pass()) { + DCHECK_EQ(net::UploadElement::TYPE_FILE, element_->type()); + } + + private: + scoped_ptr element_; + + DISALLOW_COPY_AND_ASSIGN(FileElementReader); +}; + +} // namespace + + +#define CHECK_READONLY_RETURN(val) \ + if (read_only_) { \ + NOTREACHED() << "object is read only"; \ + return val; \ + } + +#define CHECK_READONLY_RETURN_VOID() \ + if (read_only_) { \ + NOTREACHED() << "object is read only"; \ + return; \ + } + + +// CefRequest ----------------------------------------------------------------- + +// static +CefRefPtr CefRequest::Create() { + CefRefPtr request(new CefRequestImpl()); + return request; +} + + +// CefRequestImpl ------------------------------------------------------------- + +CefRequestImpl::CefRequestImpl() + : method_("GET"), + resource_type_(RT_SUB_RESOURCE), + transition_type_(TT_EXPLICIT), + flags_(UR_FLAG_NONE), + read_only_(false) { +} + +bool CefRequestImpl::IsReadOnly() { + base::AutoLock lock_scope(lock_); + return read_only_; +} + +CefString CefRequestImpl::GetURL() { + base::AutoLock lock_scope(lock_); + return url_; +} + +void CefRequestImpl::SetURL(const CefString& url) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + url_ = url; +} + +CefString CefRequestImpl::GetMethod() { + base::AutoLock lock_scope(lock_); + return method_; +} + +void CefRequestImpl::SetMethod(const CefString& method) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + method_ = method; +} + +CefRefPtr CefRequestImpl::GetPostData() { + base::AutoLock lock_scope(lock_); + return postdata_; +} + +void CefRequestImpl::SetPostData(CefRefPtr postData) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + postdata_ = postData; +} + +void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) { + base::AutoLock lock_scope(lock_); + headerMap = headermap_; +} + +void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + headermap_ = headerMap; +} + +void CefRequestImpl::Set(const CefString& url, + const CefString& method, + CefRefPtr postData, + const HeaderMap& headerMap) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + url_ = url; + method_ = method; + postdata_ = postData; + headermap_ = headerMap; +} + +int CefRequestImpl::GetFlags() { + base::AutoLock lock_scope(lock_); + return flags_; +} +void CefRequestImpl::SetFlags(int flags) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + flags_ = flags; +} + +CefString CefRequestImpl::GetFirstPartyForCookies() { + base::AutoLock lock_scope(lock_); + return first_party_for_cookies_; +} +void CefRequestImpl::SetFirstPartyForCookies(const CefString& url) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + first_party_for_cookies_ = url; +} + +CefRequestImpl::ResourceType CefRequestImpl::GetResourceType() { + base::AutoLock lock_scope(lock_); + return resource_type_; +} + +CefRequestImpl::TransitionType CefRequestImpl::GetTransitionType() { + base::AutoLock lock_scope(lock_); + return transition_type_; +} + +void CefRequestImpl::Set(net::URLRequest* request) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + + url_ = request->url().spec(); + method_ = request->method(); + first_party_for_cookies_ = request->first_party_for_cookies().spec(); + + net::HttpRequestHeaders headers = request->extra_request_headers(); + + // URLRequest::SetReferrer ensures that we do not send username and password + // fields in the referrer. + GURL referrer(request->referrer()); + + // Strip Referer from request_info_.extra_headers to prevent, e.g., plugins + // from overriding headers that are controlled using other means. Otherwise a + // plugin could set a referrer although sending the referrer is inhibited. + headers.RemoveHeader(net::HttpRequestHeaders::kReferer); + + // Our consumer should have made sure that this is a safe referrer. See for + // instance WebCore::FrameLoader::HideReferrer. + if (referrer.is_valid()) + headers.SetHeader(net::HttpRequestHeaders::kReferer, referrer.spec()); + + // Transfer request headers + GetHeaderMap(headers, headermap_); + + // Transfer post data, if any + const net::UploadDataStream* data = request->get_upload(); + if (data) { + postdata_ = CefPostData::Create(); + static_cast(postdata_.get())->Set(*data); + } else if (postdata_.get()) { + postdata_ = NULL; + } + + const content::ResourceRequestInfo* info = + content::ResourceRequestInfo::ForRequest(request); + if (info) { + resource_type_ = + static_cast(info->GetResourceType()); + transition_type_ = + static_cast(info->GetPageTransition()); + } else { + resource_type_ = RT_SUB_RESOURCE; + transition_type_ = TT_EXPLICIT; + } +} + +void CefRequestImpl::Get(net::URLRequest* request) { + base::AutoLock lock_scope(lock_); + + request->set_method(method_); + if (!first_party_for_cookies_.empty()) { + request->set_first_party_for_cookies( + GURL(std::string(first_party_for_cookies_))); + } + + CefString referrerStr; + referrerStr.FromASCII(net::HttpRequestHeaders::kReferer); + HeaderMap headerMap = headermap_; + HeaderMap::iterator it = headerMap.find(referrerStr); + if (it == headerMap.end()) { + request->SetReferrer(""); + } else { + request->SetReferrer(it->second); + headerMap.erase(it); + } + net::HttpRequestHeaders headers; + headers.AddHeadersFromString(HttpHeaderUtils::GenerateHeaders(headerMap)); + request->SetExtraRequestHeaders(headers); + + if (postdata_.get()) { + request->set_upload( + make_scoped_ptr(static_cast(postdata_.get())->Get())); + } else if (request->get_upload()) { + request->set_upload(scoped_ptr()); + } +} + +void CefRequestImpl::Set(const blink::WebURLRequest& request) { + DCHECK(!request.isNull()); + + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + + url_ = request.url().spec().utf16(); + method_ = request.httpMethod(); + + const blink::WebHTTPBody& body = request.httpBody(); + if (!body.isNull()) { + postdata_ = new CefPostDataImpl(); + static_cast(postdata_.get())->Set(body); + } else if (postdata_.get()) { + postdata_ = NULL; + } + + headermap_.clear(); + GetHeaderMap(request, headermap_); + + flags_ = UR_FLAG_NONE; + if (request.cachePolicy() == blink::WebURLRequest::ReloadIgnoringCacheData) + flags_ |= UR_FLAG_SKIP_CACHE; + if (request.allowStoredCredentials()) + flags_ |= UR_FLAG_ALLOW_CACHED_CREDENTIALS; + if (request.reportUploadProgress()) + flags_ |= UR_FLAG_REPORT_UPLOAD_PROGRESS; + if (request.reportRawHeaders()) + flags_ |= UR_FLAG_REPORT_RAW_HEADERS; + + first_party_for_cookies_ = request.firstPartyForCookies().spec().utf16(); +} + +void CefRequestImpl::Get(blink::WebURLRequest& request) { + request.initialize(); + base::AutoLock lock_scope(lock_); + + GURL gurl = GURL(url_.ToString()); + request.setURL(blink::WebURL(gurl)); + + std::string method(method_); + request.setHTTPMethod(blink::WebString::fromUTF8(method.c_str())); + + blink::WebHTTPBody body; + if (postdata_.get()) { + body.initialize(); + static_cast(postdata_.get())->Get(body); + request.setHTTPBody(body); + } + + SetHeaderMap(headermap_, request); + + request.setCachePolicy((flags_ & UR_FLAG_SKIP_CACHE) ? + blink::WebURLRequest::ReloadIgnoringCacheData : + blink::WebURLRequest::UseProtocolCachePolicy); + + #define SETBOOLFLAG(obj, flags, method, FLAG) \ + obj.method((flags & (FLAG)) == (FLAG)) + + SETBOOLFLAG(request, flags_, setAllowStoredCredentials, + UR_FLAG_ALLOW_CACHED_CREDENTIALS); + SETBOOLFLAG(request, flags_, setReportUploadProgress, + UR_FLAG_REPORT_UPLOAD_PROGRESS); + SETBOOLFLAG(request, flags_, setReportRawHeaders, + UR_FLAG_REPORT_RAW_HEADERS); + + if (!first_party_for_cookies_.empty()) { + GURL gurl = GURL(first_party_for_cookies_.ToString()); + request.setFirstPartyForCookies(blink::WebURL(gurl)); + } +} + +void CefRequestImpl::SetReadOnly(bool read_only) { + base::AutoLock lock_scope(lock_); + if (read_only_ == read_only) + return; + + read_only_ = read_only; + + if (postdata_.get()) + static_cast(postdata_.get())->SetReadOnly(read_only); +} + +// static +void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers, + HeaderMap& map) { + if (headers.IsEmpty()) + return; + + net::HttpRequestHeaders::Iterator it(headers); + do { + map.insert(std::make_pair(it.name(), it.value())); + } while (it.GetNext()); +} + + +// static +void CefRequestImpl::GetHeaderMap(const blink::WebURLRequest& request, + HeaderMap& map) { + class HeaderVisitor : public blink::WebHTTPHeaderVisitor { + public: + explicit HeaderVisitor(HeaderMap* map) : map_(map) {} + + void visitHeader(const blink::WebString& name, + const blink::WebString& value) override { + map_->insert(std::make_pair(base::string16(name), + base::string16(value))); + } + + private: + HeaderMap* map_; + }; + + HeaderVisitor visitor(&map); + request.visitHTTPHeaderFields(&visitor); +} + +// static +void CefRequestImpl::SetHeaderMap(const HeaderMap& map, + blink::WebURLRequest& request) { + HeaderMap::const_iterator it = map.begin(); + for (; it != map.end(); ++it) + request.setHTTPHeaderField(base::string16(it->first), + base::string16(it->second)); +} + +// CefPostData ---------------------------------------------------------------- + +// static +CefRefPtr CefPostData::Create() { + CefRefPtr postdata(new CefPostDataImpl()); + return postdata; +} + + +// CefPostDataImpl ------------------------------------------------------------ + +CefPostDataImpl::CefPostDataImpl() + : read_only_(false) { +} + +bool CefPostDataImpl::IsReadOnly() { + base::AutoLock lock_scope(lock_); + return read_only_; +} + +size_t CefPostDataImpl::GetElementCount() { + base::AutoLock lock_scope(lock_); + return elements_.size(); +} + +void CefPostDataImpl::GetElements(ElementVector& elements) { + base::AutoLock lock_scope(lock_); + elements = elements_; +} + +bool CefPostDataImpl::RemoveElement(CefRefPtr element) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN(false); + + ElementVector::iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + if (it->get() == element.get()) { + elements_.erase(it); + return true; + } + } + + return false; +} + +bool CefPostDataImpl::AddElement(CefRefPtr element) { + bool found = false; + + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN(false); + + // check that the element isn't already in the list before adding + ElementVector::const_iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + if (it->get() == element.get()) { + found = true; + break; + } + } + + if (!found) + elements_.push_back(element); + + return !found; +} + +void CefPostDataImpl::RemoveElements() { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + elements_.clear(); +} + +void CefPostDataImpl::Set(const net::UploadData& data) { + { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + } + + CefRefPtr postelem; + + const ScopedVector& elements = data.elements(); + ScopedVector::const_iterator it = elements.begin(); + for (; it != elements.end(); ++it) { + postelem = CefPostDataElement::Create(); + static_cast(postelem.get())->Set(**it); + AddElement(postelem); + } +} + +void CefPostDataImpl::Set(const net::UploadDataStream& data_stream) { + { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + } + + CefRefPtr postelem; + + const ScopedVector* elements = + data_stream.GetElementReaders(); + if (elements) { + ScopedVector::const_iterator it = + elements->begin(); + for (; it != elements->end(); ++it) { + postelem = CefPostDataElement::Create(); + static_cast(postelem.get())->Set(**it); + AddElement(postelem); + } + } +} + +void CefPostDataImpl::Get(net::UploadData& data) { + base::AutoLock lock_scope(lock_); + + ScopedVector data_elements; + ElementVector::const_iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + net::UploadElement* element = new net::UploadElement(); + static_cast(it->get())->Get(*element); + data_elements.push_back(element); + } + data.swap_elements(&data_elements); +} + +net::UploadDataStream* CefPostDataImpl::Get() { + base::AutoLock lock_scope(lock_); + + ScopedVector element_readers; + ElementVector::const_iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + element_readers.push_back( + static_cast(it->get())->Get()); + } + + return new net::ElementsUploadDataStream(element_readers.Pass(), 0); +} + +void CefPostDataImpl::Set(const blink::WebHTTPBody& data) { + { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + } + + CefRefPtr postelem; + blink::WebHTTPBody::Element element; + size_t size = data.elementCount(); + for (size_t i = 0; i < size; ++i) { + if (data.elementAt(i, element)) { + postelem = CefPostDataElement::Create(); + static_cast(postelem.get())->Set(element); + AddElement(postelem); + } + } +} + +void CefPostDataImpl::Get(blink::WebHTTPBody& data) { + base::AutoLock lock_scope(lock_); + + blink::WebHTTPBody::Element element; + ElementVector::iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + static_cast(it->get())->Get(element); + if (element.type == blink::WebHTTPBody::Element::TypeData) { + data.appendData(element.data); + } else if (element.type == blink::WebHTTPBody::Element::TypeFile) { + data.appendFile(element.filePath); + } else { + NOTREACHED(); + } + } +} + +void CefPostDataImpl::SetReadOnly(bool read_only) { + base::AutoLock lock_scope(lock_); + if (read_only_ == read_only) + return; + + read_only_ = read_only; + + ElementVector::const_iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + static_cast(it->get())->SetReadOnly(read_only); + } +} + +// CefPostDataElement --------------------------------------------------------- + +// static +CefRefPtr CefPostDataElement::Create() { + CefRefPtr element(new CefPostDataElementImpl()); + return element; +} + + +// CefPostDataElementImpl ----------------------------------------------------- + +CefPostDataElementImpl::CefPostDataElementImpl() + : type_(PDE_TYPE_EMPTY), + read_only_(false) { + memset(&data_, 0, sizeof(data_)); +} + +CefPostDataElementImpl::~CefPostDataElementImpl() { + Cleanup(); +} + +bool CefPostDataElementImpl::IsReadOnly() { + base::AutoLock lock_scope(lock_); + return read_only_; +} + +void CefPostDataElementImpl::SetToEmpty() { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + + Cleanup(); +} + +void CefPostDataElementImpl::SetToFile(const CefString& fileName) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + + // Clear any data currently in the element + Cleanup(); + + // Assign the new data + type_ = PDE_TYPE_FILE; + cef_string_copy(fileName.c_str(), fileName.length(), &data_.filename); +} + +void CefPostDataElementImpl::SetToBytes(size_t size, const void* bytes) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + + // Clear any data currently in the element + Cleanup(); + + // Assign the new data + void* data = malloc(size); + DCHECK(data != NULL); + if (data == NULL) + return; + + memcpy(data, bytes, size); + + type_ = PDE_TYPE_BYTES; + data_.bytes.bytes = data; + data_.bytes.size = size; +} + +CefPostDataElement::Type CefPostDataElementImpl::GetType() { + base::AutoLock lock_scope(lock_); + return type_; +} + +CefString CefPostDataElementImpl::GetFile() { + base::AutoLock lock_scope(lock_); + DCHECK(type_ == PDE_TYPE_FILE); + CefString filename; + if (type_ == PDE_TYPE_FILE) + filename.FromString(data_.filename.str, data_.filename.length, false); + return filename; +} + +size_t CefPostDataElementImpl::GetBytesCount() { + base::AutoLock lock_scope(lock_); + DCHECK(type_ == PDE_TYPE_BYTES); + size_t size = 0; + if (type_ == PDE_TYPE_BYTES) + size = data_.bytes.size; + return size; +} + +size_t CefPostDataElementImpl::GetBytes(size_t size, void* bytes) { + base::AutoLock lock_scope(lock_); + DCHECK(type_ == PDE_TYPE_BYTES); + size_t rv = 0; + if (type_ == PDE_TYPE_BYTES) { + rv = (size < data_.bytes.size ? size : data_.bytes.size); + memcpy(bytes, data_.bytes.bytes, rv); + } + return rv; +} + +void CefPostDataElementImpl::Set(const net::UploadElement& element) { + { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + } + + if (element.type() == net::UploadElement::TYPE_BYTES) { + SetToBytes(element.bytes_length(), element.bytes()); + } else if (element.type() == net::UploadElement::TYPE_FILE) { + SetToFile(element.file_path().value()); + } else { + NOTREACHED(); + } +} + +void CefPostDataElementImpl::Set( + const net::UploadElementReader& element_reader) { + { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + } + + const net::UploadBytesElementReader* bytes_reader = + element_reader.AsBytesReader(); + if (bytes_reader) { + SetToBytes(bytes_reader->length(), bytes_reader->bytes()); + return; + } + + const net::UploadFileElementReader* file_reader = + element_reader.AsFileReader(); + if (file_reader) { + SetToFile(file_reader->path().value()); + return; + } + + NOTREACHED(); +} + +void CefPostDataElementImpl::Get(net::UploadElement& element) { + base::AutoLock lock_scope(lock_); + + if (type_ == PDE_TYPE_BYTES) { + element.SetToBytes(static_cast(data_.bytes.bytes), data_.bytes.size); + } else if (type_ == PDE_TYPE_FILE) { + base::FilePath path = base::FilePath(CefString(&data_.filename)); + element.SetToFilePath(path); + } else { + NOTREACHED(); + } +} + +net::UploadElementReader* CefPostDataElementImpl::Get() { + base::AutoLock lock_scope(lock_); + + if (type_ == PDE_TYPE_BYTES) { + net::UploadElement* element = new net::UploadElement(); + element->SetToBytes(static_cast(data_.bytes.bytes), + data_.bytes.size); + return new BytesElementReader(make_scoped_ptr(element)); + } else if (type_ == PDE_TYPE_FILE) { + net::UploadElement* element = new net::UploadElement(); + base::FilePath path = base::FilePath(CefString(&data_.filename)); + element->SetToFilePath(path); + return new FileElementReader(make_scoped_ptr(element)); + } else { + NOTREACHED(); + return NULL; + } +} + +void CefPostDataElementImpl::Set(const blink::WebHTTPBody::Element& element) { + { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + } + + if (element.type == blink::WebHTTPBody::Element::TypeData) { + SetToBytes(element.data.size(), + static_cast(element.data.data())); + } else if (element.type == blink::WebHTTPBody::Element::TypeFile) { + SetToFile(base::string16(element.filePath)); + } else { + NOTREACHED(); + } +} + +void CefPostDataElementImpl::Get(blink::WebHTTPBody::Element& element) { + base::AutoLock lock_scope(lock_); + + if (type_ == PDE_TYPE_BYTES) { + element.type = blink::WebHTTPBody::Element::TypeData; + element.data.assign( + static_cast(data_.bytes.bytes), data_.bytes.size); + } else if (type_ == PDE_TYPE_FILE) { + element.type = blink::WebHTTPBody::Element::TypeFile; + element.filePath.assign(base::string16(CefString(&data_.filename))); + } else { + NOTREACHED(); + } +} + +void CefPostDataElementImpl::SetReadOnly(bool read_only) { + base::AutoLock lock_scope(lock_); + if (read_only_ == read_only) + return; + + read_only_ = read_only; +} + +void CefPostDataElementImpl::Cleanup() { + if (type_ == PDE_TYPE_EMPTY) + return; + + if (type_ == PDE_TYPE_BYTES) + free(data_.bytes.bytes); + else if (type_ == PDE_TYPE_FILE) + cef_string_clear(&data_.filename); + type_ = PDE_TYPE_EMPTY; + memset(&data_, 0, sizeof(data_)); +} diff --git a/libcef/common/request_impl.h b/libcef/common/request_impl.h new file mode 100644 index 000000000..6e6ac9053 --- /dev/null +++ b/libcef/common/request_impl.h @@ -0,0 +1,171 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_REQUEST_IMPL_H_ +#define CEF_LIBCEF_COMMON_REQUEST_IMPL_H_ +#pragma once + +#include "include/cef_request.h" + +#include "base/synchronization/lock.h" +#include "third_party/WebKit/public/platform/WebHTTPBody.h" + +namespace net { +class HttpRequestHeaders; +class UploadData; +class UploadDataStream; +class UploadElement; +class UploadElementReader; +class URLRequest; +}; + +namespace blink { +class WebURLRequest; +} + +// Implementation of CefRequest +class CefRequestImpl : public CefRequest { + public: + CefRequestImpl(); + + bool IsReadOnly() override; + CefString GetURL() override; + void SetURL(const CefString& url) override; + CefString GetMethod() override; + void SetMethod(const CefString& method) override; + CefRefPtr GetPostData() override; + void SetPostData(CefRefPtr postData) override; + void GetHeaderMap(HeaderMap& headerMap) override; + void SetHeaderMap(const HeaderMap& headerMap) override; + void Set(const CefString& url, + const CefString& method, + CefRefPtr postData, + const HeaderMap& headerMap) override; + int GetFlags() override; + void SetFlags(int flags) override; + CefString GetFirstPartyForCookies() override; + void SetFirstPartyForCookies(const CefString& url) override; + ResourceType GetResourceType() override; + TransitionType GetTransitionType() override; + + // Populate this object from the URLRequest object. + void Set(net::URLRequest* request); + + // Populate the URLRequest object from this object. + void Get(net::URLRequest* request); + + // Populate this object from a WebURLRequest object. + void Set(const blink::WebURLRequest& request); + + // Populate the WebURLRequest object from this object. + void Get(blink::WebURLRequest& request); + + void SetReadOnly(bool read_only); + + static void GetHeaderMap(const net::HttpRequestHeaders& headers, + HeaderMap& map); + static void GetHeaderMap(const blink::WebURLRequest& request, + HeaderMap& map); + static void SetHeaderMap(const HeaderMap& map, + blink::WebURLRequest& request); + + protected: + CefString url_; + CefString method_; + CefRefPtr postdata_; + HeaderMap headermap_; + ResourceType resource_type_; + TransitionType transition_type_; + + // The below members are used by CefURLRequest. + int flags_; + CefString first_party_for_cookies_; + + // True if this object is read-only. + bool read_only_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefRequestImpl); +}; + +// Implementation of CefPostData +class CefPostDataImpl : public CefPostData { + public: + CefPostDataImpl(); + + bool IsReadOnly() override; + size_t GetElementCount() override; + void GetElements(ElementVector& elements) override; + bool RemoveElement(CefRefPtr element) override; + bool AddElement(CefRefPtr element) override; + void RemoveElements() override; + + void Set(const net::UploadData& data); + void Set(const net::UploadDataStream& data_stream); + void Get(net::UploadData& data); + net::UploadDataStream* Get(); + void Set(const blink::WebHTTPBody& data); + void Get(blink::WebHTTPBody& data); + + void SetReadOnly(bool read_only); + + protected: + ElementVector elements_; + + // True if this object is read-only. + bool read_only_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefPostDataImpl); +}; + +// Implementation of CefPostDataElement +class CefPostDataElementImpl : public CefPostDataElement { + public: + CefPostDataElementImpl(); + ~CefPostDataElementImpl() override; + + bool IsReadOnly() override; + void SetToEmpty() override; + void SetToFile(const CefString& fileName) override; + void SetToBytes(size_t size, const void* bytes) override; + Type GetType() override; + CefString GetFile() override; + size_t GetBytesCount() override; + size_t GetBytes(size_t size, void* bytes) override; + + void* GetBytes() { return data_.bytes.bytes; } + + void Set(const net::UploadElement& element); + void Set(const net::UploadElementReader& element_reader); + void Get(net::UploadElement& element); + net::UploadElementReader* Get(); + void Set(const blink::WebHTTPBody::Element& element); + void Get(blink::WebHTTPBody::Element& element); + + void SetReadOnly(bool read_only); + + protected: + void Cleanup(); + + Type type_; + union { + struct { + void* bytes; + size_t size; + } bytes; + cef_string_t filename; + } data_; + + // True if this object is read-only. + bool read_only_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefPostDataElementImpl); +}; + +#endif // CEF_LIBCEF_COMMON_REQUEST_IMPL_H_ diff --git a/libcef/common/response_impl.cc b/libcef/common/response_impl.cc new file mode 100644 index 000000000..6cd79ec14 --- /dev/null +++ b/libcef/common/response_impl.cc @@ -0,0 +1,205 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/response_impl.h" + +#include + +#include "base/logging.h" +#include "base/strings/stringprintf.h" +#include "net/http/http_request_headers.h" +#include "net/http/http_response_headers.h" +#include "third_party/WebKit/public/platform/WebHTTPHeaderVisitor.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURLResponse.h" + + +#define CHECK_READONLY_RETURN_VOID() \ + if (read_only_) { \ + NOTREACHED() << "object is read only"; \ + return; \ + } + + +// CefResponse ---------------------------------------------------------------- + +// static +CefRefPtr CefResponse::Create() { + CefRefPtr response(new CefResponseImpl()); + return response; +} + + +// CefResponseImpl ------------------------------------------------------------ + +CefResponseImpl::CefResponseImpl() + : status_code_(0), + read_only_(false) { +} + +bool CefResponseImpl::IsReadOnly() { + base::AutoLock lock_scope(lock_); + return read_only_; +} + +int CefResponseImpl::GetStatus() { + base::AutoLock lock_scope(lock_); + return status_code_; +} + +void CefResponseImpl::SetStatus(int status) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + status_code_ = status; +} + +CefString CefResponseImpl::GetStatusText() { + base::AutoLock lock_scope(lock_); + return status_text_; +} + +void CefResponseImpl::SetStatusText(const CefString& statusText) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + status_text_ = statusText; +} + +CefString CefResponseImpl::GetMimeType() { + base::AutoLock lock_scope(lock_); + return mime_type_; +} + +void CefResponseImpl::SetMimeType(const CefString& mimeType) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + mime_type_ = mimeType; +} + +CefString CefResponseImpl::GetHeader(const CefString& name) { + base::AutoLock lock_scope(lock_); + + CefString value; + + HeaderMap::const_iterator it = header_map_.find(name); + if (it != header_map_.end()) + value = it->second; + + return value; +} + +void CefResponseImpl::GetHeaderMap(HeaderMap& map) { + base::AutoLock lock_scope(lock_); + map = header_map_; +} + +void CefResponseImpl::SetHeaderMap(const HeaderMap& headerMap) { + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + header_map_ = headerMap; +} + +net::HttpResponseHeaders* CefResponseImpl::GetResponseHeaders() { + base::AutoLock lock_scope(lock_); + + std::string response; + std::string status_text; + bool has_content_type_header = false; + + if (!status_text_.empty()) + status_text = status_text_; + else + status_text = (status_code_ == 200)?"OK":"ERROR"; + + base::SStringPrintf(&response, "HTTP/1.1 %d %s", status_code_, + status_text.c_str()); + if (header_map_.size() > 0) { + for (HeaderMap::const_iterator header = header_map_.begin(); + header != header_map_.end(); + ++header) { + const CefString& key = header->first; + const CefString& value = header->second; + + if (!key.empty()) { + // Delimit with "\0" as required by net::HttpResponseHeaders. + std::string key_str(key); + std::string value_str(value); + base::StringAppendF(&response, "%c%s: %s", '\0', key_str.c_str(), + value_str.c_str()); + + if (!has_content_type_header && + key_str == net::HttpRequestHeaders::kContentType) { + has_content_type_header = true; + } + } + } + } + + if (!has_content_type_header) { + std::string mime_type; + if (!mime_type_.empty()) + mime_type = mime_type_; + else + mime_type = "text/html"; + + base::StringAppendF(&response, "%c%s: %s", '\0', + net::HttpRequestHeaders::kContentType, mime_type.c_str()); + } + + return new net::HttpResponseHeaders(response); +} + +void CefResponseImpl::SetResponseHeaders( + const net::HttpResponseHeaders& headers) { + base::AutoLock lock_scope(lock_); + + header_map_.empty(); + + void* iter = NULL; + std::string name, value; + while (headers.EnumerateHeaderLines(&iter, &name, &value)) + header_map_.insert(std::make_pair(name, value)); + + status_code_ = headers.response_code(); + status_text_ = headers.GetStatusText(); + + std::string mime_type; + if (headers.GetMimeType(&mime_type)) + mime_type_ = mime_type; +} + +void CefResponseImpl::Set(const blink::WebURLResponse& response) { + DCHECK(!response.isNull()); + + base::AutoLock lock_scope(lock_); + CHECK_READONLY_RETURN_VOID(); + + blink::WebString str; + status_code_ = response.httpStatusCode(); + str = response.httpStatusText(); + status_text_ = CefString(str); + str = response.mimeType(); + mime_type_ = CefString(str); + + class HeaderVisitor : public blink::WebHTTPHeaderVisitor { + public: + explicit HeaderVisitor(HeaderMap* map) : map_(map) {} + + void visitHeader(const blink::WebString& name, + const blink::WebString& value) override { + map_->insert(std::make_pair(base::string16(name), + base::string16(value))); + } + + private: + HeaderMap* map_; + }; + + HeaderVisitor visitor(&header_map_); + response.visitHTTPHeaderFields(&visitor); +} + +void CefResponseImpl::SetReadOnly(bool read_only) { + base::AutoLock lock_scope(lock_); + read_only_ = read_only; +} diff --git a/libcef/common/response_impl.h b/libcef/common/response_impl.h new file mode 100644 index 000000000..df78a0c11 --- /dev/null +++ b/libcef/common/response_impl.h @@ -0,0 +1,57 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_RESPONSE_IMPL_H_ +#define CEF_LIBCEF_COMMON_RESPONSE_IMPL_H_ +#pragma once + +#include "include/cef_response.h" + +#include "base/synchronization/lock.h" + +namespace net { +class HttpResponseHeaders; +} + +namespace blink { +class WebURLResponse; +} + +// Implementation of CefResponse. +class CefResponseImpl : public CefResponse { + public: + CefResponseImpl(); + + // CefResponse methods. + bool IsReadOnly() override; + int GetStatus() override; + void SetStatus(int status) override; + CefString GetStatusText() override; + void SetStatusText(const CefString& statusText) override; + CefString GetMimeType() override; + void SetMimeType(const CefString& mimeType) override; + CefString GetHeader(const CefString& name) override; + void GetHeaderMap(HeaderMap& headerMap) override; + void SetHeaderMap(const HeaderMap& headerMap) override; + + net::HttpResponseHeaders* GetResponseHeaders(); + void SetResponseHeaders(const net::HttpResponseHeaders& headers); + + void Set(const blink::WebURLResponse& response); + + void SetReadOnly(bool read_only); + + protected: + int status_code_; + CefString status_text_; + CefString mime_type_; + HeaderMap header_map_; + bool read_only_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefResponseImpl); +}; + +#endif // CEF_LIBCEF_COMMON_RESPONSE_IMPL_H_ diff --git a/libcef/common/response_manager.cc b/libcef/common/response_manager.cc new file mode 100644 index 000000000..b7f6efcb7 --- /dev/null +++ b/libcef/common/response_manager.cc @@ -0,0 +1,58 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/common/response_manager.h" +#include "libcef/common/cef_messages.h" + +#include "base/logging.h" + +CefResponseManager::CefResponseManager() + : next_request_id_(0) { +} + +int CefResponseManager::GetNextRequestId() { + DCHECK(CalledOnValidThread()); + return ++next_request_id_; +} + +int CefResponseManager::RegisterHandler(CefRefPtr handler) { + DCHECK(CalledOnValidThread()); + int request_id = GetNextRequestId(); + TRACE_EVENT_ASYNC_BEGIN1("libcef", "CefResponseManager::Handler", request_id, "request_id", request_id); + handlers_.insert(std::make_pair(request_id, handler)); + return request_id; +} + +bool CefResponseManager::RunHandler(const Cef_Response_Params& params) { + DCHECK(CalledOnValidThread()); + DCHECK_GT(params.request_id, 0); + HandlerMap::iterator it = handlers_.find(params.request_id); + if (it != handlers_.end()) { + TRACE_EVENT0("libcef", "CefResponseManager::RunHandler"); + it->second->OnResponse(params); + handlers_.erase(it); + TRACE_EVENT_ASYNC_END1("libcef", "CefResponseManager::Handler", params.request_id, "success", 1); + return true; + } + TRACE_EVENT_ASYNC_END1("libcef", "CefResponseManager::Handler", params.request_id, "success", 0); + return false; +} + +void CefResponseManager::RegisterAckHandler(int request_id, + CefRefPtr handler) { + DCHECK(CalledOnValidThread()); + ack_handlers_.insert(std::make_pair(request_id, handler)); +} + +bool CefResponseManager::RunAckHandler(int request_id) { + DCHECK(CalledOnValidThread()); + DCHECK_GT(request_id, 0); + AckHandlerMap::iterator it = ack_handlers_.find(request_id); + if (it != ack_handlers_.end()) { + it->second->OnResponseAck(); + ack_handlers_.erase(it); + return true; + } + return false; +} diff --git a/libcef/common/response_manager.h b/libcef/common/response_manager.h new file mode 100644 index 000000000..ee383cc83 --- /dev/null +++ b/libcef/common/response_manager.h @@ -0,0 +1,62 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_RESPONSE_MANAGER_H_ +#define CEF_LIBCEF_COMMON_RESPONSE_MANAGER_H_ +#pragma once + +#include +#include "include/cef_base.h" +#include "base/threading/non_thread_safe.h" + +struct Cef_Response_Params; + +// This class is not thread-safe. +class CefResponseManager : base::NonThreadSafe { + public: + // Used for handling response messages. + class Handler : public virtual CefBase { + public: + virtual void OnResponse(const Cef_Response_Params& params) =0; + }; + + // Used for handling response ack messages. + class AckHandler : public virtual CefBase { + public: + virtual void OnResponseAck() =0; + }; + + CefResponseManager(); + + // Returns the next unique request id. + int GetNextRequestId(); + + // Register a response handler and return the unique request id. + int RegisterHandler(CefRefPtr handler); + + // Run the response handler for the specified request id. Returns true if a + // handler was run. + bool RunHandler(const Cef_Response_Params& params); + + // Register a response ack handler for the specified request id. + void RegisterAckHandler(int request_id, CefRefPtr handler); + + // Run the response ack handler for the specified request id. Returns true if + // a handler was run. + bool RunAckHandler(int request_id); + + private: + // Used for generating unique request ids. + int next_request_id_; + + // Map of unique request ids to Handler references. + typedef std::map > HandlerMap; + HandlerMap handlers_; + + // Map of unique request ids to AckHandler references. + typedef std::map > AckHandlerMap; + AckHandlerMap ack_handlers_; +}; + +#endif // CEF_LIBCEF_COMMON_RESPONSE_MANAGER_H_ diff --git a/libcef/common/scheme_registrar_impl.cc b/libcef/common/scheme_registrar_impl.cc new file mode 100644 index 000000000..26e841742 --- /dev/null +++ b/libcef/common/scheme_registrar_impl.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/common/scheme_registrar_impl.h" + +#include + +#include "libcef/common/content_client.h" + +#include "base/bind.h" +#include "base/logging.h" + +CefSchemeRegistrarImpl::CefSchemeRegistrarImpl() + : supported_thread_id_(base::PlatformThread::CurrentId()) { +} + +bool CefSchemeRegistrarImpl::AddCustomScheme( + const CefString& scheme_name, + bool is_standard, + bool is_local, + bool is_display_isolated) { + if (!VerifyContext()) + return false; + + const std::string& scheme = scheme_name; + + if (is_standard) + standard_schemes_.push_back(scheme); + + CefContentClient::SchemeInfo scheme_info = { + scheme, is_standard, is_local, is_display_isolated}; + CefContentClient::Get()->AddCustomScheme(scheme_info); + + return true; +} + +void CefSchemeRegistrarImpl::GetStandardSchemes( + std::vector* standard_schemes) { + if (!VerifyContext()) + return; + + if (standard_schemes_.empty()) + return; + + standard_schemes->insert(standard_schemes->end(), standard_schemes_.begin(), + standard_schemes_.end()); +} + +bool CefSchemeRegistrarImpl::VerifyRefCount() { + return HasOneRef(); +} + +void CefSchemeRegistrarImpl::Detach() { + if (VerifyContext()) + supported_thread_id_ = base::kInvalidThreadId; +} + +bool CefSchemeRegistrarImpl::VerifyContext() { + if (base::PlatformThread::CurrentId() != supported_thread_id_) { + // This object should only be accessed from the thread that created it. + NOTREACHED(); + return false; + } + + return true; +} diff --git a/libcef/common/scheme_registrar_impl.h b/libcef/common/scheme_registrar_impl.h new file mode 100644 index 000000000..aeb3c01aa --- /dev/null +++ b/libcef/common/scheme_registrar_impl.h @@ -0,0 +1,46 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_SCHEME_REGISTRAR_IMPL_H_ +#define CEF_LIBCEF_COMMON_SCHEME_REGISTRAR_IMPL_H_ +#pragma once + +#include +#include + +#include "include/cef_scheme.h" + +#include "base/threading/platform_thread.h" + +class CefSchemeRegistrarImpl : public CefSchemeRegistrar { + public: + CefSchemeRegistrarImpl(); + + // CefSchemeRegistrar methods. + bool AddCustomScheme(const CefString& scheme_name, + bool is_standard, + bool is_local, + bool is_display_isolated) override; + + void GetStandardSchemes(std::vector* standard_schemes); + + // Verify that only a single reference exists to all CefSchemeRegistrarImpl + // objects. + bool VerifyRefCount(); + + void Detach(); + + private: + // Verify that the object is being accessed from the correct thread. + bool VerifyContext(); + + base::PlatformThreadId supported_thread_id_; + + std::vector standard_schemes_; + + IMPLEMENT_REFCOUNTING(CefSchemeRegistrarImpl); + DISALLOW_COPY_AND_ASSIGN(CefSchemeRegistrarImpl); +}; + +#endif // CEF_LIBCEF_COMMON_SCHEME_REGISTRAR_IMPL_H_ diff --git a/libcef/common/scheme_registration.cc b/libcef/common/scheme_registration.cc new file mode 100644 index 000000000..fa505294e --- /dev/null +++ b/libcef/common/scheme_registration.cc @@ -0,0 +1,68 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/scheme_registration.h" +#include "libcef/common/content_client.h" + +#include "content/public/common/url_constants.h" +#include "url/url_constants.h" + +namespace scheme { + +void AddInternalSchemes(std::vector* standard_schemes) { + static CefContentClient::SchemeInfo schemes[] = { + { content::kChromeUIScheme, true, true, true }, + { content::kChromeDevToolsScheme, true, false, true } + }; + + CefContentClient* client = CefContentClient::Get(); + for (size_t i = 0; i < sizeof(schemes) / sizeof(schemes[0]); ++i) { + if (schemes[0].is_standard) + standard_schemes->push_back(schemes[i].scheme_name); + client->AddCustomScheme(schemes[i]); + } +} + +bool IsInternalHandledScheme(const std::string& scheme) { + static const char* schemes[] = { + url::kBlobScheme, + content::kChromeDevToolsScheme, + content::kChromeUIScheme, + url::kDataScheme, + url::kFileScheme, + url::kFileSystemScheme, + }; + + for (size_t i = 0; i < sizeof(schemes) / sizeof(schemes[0]); ++i) { + if (scheme == schemes[i]) + return true; + } + + return false; +} + +bool IsInternalProtectedScheme(const std::string& scheme) { + // Some of these values originate from StoragePartitionImplMap::Get() in + // content/browser/storage_partition_impl_map.cc and are modified by + // InstallInternalProtectedHandlers(). + static const char* schemes[] = { + url::kBlobScheme, + content::kChromeUIScheme, + url::kDataScheme, + url::kFileScheme, + url::kFileSystemScheme, +#if !defined(DISABLE_FTP_SUPPORT) + url::kFtpScheme, +#endif + }; + + for (size_t i = 0; i < sizeof(schemes) / sizeof(schemes[0]); ++i) { + if (scheme == schemes[i]) + return true; + } + + return false; +} + +} // namespace scheme diff --git a/libcef/common/scheme_registration.h b/libcef/common/scheme_registration.h new file mode 100644 index 000000000..7252f24d8 --- /dev/null +++ b/libcef/common/scheme_registration.h @@ -0,0 +1,29 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_SCHEME_REGISTRATION_H_ +#define CEF_LIBCEF_COMMON_SCHEME_REGISTRATION_H_ +#pragma once + +#include +#include + +namespace scheme { + +// Add internal schemes. +void AddInternalSchemes(std::vector* standard_schemes); + +// Returns true if the specified |scheme| is handled internally. +bool IsInternalHandledScheme(const std::string& scheme); + +// Returns true if the specified |scheme| is handled internally and should not +// be explicitly registered or unregistered with the URLRequestJobFactory. A +// registered handler for one of these schemes (like "chrome") may still be +// triggered via chaining from an existing ProtocolHandler. |scheme| should +// always be a lower-case string. +bool IsInternalProtectedScheme(const std::string& scheme); + +} // namespace scheme + +#endif // CEF_LIBCEF_COMMON_SCHEME_REGISTRATION_H_ diff --git a/libcef/common/string_list_impl.cc b/libcef/common/string_list_impl.cc new file mode 100644 index 000000000..8db72cbeb --- /dev/null +++ b/libcef/common/string_list_impl.cc @@ -0,0 +1,57 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include "include/internal/cef_string_list.h" +#include "base/logging.h" + +typedef std::vector StringList; + +CEF_EXPORT cef_string_list_t cef_string_list_alloc() { + return new StringList; +} + +CEF_EXPORT int cef_string_list_size(cef_string_list_t list) { + DCHECK(list); + StringList* impl = reinterpret_cast(list); + return impl->size(); +} + +CEF_EXPORT int cef_string_list_value(cef_string_list_t list, int index, + cef_string_t* value) { + DCHECK(list); + DCHECK(value); + StringList* impl = reinterpret_cast(list); + DCHECK_GE(index, 0); + DCHECK_LT(index, static_cast(impl->size())); + if (index < 0 || index >= static_cast(impl->size())) + return false; + const CefString& str = (*impl)[index]; + return cef_string_copy(str.c_str(), str.length(), value); +} + +CEF_EXPORT void cef_string_list_append(cef_string_list_t list, + const cef_string_t* value) { + DCHECK(list); + StringList* impl = reinterpret_cast(list); + impl->push_back(CefString(value)); +} + +CEF_EXPORT void cef_string_list_clear(cef_string_list_t list) { + DCHECK(list); + StringList* impl = reinterpret_cast(list); + impl->clear(); +} + +CEF_EXPORT void cef_string_list_free(cef_string_list_t list) { + DCHECK(list); + StringList* impl = reinterpret_cast(list); + delete impl; +} + +CEF_EXPORT cef_string_list_t cef_string_list_copy(cef_string_list_t list) { + DCHECK(list); + StringList* impl = reinterpret_cast(list); + return new StringList(*impl); +} diff --git a/libcef/common/string_map_impl.cc b/libcef/common/string_map_impl.cc new file mode 100644 index 000000000..9538ab05e --- /dev/null +++ b/libcef/common/string_map_impl.cc @@ -0,0 +1,92 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include "include/internal/cef_string_map.h" +#include "base/logging.h" + +typedef std::map StringMap; + +CEF_EXPORT cef_string_map_t cef_string_map_alloc() { + return new StringMap; +} + +CEF_EXPORT int cef_string_map_size(cef_string_map_t map) { + DCHECK(map); + StringMap* impl = reinterpret_cast(map); + return impl->size(); +} + +CEF_EXPORT int cef_string_map_find(cef_string_map_t map, + const cef_string_t* key, + cef_string_t* value) { + DCHECK(map); + DCHECK(value); + StringMap* impl = reinterpret_cast(map); + StringMap::const_iterator it = impl->find(CefString(key)); + if (it == impl->end()) + return 0; + + const CefString& val = it->second; + return cef_string_set(val.c_str(), val.length(), value, true); +} + +CEF_EXPORT int cef_string_map_key(cef_string_map_t map, int index, + cef_string_t* key) { + DCHECK(map); + DCHECK(key); + StringMap* impl = reinterpret_cast(map); + DCHECK_GE(index, 0); + DCHECK_LT(index, static_cast(impl->size())); + if (index < 0 || index >= static_cast(impl->size())) + return 0; + + StringMap::const_iterator it = impl->begin(); + for (int ct = 0; it != impl->end(); ++it, ct++) { + if (ct == index) + return cef_string_set(it->first.c_str(), it->first.length(), key, true); + } + return 0; +} + +CEF_EXPORT int cef_string_map_value(cef_string_map_t map, int index, + cef_string_t* value) { + DCHECK(map); + DCHECK(value); + StringMap* impl = reinterpret_cast(map); + DCHECK_GE(index, 0); + DCHECK_LT(index, static_cast(impl->size())); + if (index < 0 || index >= static_cast(impl->size())) + return 0; + + StringMap::const_iterator it = impl->begin(); + for (int ct = 0; it != impl->end(); ++it, ct++) { + if (ct == index) { + return cef_string_set(it->second.c_str(), it->second.length(), value, + true); + } + } + return 0; +} + +CEF_EXPORT int cef_string_map_append(cef_string_map_t map, + const cef_string_t* key, + const cef_string_t* value) { + DCHECK(map); + StringMap* impl = reinterpret_cast(map); + impl->insert(std::make_pair(CefString(key), CefString(value))); + return 1; +} + +CEF_EXPORT void cef_string_map_clear(cef_string_map_t map) { + DCHECK(map); + StringMap* impl = reinterpret_cast(map); + impl->clear(); +} + +CEF_EXPORT void cef_string_map_free(cef_string_map_t map) { + DCHECK(map); + StringMap* impl = reinterpret_cast(map); + delete impl; +} diff --git a/libcef/common/string_multimap_impl.cc b/libcef/common/string_multimap_impl.cc new file mode 100644 index 000000000..594ca90dd --- /dev/null +++ b/libcef/common/string_multimap_impl.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include "include/internal/cef_string_multimap.h" +#include "base/logging.h" + +typedef std::multimap StringMultimap; + +CEF_EXPORT cef_string_multimap_t cef_string_multimap_alloc() { + return new StringMultimap; +} + +CEF_EXPORT int cef_string_multimap_size(cef_string_multimap_t map) { + DCHECK(map); + StringMultimap* impl = reinterpret_cast(map); + return impl->size(); +} + +CEF_EXPORT int cef_string_multimap_find_count(cef_string_multimap_t map, + const cef_string_t* key) { + DCHECK(map); + DCHECK(key); + StringMultimap* impl = reinterpret_cast(map); + return impl->count(CefString(key)); +} + +CEF_EXPORT int cef_string_multimap_enumerate(cef_string_multimap_t map, + const cef_string_t* key, + int value_index, + cef_string_t* value) { + DCHECK(map); + DCHECK(key); + DCHECK(value); + + StringMultimap* impl = reinterpret_cast(map); + CefString key_str(key); + + DCHECK_GE(value_index, 0); + DCHECK_LT(value_index, static_cast(impl->count(key_str))); + if (value_index < 0 || value_index >= static_cast(impl->count(key_str))) + return 0; + + std::pair range_it = + impl->equal_range(key_str); + + int count = value_index; + while (count-- && range_it.first != range_it.second) + range_it.first++; + + if (range_it.first == range_it.second) + return 0; + + const CefString& val = range_it.first->second; + return cef_string_set(val.c_str(), val.length(), value, true); +} + +CEF_EXPORT int cef_string_multimap_key(cef_string_multimap_t map, int index, + cef_string_t* key) { + DCHECK(map); + DCHECK(key); + StringMultimap* impl = reinterpret_cast(map); + DCHECK_GE(index, 0); + DCHECK_LT(index, static_cast(impl->size())); + if (index < 0 || index >= static_cast(impl->size())) + return 0; + + StringMultimap::const_iterator it = impl->begin(); + for (int ct = 0; it != impl->end(); ++it, ct++) { + if (ct == index) + return cef_string_set(it->first.c_str(), it->first.length(), key, true); + } + return 0; +} + +CEF_EXPORT int cef_string_multimap_value(cef_string_multimap_t map, int index, + cef_string_t* value) { + DCHECK(map); + DCHECK(value); + StringMultimap* impl = reinterpret_cast(map); + DCHECK_GE(index, 0); + DCHECK_LT(index, static_cast(impl->size())); + if (index < 0 || index >= static_cast(impl->size())) + return 0; + + StringMultimap::const_iterator it = impl->begin(); + for (int ct = 0; it != impl->end(); ++it, ct++) { + if (ct == index) { + return cef_string_set(it->second.c_str(), it->second.length(), value, + true); + } + } + return 0; +} + +CEF_EXPORT int cef_string_multimap_append(cef_string_multimap_t map, + const cef_string_t* key, + const cef_string_t* value) { + DCHECK(map); + StringMultimap* impl = reinterpret_cast(map); + impl->insert(std::make_pair(CefString(key), CefString(value))); + return 1; +} + +CEF_EXPORT void cef_string_multimap_clear(cef_string_multimap_t map) { + DCHECK(map); + StringMultimap* impl = reinterpret_cast(map); + impl->clear(); +} + +CEF_EXPORT void cef_string_multimap_free(cef_string_multimap_t map) { + DCHECK(map); + StringMultimap* impl = reinterpret_cast(map); + delete impl; +} diff --git a/libcef/common/string_types_impl.cc b/libcef/common/string_types_impl.cc new file mode 100644 index 000000000..a893c4e2b --- /dev/null +++ b/libcef/common/string_types_impl.cc @@ -0,0 +1,277 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/internal/cef_string_types.h" +#include +#include "base/logging.h" +#include "base/strings/string16.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" + +namespace { + +void string_wide_dtor(wchar_t* str) { + delete [] str; +} + +void string_utf8_dtor(char* str) { + delete [] str; +} + +void string_utf16_dtor(char16* str) { + delete [] str; +} + +// Originally from base/strings/utf_string_conversions.cc +std::wstring ASCIIToWide(const base::StringPiece& ascii) { + DCHECK(base::IsStringASCII(ascii)) << ascii; + return std::wstring(ascii.begin(), ascii.end()); +} + +} // namespace + +CEF_EXPORT int cef_string_wide_set(const wchar_t* src, size_t src_len, + cef_string_wide_t* output, int copy) { + cef_string_wide_clear(output); + + if (copy) { + if (src && src_len > 0) { + output->str = new wchar_t[src_len+1]; + if (!output->str) + return 0; + + memcpy(output->str, src, src_len * sizeof(wchar_t)); + output->str[src_len] = 0; + output->length = src_len; + output->dtor = string_wide_dtor; + } + } else { + output->str = const_cast(src); + output->length = src_len; + output->dtor = NULL; + } + return 1; +} + +CEF_EXPORT int cef_string_utf8_set(const char* src, size_t src_len, + cef_string_utf8_t* output, int copy) { + cef_string_utf8_clear(output); + if (copy) { + if (src && src_len > 0) { + output->str = new char[src_len+1]; + if (!output->str) + return 0; + + memcpy(output->str, src, src_len * sizeof(char)); + output->str[src_len] = 0; + output->length = src_len; + output->dtor = string_utf8_dtor; + } + } else { + output->str = const_cast(src); + output->length = src_len; + output->dtor = NULL; + } + return 1; +} + +CEF_EXPORT int cef_string_utf16_set(const char16* src, size_t src_len, + cef_string_utf16_t* output, int copy) { + cef_string_utf16_clear(output); + + if (copy) { + if (src && src_len > 0) { + output->str = new char16[src_len+1]; + if (!output->str) + return 0; + + memcpy(output->str, src, src_len * sizeof(char16)); + output->str[src_len] = 0; + output->length = src_len; + output->dtor = string_utf16_dtor; + } + } else { + output->str = const_cast(src); + output->length = src_len; + output->dtor = NULL; + } + return 1; +} + +CEF_EXPORT void cef_string_wide_clear(cef_string_wide_t* str) { + DCHECK(str != NULL); + if (str->dtor && str->str) + str->dtor(str->str); + + str->str = NULL; + str->length = 0; + str->dtor = NULL; +} + +CEF_EXPORT void cef_string_utf8_clear(cef_string_utf8_t* str) { + DCHECK(str != NULL); + if (str->dtor && str->str) + str->dtor(str->str); + + str->str = NULL; + str->length = 0; + str->dtor = NULL; +} + +CEF_EXPORT void cef_string_utf16_clear(cef_string_utf16_t* str) { + DCHECK(str != NULL); + if (str->dtor && str->str) + str->dtor(str->str); + + str->str = NULL; + str->length = 0; + str->dtor = NULL; +} + +CEF_EXPORT int cef_string_wide_cmp(const cef_string_wide_t* str1, + const cef_string_wide_t* str2) { + if (str1->length == 0 && str2->length == 0) + return 0; + int r = wcsncmp(str1->str, str2->str, std::min(str1->length, str2->length)); + if (r == 0) { + if (str1->length > str2->length) + return 1; + else if (str1->length < str2->length) + return -1; + } + return r; +} + +CEF_EXPORT int cef_string_utf8_cmp(const cef_string_utf8_t* str1, + const cef_string_utf8_t* str2) { + if (str1->length == 0 && str2->length == 0) + return 0; + int r = strncmp(str1->str, str2->str, std::min(str1->length, str2->length)); + if (r == 0) { + if (str1->length > str2->length) + return 1; + else if (str1->length < str2->length) + return -1; + } + return r; +} + +CEF_EXPORT int cef_string_utf16_cmp(const cef_string_utf16_t* str1, + const cef_string_utf16_t* str2) { + if (str1->length == 0 && str2->length == 0) + return 0; +#if defined(WCHAR_T_IS_UTF32) + int r = base::c16memcmp(str1->str, str2->str, std::min(str1->length, + str2->length)); +#else + int r = wcsncmp(str1->str, str2->str, std::min(str1->length, str2->length)); +#endif + if (r == 0) { + if (str1->length > str2->length) + return 1; + else if (str1->length < str2->length) + return -1; + } + return r; +} + +CEF_EXPORT int cef_string_wide_to_utf8(const wchar_t* src, size_t src_len, + cef_string_utf8_t* output) { + std::string str; + bool ret = base::WideToUTF8(src, src_len, &str); + if (!cef_string_utf8_set(str.c_str(), str.length(), output, true)) + return false; + return ret; +} + +CEF_EXPORT int cef_string_utf8_to_wide(const char* src, size_t src_len, + cef_string_wide_t* output) { + std::wstring str; + bool ret = base::UTF8ToWide(src, src_len, &str); + if (!cef_string_wide_set(str.c_str(), str.length(), output, true)) + return false; + return ret; +} + +CEF_EXPORT int cef_string_wide_to_utf16(const wchar_t* src, size_t src_len, + cef_string_utf16_t* output) { + base::string16 str; + bool ret = base::WideToUTF16(src, src_len, &str); + if (!cef_string_utf16_set(str.c_str(), str.length(), output, true)) + return false; + return ret; +} + +CEF_EXPORT int cef_string_utf16_to_wide(const char16* src, size_t src_len, + cef_string_wide_t* output) { + std::wstring str; + bool ret = base::UTF16ToWide(src, src_len, &str); + if (!cef_string_wide_set(str.c_str(), str.length(), output, true)) + return false; + return ret; +} + +CEF_EXPORT int cef_string_utf8_to_utf16(const char* src, size_t src_len, + cef_string_utf16_t* output) { + base::string16 str; + bool ret = base::UTF8ToUTF16(src, src_len, &str); + if (!cef_string_utf16_set(str.c_str(), str.length(), output, true)) + return false; + return ret; +} + +CEF_EXPORT int cef_string_utf16_to_utf8(const char16* src, size_t src_len, + cef_string_utf8_t* output) { + std::string str; + bool ret = base::UTF16ToUTF8(src, src_len, &str); + if (!cef_string_utf8_set(str.c_str(), str.length(), output, true)) + return false; + return ret; +} + +CEF_EXPORT int cef_string_ascii_to_wide(const char* src, size_t src_len, + cef_string_wide_t* output) { + const std::wstring& str = ASCIIToWide(std::string(src, src_len)); + return cef_string_wide_set(str.c_str(), str.length(), output, true); +} + +CEF_EXPORT int cef_string_ascii_to_utf16(const char* src, size_t src_len, + cef_string_utf16_t* output) { + const base::string16& str = base::ASCIIToUTF16(std::string(src, src_len)); + return cef_string_utf16_set(str.c_str(), str.length(), output, true); +} + +CEF_EXPORT cef_string_userfree_wide_t cef_string_userfree_wide_alloc() { + cef_string_wide_t* s = new cef_string_wide_t; + memset(s, 0, sizeof(cef_string_wide_t)); + return s; +} + +CEF_EXPORT cef_string_userfree_utf8_t cef_string_userfree_utf8_alloc() { + cef_string_utf8_t* s = new cef_string_utf8_t; + memset(s, 0, sizeof(cef_string_utf8_t)); + return s; +} + +CEF_EXPORT cef_string_userfree_utf16_t cef_string_userfree_utf16_alloc() { + cef_string_utf16_t* s = new cef_string_utf16_t; + memset(s, 0, sizeof(cef_string_utf16_t)); + return s; +} + +CEF_EXPORT void cef_string_userfree_wide_free(cef_string_userfree_wide_t str) { + cef_string_wide_clear(str); + delete str; +} + +CEF_EXPORT void cef_string_userfree_utf8_free(cef_string_userfree_utf8_t str) { + cef_string_utf8_clear(str); + delete str; +} + +CEF_EXPORT void cef_string_userfree_utf16_free( + cef_string_userfree_utf16_t str) { + cef_string_utf16_clear(str); + delete str; +} diff --git a/libcef/common/task_impl.cc b/libcef/common/task_impl.cc new file mode 100644 index 000000000..c7832ae1c --- /dev/null +++ b/libcef/common/task_impl.cc @@ -0,0 +1,38 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "include/cef_task.h" +#include "libcef/common/task_runner_impl.h" + +#include "base/bind.h" +#include "base/location.h" + +bool CefCurrentlyOn(CefThreadId threadId) { + scoped_refptr task_runner = + CefTaskRunnerImpl::GetTaskRunner(threadId); + if (task_runner.get()) + return task_runner->RunsTasksOnCurrentThread(); + return false; +} + +bool CefPostTask(CefThreadId threadId, CefRefPtr task) { + scoped_refptr task_runner = + CefTaskRunnerImpl::GetTaskRunner(threadId); + if (task_runner.get()) { + return task_runner->PostTask(FROM_HERE, + base::Bind(&CefTask::Execute, task.get())); + } + return false; +} + +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, int64 delay_ms) { + scoped_refptr task_runner = + CefTaskRunnerImpl::GetTaskRunner(threadId); + if (task_runner.get()) { + return task_runner->PostDelayedTask(FROM_HERE, + base::Bind(&CefTask::Execute, task.get()), + base::TimeDelta::FromMilliseconds(delay_ms)); + } + return false; +} diff --git a/libcef/common/task_runner_impl.cc b/libcef/common/task_runner_impl.cc new file mode 100644 index 000000000..a6f269913 --- /dev/null +++ b/libcef/common/task_runner_impl.cc @@ -0,0 +1,147 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/task_runner_impl.h" +#include "libcef/common/content_client.h" +#include "libcef/renderer/content_renderer_client.h" + +#include "base/bind.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "base/message_loop/message_loop_proxy.h" +#include "content/public/browser/browser_thread.h" + +using content::BrowserThread; + +// CefTaskRunner + +// static +CefRefPtr CefTaskRunner::GetForCurrentThread() { + scoped_refptr task_runner = + CefTaskRunnerImpl::GetCurrentTaskRunner(); + if (task_runner.get()) + return new CefTaskRunnerImpl(task_runner); + return NULL; +} + +// static +CefRefPtr CefTaskRunner::GetForThread(CefThreadId threadId) { + scoped_refptr task_runner = + CefTaskRunnerImpl::GetTaskRunner(threadId); + if (task_runner.get()) + return new CefTaskRunnerImpl(task_runner); + + LOG(WARNING) << "Invalid thread id " << threadId; + return NULL; +} + + +// CefTaskRunnerImpl + +CefTaskRunnerImpl::CefTaskRunnerImpl( + scoped_refptr task_runner) + : task_runner_(task_runner) { + DCHECK(task_runner_.get()); +} + +// static +scoped_refptr + CefTaskRunnerImpl::GetTaskRunner(CefThreadId threadId) { + // Render process. + if (threadId == TID_RENDERER) { + CefContentRendererClient* client = CefContentRendererClient::Get(); + if (client) + return client->render_task_runner(); + return NULL; + } + + // Browser process. + int id = -1; + switch (threadId) { + case TID_UI: + id = BrowserThread::UI; + break; + case TID_DB: + id = BrowserThread::DB; + break; + case TID_FILE: + id = BrowserThread::FILE; + break; + case TID_FILE_USER_BLOCKING: + id = BrowserThread::FILE_USER_BLOCKING; + break; + case TID_PROCESS_LAUNCHER: + id = BrowserThread::PROCESS_LAUNCHER; + break; + case TID_CACHE: + id = BrowserThread::CACHE; + break; + case TID_IO: + id = BrowserThread::IO; + break; + default: + break; + }; + + if (id >= 0 && CefContentClient::Get()->browser() && + BrowserThread::IsMessageLoopValid(static_cast(id))) { + // Don't use BrowserThread::GetMessageLoopProxyForThread because it returns + // a new MessageLoopProxy object for each call and makes pointer equality + // testing impossible. + base::MessageLoop* message_loop = + BrowserThread::UnsafeGetMessageLoopForThread( + static_cast(id)); + if (message_loop) + return message_loop->message_loop_proxy(); + } + + return NULL; +} + +// static +scoped_refptr + CefTaskRunnerImpl::GetCurrentTaskRunner() { + scoped_refptr task_runner; + + // Check for a MessageLoopProxy. This covers all of the named browser and + // render process threads, plus a few extra. + task_runner = base::MessageLoopProxy::current(); + + if (!task_runner.get()) { + // Check for a WebWorker thread. + CefContentRendererClient* client = CefContentRendererClient::Get(); + if (client) + task_runner = client->GetCurrentTaskRunner(); + } + + return task_runner; +} + +bool CefTaskRunnerImpl::IsSame(CefRefPtr that) { + CefTaskRunnerImpl* impl = static_cast(that.get()); + return (impl && task_runner_ == impl->task_runner_); +} + +bool CefTaskRunnerImpl::BelongsToCurrentThread() { + return task_runner_->RunsTasksOnCurrentThread(); +} + +bool CefTaskRunnerImpl::BelongsToThread(CefThreadId threadId) { + scoped_refptr task_runner = + GetTaskRunner(threadId); + return (task_runner_ == task_runner); +} + +bool CefTaskRunnerImpl::PostTask(CefRefPtr task) { + return task_runner_->PostTask(FROM_HERE, + base::Bind(&CefTask::Execute, task.get())); +} + +bool CefTaskRunnerImpl::PostDelayedTask(CefRefPtr task, + int64 delay_ms) { + return task_runner_->PostDelayedTask(FROM_HERE, + base::Bind(&CefTask::Execute, task.get()), + base::TimeDelta::FromMilliseconds(delay_ms)); +} diff --git a/libcef/common/task_runner_impl.h b/libcef/common/task_runner_impl.h new file mode 100644 index 000000000..c0b3aa821 --- /dev/null +++ b/libcef/common/task_runner_impl.h @@ -0,0 +1,38 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_TASK_RUNNER_IMPL_H_ +#define CEF_LIBCEF_COMMON_TASK_RUNNER_IMPL_H_ +#pragma once + +#include "include/cef_task.h" +#include "base/sequenced_task_runner.h" + +class CefTaskRunnerImpl : public CefTaskRunner { + public: + explicit CefTaskRunnerImpl( + scoped_refptr task_runner); + + // Returns the task runner associated with |threadId|. + static scoped_refptr + GetTaskRunner(CefThreadId threadId); + // Returns the current task runner. + static scoped_refptr GetCurrentTaskRunner(); + + // CefTaskRunner methods: + bool IsSame(CefRefPtr that) override; + bool BelongsToCurrentThread() override; + bool BelongsToThread(CefThreadId threadId) override; + bool PostTask(CefRefPtr task) override; + bool PostDelayedTask(CefRefPtr task, + int64 delay_ms) override; + + private: + scoped_refptr task_runner_; + + IMPLEMENT_REFCOUNTING(CefTaskRunnerImpl); + DISALLOW_COPY_AND_ASSIGN(CefTaskRunnerImpl); +}; + +#endif // CEF_LIBCEF_COMMON_TASK_RUNNER_IMPL_H_ diff --git a/libcef/common/time_impl.cc b/libcef/common/time_impl.cc new file mode 100644 index 000000000..68100b0b3 --- /dev/null +++ b/libcef/common/time_impl.cc @@ -0,0 +1,93 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/time_util.h" + +void cef_time_to_basetime(const cef_time_t& cef_time, base::Time& time) { + base::Time::Exploded exploded; + exploded.year = cef_time.year; + exploded.month = cef_time.month; + exploded.day_of_week = cef_time.day_of_week; + exploded.day_of_month = cef_time.day_of_month; + exploded.hour = cef_time.hour; + exploded.minute = cef_time.minute; + exploded.second = cef_time.second; + exploded.millisecond = cef_time.millisecond; + time = base::Time::FromUTCExploded(exploded); +} + +void cef_time_from_basetime(const base::Time& time, cef_time_t& cef_time) { + base::Time::Exploded exploded; + time.UTCExplode(&exploded); + cef_time.year = exploded.year; + cef_time.month = exploded.month; + cef_time.day_of_week = exploded.day_of_week; + cef_time.day_of_month = exploded.day_of_month; + cef_time.hour = exploded.hour; + cef_time.minute = exploded.minute; + cef_time.second = exploded.second; + cef_time.millisecond = exploded.millisecond; +} + +CEF_EXPORT int cef_time_to_timet(const cef_time_t* cef_time, time_t* time) { + if (!cef_time || !time) + return 0; + + base::Time base_time; + cef_time_to_basetime(*cef_time, base_time); + *time = base_time.ToTimeT(); + return 1; +} + +CEF_EXPORT int cef_time_from_timet(time_t time, cef_time_t* cef_time) { + if (!cef_time) + return 0; + + base::Time base_time = base::Time::FromTimeT(time); + cef_time_from_basetime(base_time, *cef_time); + return 1; +} + +CEF_EXPORT int cef_time_to_doublet(const cef_time_t* cef_time, double* time) { + if (!cef_time || !time) + return 0; + + base::Time base_time; + cef_time_to_basetime(*cef_time, base_time); + *time = base_time.ToDoubleT(); + return 1; +} + +CEF_EXPORT int cef_time_from_doublet(double time, cef_time_t* cef_time) { + if (!cef_time) + return 0; + + base::Time base_time = base::Time::FromDoubleT(time); + cef_time_from_basetime(base_time, *cef_time); + return 1; +} + +CEF_EXPORT int cef_time_now(cef_time_t* cef_time) { + if (!cef_time) + return 0; + + base::Time base_time = base::Time::Now(); + cef_time_from_basetime(base_time, *cef_time); + return 1; +} + +CEF_EXPORT int cef_time_delta(const cef_time_t* cef_time1, + const cef_time_t* cef_time2, + long long* delta) { + if (!cef_time1 || !cef_time2 || !delta) + return 0; + + base::Time base_time1, base_time2; + cef_time_to_basetime(*cef_time1, base_time1); + cef_time_to_basetime(*cef_time2, base_time2); + + base::TimeDelta time_delta = base_time2 - base_time1; + *delta = time_delta.InMilliseconds(); + return 1; +} diff --git a/libcef/common/time_util.h b/libcef/common/time_util.h new file mode 100644 index 000000000..8d92da7ec --- /dev/null +++ b/libcef/common/time_util.h @@ -0,0 +1,16 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_TIME_UTIL_H_ +#define CEF_LIBCEF_COMMON_TIME_UTIL_H_ +#pragma once + +#include "include/internal/cef_time.h" +#include "base/time/time.h" + +// Converts cef_time_t to/from a base::Time object. +void cef_time_to_basetime(const cef_time_t& cef_time, base::Time& time); +void cef_time_from_basetime(const base::Time& time, cef_time_t& cef_time); + +#endif // CEF_LIBCEF_COMMON_TIME_UTIL_H_ diff --git a/libcef/common/tracker.cc b/libcef/common/tracker.cc new file mode 100644 index 000000000..0a94ddb10 --- /dev/null +++ b/libcef/common/tracker.cc @@ -0,0 +1,83 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/tracker.h" + +// CefTrackNode implementation. + +CefTrackNode::CefTrackNode() + : track_next_(NULL), + track_prev_(NULL) { +} + +CefTrackNode::~CefTrackNode() { +} + +void CefTrackNode::InsertTrackPrev(CefTrackNode* object) { + if (track_prev_) + track_prev_->SetTrackNext(object); + object->SetTrackNext(this); + object->SetTrackPrev(track_prev_); + track_prev_ = object; +} + +void CefTrackNode::InsertTrackNext(CefTrackNode* object) { + if (track_next_) + track_next_->SetTrackPrev(object); + object->SetTrackPrev(this); + object->SetTrackNext(track_next_); + track_next_ = object; +} + +void CefTrackNode::RemoveTracking() { + if (track_next_) + track_next_->SetTrackPrev(track_prev_); + if (track_prev_) + track_prev_->SetTrackNext(track_next_); + track_next_ = NULL; + track_prev_ = NULL; +} + + +// CefTrackManager implementation. + +CefTrackManager::CefTrackManager() + : object_count_(0) { +} + +CefTrackManager::~CefTrackManager() { + DeleteAll(); +} + +void CefTrackManager::Add(CefTrackNode* object) { + base::AutoLock lock_scope(lock_); + if (!object->IsTracked()) { + tracker_.InsertTrackNext(object); + ++object_count_; + } +} + +bool CefTrackManager::Delete(CefTrackNode* object) { + base::AutoLock lock_scope(lock_); + if (object->IsTracked()) { + object->RemoveTracking(); + delete object; + --object_count_; + return true; + } + return false; +} + +void CefTrackManager::DeleteAll() { + base::AutoLock lock_scope(lock_); + CefTrackNode* next; + do { + next = tracker_.GetTrackNext(); + if (next) { + next->RemoveTracking(); + delete next; + } + } while (next != NULL); + object_count_ = 0; +} diff --git a/libcef/common/tracker.h b/libcef/common/tracker.h new file mode 100644 index 000000000..cf6f8b8c6 --- /dev/null +++ b/libcef/common/tracker.h @@ -0,0 +1,77 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_TRACKER_H_ +#define CEF_LIBCEF_COMMON_TRACKER_H_ +#pragma once + +#include "include/cef_base.h" + +#include "base/synchronization/lock.h" + +// Class extended by objects that must be tracked. After creating a tracked +// object you should add it to the appropriate track manager. +class CefTrackNode { + public: + CefTrackNode(); + virtual ~CefTrackNode(); + + // Returns true if the object is currently being tracked. + inline bool IsTracked() { return (track_prev_ || track_next_); } + + private: + inline CefTrackNode* GetTrackPrev() { return track_prev_; } + inline void SetTrackPrev(CefTrackNode* base) { track_prev_ = base; } + inline CefTrackNode* GetTrackNext() { return track_next_; } + inline void SetTrackNext(CefTrackNode* base) { track_next_ = base; } + + // Insert a new object into the tracking list before this object. + void InsertTrackPrev(CefTrackNode* object); + + // Insert a new object into the tracking list after this object. + void InsertTrackNext(CefTrackNode* object); + + // Remove this object from the tracking list. + void RemoveTracking(); + + private: + CefTrackNode* track_next_; + CefTrackNode* track_prev_; + + friend class CefTrackManager; +}; + +// Class used to manage tracked objects. A single instance of this class +// should be created for each intended usage. Any objects that have not been +// removed by explicit calls to the Destroy() method will be removed when the +// manager object is destroyed. A manager object can be created as either a +// member variable of another class or by using lazy initialization: +// base::LazyInstance g_singleton = LAZY_INSTANCE_INITIALIZER; +class CefTrackManager : public CefBase { + public: + CefTrackManager(); + ~CefTrackManager() override; + + // Add an object to be tracked by this manager. + void Add(CefTrackNode* object); + + // Delete an object tracked by this manager. + bool Delete(CefTrackNode* object); + + // Delete all objects tracked by this manager. + void DeleteAll(); + + // Returns the number of objects currently being tracked. + inline int GetCount() { return object_count_; } + + private: + CefTrackNode tracker_; + int object_count_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(CefTrackManager); +}; + +#endif // CEF_LIBCEF_COMMON_TRACKER_H_ diff --git a/libcef/common/upload_data.cc b/libcef/common/upload_data.cc new file mode 100644 index 000000000..9fd260a39 --- /dev/null +++ b/libcef/common/upload_data.cc @@ -0,0 +1,37 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cef/libcef/common/upload_data.h" + +#include "base/logging.h" + +namespace net { + +UploadData::UploadData() + : identifier_(0), + is_chunked_(false), + last_chunk_appended_(false) { +} + +void UploadData::AppendBytes(const char* bytes, int bytes_len) { + DCHECK(!is_chunked_); + if (bytes_len > 0) { + elements_.push_back(new UploadElement()); + elements_.back()->SetToBytes(bytes, bytes_len); + } +} + +void UploadData::AppendFileRange(const base::FilePath& file_path, + uint64 offset, uint64 length, + const base::Time& expected_modification_time) { + DCHECK(!is_chunked_); + elements_.push_back(new UploadElement()); + elements_.back()->SetToFilePathRange(file_path, offset, length, + expected_modification_time); +} + +UploadData::~UploadData() { +} + +} // namespace net diff --git a/libcef/common/upload_data.h b/libcef/common/upload_data.h new file mode 100644 index 000000000..2e3b89b6b --- /dev/null +++ b/libcef/common/upload_data.h @@ -0,0 +1,84 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_UPLOAD_DATA_H_ +#define CEF_LIBCEF_COMMON_UPLOAD_DATA_H_ + +#include "libcef/common/upload_element.h" + +#include "base/basictypes.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_vector.h" +#include "base/supports_user_data.h" +#include "net/base/net_export.h" + +namespace base { +class FilePath; +class Time; +} // namespace base + +namespace net { + +//----------------------------------------------------------------------------- +// A very concrete class representing the data to be uploaded as part of a +// URLRequest. +// +// Until there is a more abstract class for this, this one derives from +// SupportsUserData to allow users to stash random data by +// key and ensure its destruction when UploadData is finally deleted. +class NET_EXPORT UploadData + : public base::RefCounted, + public base::SupportsUserData { + public: + UploadData(); + + void AppendBytes(const char* bytes, int bytes_len); + + void AppendFileRange(const base::FilePath& file_path, + uint64 offset, uint64 length, + const base::Time& expected_modification_time); + + // Initializes the object to send chunks of upload data over time rather + // than all at once. Chunked data may only contain bytes, not files. + void set_is_chunked(bool set) { is_chunked_ = set; } + bool is_chunked() const { return is_chunked_; } + + // set_last_chunk_appended() is only used for serialization. + void set_last_chunk_appended(bool set) { last_chunk_appended_ = set; } + bool last_chunk_appended() const { return last_chunk_appended_; } + + const ScopedVector& elements() const { + return elements_; + } + + ScopedVector* elements_mutable() { + return &elements_; + } + + void swap_elements(ScopedVector* elements) { + elements_.swap(*elements); + } + + // Identifies a particular upload instance, which is used by the cache to + // formulate a cache key. This value should be unique across browser + // sessions. A value of 0 is used to indicate an unspecified identifier. + void set_identifier(int64 id) { identifier_ = id; } + int64 identifier() const { return identifier_; } + + private: + friend class base::RefCounted; + + ~UploadData() override; + + ScopedVector elements_; + int64 identifier_; + bool is_chunked_; + bool last_chunk_appended_; + + DISALLOW_COPY_AND_ASSIGN(UploadData); +}; + +} // namespace net + +#endif // CEF_LIBCEF_COMMON_UPLOAD_DATA_H_ diff --git a/libcef/common/upload_element.cc b/libcef/common/upload_element.cc new file mode 100644 index 000000000..bb5e2b897 --- /dev/null +++ b/libcef/common/upload_element.cc @@ -0,0 +1,25 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/common/upload_element.h" + +#include + +#include "net/base/file_stream.h" +#include "net/base/net_errors.h" + +namespace net { + +UploadElement::UploadElement() + : type_(TYPE_BYTES), + bytes_start_(NULL), + bytes_length_(0), + file_range_offset_(0), + file_range_length_(kuint64max) { +} + +UploadElement::~UploadElement() { +} + +} // namespace net diff --git a/libcef/common/upload_element.h b/libcef/common/upload_element.h new file mode 100644 index 000000000..2b63a0df3 --- /dev/null +++ b/libcef/common/upload_element.h @@ -0,0 +1,110 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_UPLOAD_ELEMENT_H_ +#define CEF_LIBCEF_COMMON_UPLOAD_ELEMENT_H_ + +#include + +#include "base/basictypes.h" +#include "base/files/file_path.h" +#include "base/time/time.h" +#include "net/base/net_export.h" + +namespace net { + +// A class representing an element contained by UploadData. +class NET_EXPORT UploadElement { + public: + enum Type { + TYPE_BYTES, + TYPE_FILE, + }; + + UploadElement(); + ~UploadElement(); + + Type type() const { return type_; } + + const char* bytes() const { return bytes_start_ ? bytes_start_ : &buf_[0]; } + uint64 bytes_length() const { return buf_.size() + bytes_length_; } + const base::FilePath& file_path() const { return file_path_; } + uint64 file_range_offset() const { return file_range_offset_; } + uint64 file_range_length() const { return file_range_length_; } + // If NULL time is returned, we do not do the check. + const base::Time& expected_file_modification_time() const { + return expected_file_modification_time_; + } + + void SetToBytes(const char* bytes, int bytes_len) { + type_ = TYPE_BYTES; + buf_.assign(bytes, bytes + bytes_len); + } + + // This does not copy the given data and the caller should make sure + // the data is secured somewhere else (e.g. by attaching the data + // using SetUserData). + void SetToSharedBytes(const char* bytes, int bytes_len) { + type_ = TYPE_BYTES; + bytes_start_ = bytes; + bytes_length_ = bytes_len; + } + + void SetToFilePath(const base::FilePath& path) { + SetToFilePathRange(path, 0, kuint64max, base::Time()); + } + + // If expected_modification_time is NULL, we do not check for the file + // change. Also note that the granularity for comparison is time_t, not + // the full precision. + void SetToFilePathRange(const base::FilePath& path, + uint64 offset, uint64 length, + const base::Time& expected_modification_time) { + type_ = TYPE_FILE; + file_path_ = path; + file_range_offset_ = offset; + file_range_length_ = length; + expected_file_modification_time_ = expected_modification_time; + } + + private: + Type type_; + std::vector buf_; + const char* bytes_start_; + uint64 bytes_length_; + base::FilePath file_path_; + uint64 file_range_offset_; + uint64 file_range_length_; + base::Time expected_file_modification_time_; + + DISALLOW_COPY_AND_ASSIGN(UploadElement); +}; + +#if defined(UNIT_TEST) +inline bool operator==(const UploadElement& a, + const UploadElement& b) { + if (a.type() != b.type()) + return false; + if (a.type() == UploadElement::TYPE_BYTES) + return a.bytes_length() == b.bytes_length() && + memcmp(a.bytes(), b.bytes(), b.bytes_length()) == 0; + if (a.type() == UploadElement::TYPE_FILE) { + return a.file_path() == b.file_path() && + a.file_range_offset() == b.file_range_offset() && + a.file_range_length() == b.file_range_length() && + a.expected_file_modification_time() == + b.expected_file_modification_time(); + } + return false; +} + +inline bool operator!=(const UploadElement& a, + const UploadElement& b) { + return !(a == b); +} +#endif // defined(UNIT_TEST) + +} // namespace net + +#endif // CEF_LIBCEF_COMMON_UPLOAD_ELEMENT_H_ diff --git a/libcef/common/url_impl.cc b/libcef/common/url_impl.cc new file mode 100644 index 000000000..d2660fcf2 --- /dev/null +++ b/libcef/common/url_impl.cc @@ -0,0 +1,87 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include +#include "include/cef_url.h" +#include "net/base/mime_util.h" +#include "url/gurl.h" + +bool CefParseURL(const CefString& url, + CefURLParts& parts) { + GURL gurl(url.ToString()); + if (!gurl.is_valid()) + return false; + + CefString(&parts.spec).FromString(gurl.spec()); + CefString(&parts.scheme).FromString(gurl.scheme()); + CefString(&parts.username).FromString(gurl.username()); + CefString(&parts.password).FromString(gurl.password()); + CefString(&parts.host).FromString(gurl.host()); + CefString(&parts.origin).FromString(gurl.GetOrigin().spec()); + CefString(&parts.port).FromString(gurl.port()); + CefString(&parts.path).FromString(gurl.path()); + CefString(&parts.query).FromString(gurl.query()); + + return true; +} + +bool CefCreateURL(const CefURLParts& parts, + CefString& url) { + std::string spec = CefString(parts.spec.str, parts.spec.length, false); + std::string scheme = CefString(parts.scheme.str, parts.scheme.length, false); + std::string username = + CefString(parts.username.str, parts.username.length, false); + std::string password = + CefString(parts.password.str, parts.password.length, false); + std::string host = CefString(parts.host.str, parts.host.length, false); + std::string port = CefString(parts.port.str, parts.port.length, false); + std::string path = CefString(parts.path.str, parts.path.length, false); + std::string query = CefString(parts.query.str, parts.query.length, false); + + GURL gurl; + if (!spec.empty()) { + gurl = GURL(spec); + } else if (!scheme.empty() && !host.empty()) { + std::stringstream ss; + ss << scheme << "://"; + if (!username.empty()) { + ss << username; + if (!password.empty()) + ss << ":" << password; + ss << "@"; + } + ss << host; + if (!port.empty()) + ss << ":" << port; + if (!path.empty()) + ss << path; + if (!query.empty()) + ss << "?" << query; + gurl = GURL(ss.str()); + } + + if (gurl.is_valid()) { + url = gurl.spec(); + return true; + } + + return false; +} + +CefString CefGetMimeType(const CefString& extension) { + std::string mime_type; + net::GetMimeTypeFromExtension(extension, &mime_type); + return mime_type; +} + +void CefGetExtensionsForMimeType(const CefString& mime_type, + std::vector& extensions) { + typedef std::vector VectorType; + VectorType ext; + net::GetExtensionsForMimeType(mime_type, &ext); + VectorType::const_iterator it = ext.begin(); + for (; it != ext.end(); ++it) + extensions.push_back(*it); +} + diff --git a/libcef/common/urlrequest_impl.cc b/libcef/common/urlrequest_impl.cc new file mode 100644 index 000000000..958722fd4 --- /dev/null +++ b/libcef/common/urlrequest_impl.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "include/cef_urlrequest.h" +#include "libcef/browser/browser_urlrequest_impl.h" +#include "libcef/common/content_client.h" +#include "libcef/renderer/render_urlrequest_impl.h" + +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "content/public/common/content_client.h" + +// static +CefRefPtr CefURLRequest::Create( + CefRefPtr request, + CefRefPtr client) { + if (!request.get() || !client.get()) { + NOTREACHED() << "called with invalid parameters"; + return NULL; + } + + if (!base::MessageLoop::current()) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + if (CefContentClient::Get()->browser()) { + // In the browser process. + CefRefPtr impl = + new CefBrowserURLRequest(request, client); + if (impl->Start()) + return impl.get(); + return NULL; + } else if (CefContentClient::Get()->renderer()) { + // In the render process. + CefRefPtr impl = + new CefRenderURLRequest(request, client); + if (impl->Start()) + return impl.get(); + return NULL; + } else { + NOTREACHED() << "called in unsupported process"; + return NULL; + } +} diff --git a/libcef/common/value_base.cc b/libcef/common/value_base.cc new file mode 100644 index 000000000..5ca561488 --- /dev/null +++ b/libcef/common/value_base.cc @@ -0,0 +1,201 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/value_base.h" + + +CefValueController::CefValueController() + : owner_value_(NULL), + owner_object_(NULL) { +} + +CefValueController::~CefValueController() { + // Everything should already have been removed. + DCHECK(!owner_value_ && !owner_object_); + DCHECK(reference_map_.empty()); + DCHECK(dependency_map_.empty()); +} + +void CefValueController::SetOwner(void* value, Object* object) { + DCHECK(value && object); + + // Controller should already be locked. + DCHECK(locked()); + + // Owner should only be set once. + DCHECK(!owner_value_ && !owner_object_); + + owner_value_ = value; + owner_object_ = object; +} + +void CefValueController::AddReference(void* value, Object* object) { + DCHECK(value && object); + + // Controller should already be locked. + DCHECK(locked()); + + // Controller should currently have an owner. + DCHECK(owner_value_); + + // Values should only be added once. + DCHECK(reference_map_.find(value) == reference_map_.end()); + DCHECK(value != owner_value_); + + reference_map_.insert(std::make_pair(value, object)); +} + +void CefValueController::Remove(void* value, bool notify_object) { + DCHECK(value); + + // Controller should already be locked. + DCHECK(locked()); + + // Controller should currently have an owner. + DCHECK(owner_value_); + + if (value == owner_value_) { + // Should never notify when removing the owner object. + DCHECK(!notify_object); + + owner_value_ = NULL; + owner_object_ = NULL; + + // Remove all references. + if (reference_map_.size() > 0) { + ReferenceMap::iterator it = reference_map_.begin(); + for (; it != reference_map_.end(); ++it) + it->second->OnControlRemoved(); + reference_map_.clear(); + } + + // Remove all dependencies. + dependency_map_.clear(); + } else { + ReferenceMap::iterator it = reference_map_.find(value); + if (it != reference_map_.end()) { + // Remove the reference. + if (notify_object) + it->second->OnControlRemoved(); + reference_map_.erase(it); + } + } +} + +CefValueController::Object* CefValueController::Get(void* value) { + DCHECK(value); + + // Controller should already be locked. + DCHECK(locked()); + + if (value == owner_value_) { + return owner_object_; + } else { + ReferenceMap::iterator it = reference_map_.find(value); + if (it != reference_map_.end()) + return it->second; + return NULL; + } +} + +void CefValueController::AddDependency(void* parent, void* child) { + DCHECK(parent && child && parent != child); + + // Controller should already be locked. + DCHECK(locked()); + + DependencyMap::iterator it = dependency_map_.find(parent); + if (it == dependency_map_.end()) { + // New set. + DependencySet set; + set.insert(child); + dependency_map_.insert(std::make_pair(parent, set)); + } else if (it->second.find(child) == it->second.end()) { + // Update existing set. + it->second.insert(child); + } +} + +void CefValueController::RemoveDependencies(void* value) { + DCHECK(value); + + // Controller should already be locked. + DCHECK(locked()); + + if (dependency_map_.empty()) + return; + + DependencyMap::iterator it_dependency = dependency_map_.find(value); + if (it_dependency == dependency_map_.end()) + return; + + // Start with the set of dependencies for the current value. + DependencySet remove_set = it_dependency->second; + dependency_map_.erase(it_dependency); + + DependencySet::iterator it_value; + ReferenceMap::iterator it_reference; + + while (remove_set.size() > 0) { + it_value = remove_set.begin(); + value = *it_value; + remove_set.erase(it_value); + + // Does the current value have dependencies? + it_dependency = dependency_map_.find(value); + if (it_dependency != dependency_map_.end()) { + // Append the dependency set to the remove set. + remove_set.insert(it_dependency->second.begin(), + it_dependency->second.end()); + dependency_map_.erase(it_dependency); + } + + // Does the current value have a reference? + it_reference = reference_map_.find(value); + if (it_reference != reference_map_.end()) { + // Remove the reference. + it_reference->second->OnControlRemoved(); + reference_map_.erase(it_reference); + } + } +} + +void CefValueController::TakeFrom(CefValueController* other) { + DCHECK(other); + + // Both controllers should already be locked. + DCHECK(locked()); + DCHECK(other->locked()); + + if (!other->reference_map_.empty()) { + // Transfer references from the other to this. + ReferenceMap::iterator it = other->reference_map_.begin(); + for (; it != other->reference_map_.end(); ++it) { + // References should only be added once. + DCHECK(reference_map_.find(it->first) == reference_map_.end()); + reference_map_.insert(std::make_pair(it->first, it->second)); + } + other->reference_map_.empty(); + } + + if (!other->dependency_map_.empty()) { + // Transfer dependencies from the other to this. + DependencyMap::iterator it_other = other->dependency_map_.begin(); + for (; it_other != other->dependency_map_.end(); ++it_other) { + DependencyMap::iterator it_me = dependency_map_.find(it_other->first); + if (it_me == dependency_map_.end()) { + // All children are new. + dependency_map_.insert( + std::make_pair(it_other->first, it_other->second)); + } else { + // Evaluate each child. + DependencySet::iterator it_other_set = it_other->second.begin(); + for (; it_other_set != it_other->second.end(); ++it_other_set) { + if (it_me->second.find(*it_other_set) == it_me->second.end()) + it_me->second.insert(*it_other_set); + } + } + } + } +} diff --git a/libcef/common/value_base.h b/libcef/common/value_base.h new file mode 100644 index 000000000..d9483ee21 --- /dev/null +++ b/libcef/common/value_base.h @@ -0,0 +1,419 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_VALUE_BASE_H_ +#define CEF_LIBCEF_COMMON_VALUE_BASE_H_ +#pragma once + +#include +#include +#include "include/cef_base.h" + +#include "base/logging.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/synchronization/lock.h" +#include "base/threading/platform_thread.h" + + +// Controller implementation base class. +class CefValueController + : public base::RefCountedThreadSafe { + public: + // Implemented by a class controlled using the access controller. + class Object { + public: + virtual ~Object() {} + + // Called when the value has been removed. + virtual void OnControlRemoved() =0; + }; + + // Encapsulates context locking and verification logic. + class AutoLock { + public: + explicit AutoLock(CefValueController* impl) + : impl_(impl), + verified_(impl && impl->VerifyThread()) { + DCHECK(impl); + if (verified_) + impl_->lock(); + } + ~AutoLock() { + if (verified_) + impl_->unlock(); + } + + inline bool verified() { return verified_; } + + private: + scoped_refptr impl_; + bool verified_; + + DISALLOW_COPY_AND_ASSIGN(AutoLock); + }; + + CefValueController(); + + // Returns true if this controller is thread safe. + virtual bool thread_safe() =0; + + // Returns true if the current thread is allowed to access this controller. + virtual bool on_correct_thread() =0; + + // Lock the controller. + virtual void lock() =0; + + // Unlock the controller. + virtual void unlock() =0; + + // Returns true if the controller is locked on the current thread. + virtual bool locked() =0; + + // Verify that the current thread is correct for accessing the controller. + inline bool VerifyThread() { + if (!thread_safe() && !on_correct_thread()) { + // This object should only be accessed from the thread that created it. + NOTREACHED() << "object accessed from incorrect thread."; + return false; + } + return true; + } + + // The controller must already be locked before calling the below methods. + + // Set the owner for this controller. + void SetOwner(void* value, Object* object); + + // Add a reference value and associated object. + void AddReference(void* value, Object* object); + + // Remove the value. If |notify_object| is true the removed object will be + // notified. If |value| is the owner all reference objects will be removed. + // If |value| has dependencies those objects will also be removed. + void Remove(void* value, bool notify_object); + + // Returns the object for the specified value. + Object* Get(void* value); + + // Add a dependency between |parent| and |child|. + void AddDependency(void* parent, void* child); + + // Recursively removes any dependent values. + void RemoveDependencies(void* value); + + // Takes ownership of all references and dependencies currently controlled by + // |other|. The |other| controller must already be locked. + void TakeFrom(CefValueController* other); + + protected: + friend class base::RefCountedThreadSafe; + + virtual ~CefValueController(); + + private: + // Owner object. + void* owner_value_; + Object* owner_object_; + + // Map of reference objects. + typedef std::map ReferenceMap; + ReferenceMap reference_map_; + + // Map of dependency objects. + typedef std::set DependencySet; + typedef std::map DependencyMap; + DependencyMap dependency_map_; + + DISALLOW_COPY_AND_ASSIGN(CefValueController); +}; + +// Thread-safe access control implementation. +class CefValueControllerThreadSafe : public CefValueController { + public: + explicit CefValueControllerThreadSafe() + : locked_thread_id_(0) {} + + // CefValueController methods. + bool thread_safe() override { return true; } + bool on_correct_thread() override { return true; } + void lock() override { + lock_.Acquire(); + locked_thread_id_ = base::PlatformThread::CurrentId(); + } + void unlock() override { + locked_thread_id_ = 0; + lock_.Release(); + } + bool locked() override { + return (locked_thread_id_ == base::PlatformThread::CurrentId()); + } + + private: + base::Lock lock_; + base::PlatformThreadId locked_thread_id_; + + DISALLOW_COPY_AND_ASSIGN(CefValueControllerThreadSafe); +}; + +// Non-thread-safe access control implementation. +class CefValueControllerNonThreadSafe : public CefValueController { + public: + explicit CefValueControllerNonThreadSafe() + : thread_id_(base::PlatformThread::CurrentId()) {} + + // CefValueController methods. + bool thread_safe() override { return false; } + bool on_correct_thread() override { + return (thread_id_ == base::PlatformThread::CurrentId()); + } + void lock() override {} + void unlock() override {} + bool locked() override { return on_correct_thread(); } + + private: + base::PlatformThreadId thread_id_; + + DISALLOW_COPY_AND_ASSIGN(CefValueControllerNonThreadSafe); +}; + + +// Helper macros for verifying context. + +#define CEF_VALUE_VERIFY_RETURN_VOID_EX(object, modify) \ + if (!VerifyAttached()) \ + return; \ + AutoLock auto_lock(object, modify); \ + if (!auto_lock.verified()) \ + return; + +#define CEF_VALUE_VERIFY_RETURN_VOID(modify) \ + CEF_VALUE_VERIFY_RETURN_VOID_EX(this, modify) + +#define CEF_VALUE_VERIFY_RETURN_EX(object, modify, error_val) \ + if (!VerifyAttached()) \ + return error_val; \ + AutoLock auto_lock(object, modify); \ + if (!auto_lock.verified()) \ + return error_val; + +#define CEF_VALUE_VERIFY_RETURN(modify, error_val) \ + CEF_VALUE_VERIFY_RETURN_EX(this, modify, error_val) + + +// Template class for implementing CEF wrappers of other types. +template +class CefValueBase : public CefType, public CefValueController::Object { + public: + // Specifies how the value will be used. + enum ValueMode { + // A reference to a value managed by an existing controller. These values + // can be safely detached but ownership should not be transferred (make a + // copy of the value instead). + kReference, + + // The value has its own controller and will be deleted on destruction. + // These values can only be detached to another controller otherwise any + // references will not be properly managed. + kOwnerWillDelete, + + // The value has its own controller and will not be deleted on destruction. + // This should only be used for global values or scope-limited values that + // will be explicitly detached. + kOwnerNoDelete, + }; + + // Create a new object. + // If |read_only| is true mutable access will not be allowed. + // If |parent_value| is non-NULL and the value mode is kReference a dependency + // will be added. + CefValueBase(ValueType* value, + void* parent_value, + ValueMode value_mode, + bool read_only, + CefValueController* controller) + : value_(value), + value_mode_(value_mode), + read_only_(read_only), + controller_(controller) { + DCHECK(value_); + + // Specifying a parent value for a non-reference doesn't make sense. + DCHECK(!(!reference() && parent_value)); + + if (!reference() && !controller_.get()) { + // For owned values default to using a new multi-threaded controller. + controller_ = new CefValueControllerThreadSafe(); + SetOwnsController(); + } + + // A controller is required. + DCHECK(controller_.get()); + + if (reference()) { + // Register the reference with the controller. + controller_->AddReference(value_, this); + + // Add a dependency on the parent value. + if (parent_value) + controller_->AddDependency(parent_value, value_); + } + } + + ~CefValueBase() override { + if (controller_.get() && value_) + Delete(); + } + + // True if the underlying value is referenced instead of owned. + inline bool reference() const { return (value_mode_ == kReference); } + + // True if the underlying value will be deleted. + inline bool will_delete() const { return (value_mode_ == kOwnerWillDelete); } + + // True if access to the underlying value is read-only. + inline bool read_only() const { return read_only_; } + + // True if the underlying value has been detached. + inline bool detached() { return !controller_.get(); } + + // Returns the controller. + inline CefValueController* controller() { return controller_.get(); } + + // Deletes the underlying value. + void Delete() { + CEF_VALUE_VERIFY_RETURN_VOID(false); + + // Remove the object from the controller. If this is the owner object any + // references will be detached. + controller()->Remove(value_, false); + + if (will_delete()) { + // Remove any dependencies. + controller()->RemoveDependencies(value_); + + // Delete the value. + DeleteValue(value_); + } + + controller_ = NULL; + value_ = NULL; + } + + // Detaches the underlying value and returns a pointer to it. If this is an + // owner and a |new_controller| value is specified any existing references + // will be passed to the new controller. + ValueType* Detach(CefValueController* new_controller) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + // A |new_controller| value is required for mode kOwnerWillDelete. + DCHECK(!will_delete() || new_controller); + + if (new_controller && !reference()) { + // Pass any existing references and dependencies to the new controller. + // They will be removed from this controller. + new_controller->TakeFrom(controller()); + } + + // Remove the object from the controller. If this is the owner object any + // references will be detached. + controller()->Remove(value_, false); + controller_ = NULL; + + // Return the old value. + ValueType* old_val = value_; + value_ = NULL; + return old_val; + } + + // Verify that the value is attached. + inline bool VerifyAttached() { + if (detached()) { + // This object should not be accessed after being detached. + NOTREACHED() << "object accessed after being detached."; + return false; + } + return true; + } + + protected: + // CefValueController::Object methods. + void OnControlRemoved() override { + DCHECK(controller()->locked()); + + // Only references should be removed in this manner. + DCHECK(reference()); + + controller_ = NULL; + value_ = NULL; + } + + // Override to customize value deletion. + virtual void DeleteValue(ValueType* value) { delete value; } + + // Returns a mutable reference to the value. + inline ValueType* mutable_value() { + DCHECK(value_); + DCHECK(!read_only_); + DCHECK(controller()->locked()); + return value_; + } + // Returns a const reference to the value. + inline const ValueType& const_value() { + DCHECK(value_); + DCHECK(controller()->locked()); + return *value_; + } + + // Verify that the value can be accessed. + inline bool VerifyAccess(bool modify) { + // The controller must already be locked. + DCHECK(controller()->locked()); + + if (read_only() && modify) { + // This object cannot be modified. + NOTREACHED() << "mutation attempted on read-only object."; + return false; + } + + return true; + } + + // Used to indicate that this object owns the controller. + inline void SetOwnsController() { + CefValueController::AutoLock lock_scope(controller_.get()); + if (lock_scope.verified()) + controller_->SetOwner(value_, this); + } + + // Encapsulates value locking and verification logic. + class AutoLock { + public: + explicit AutoLock(CefValueBase* impl, bool modify) + : auto_lock_(impl->controller()) { + verified_ = (auto_lock_.verified() && impl->VerifyAccess(modify)); + } + + inline bool verified() { return verified_; } + + private: + CefValueController::AutoLock auto_lock_; + bool verified_; + + DISALLOW_COPY_AND_ASSIGN(AutoLock); + }; + + private: + ValueType* value_; + ValueMode value_mode_; + bool read_only_; + scoped_refptr controller_; + + IMPLEMENT_REFCOUNTING(CefValueBase); + + DISALLOW_COPY_AND_ASSIGN(CefValueBase); +}; + + +#endif // CEF_LIBCEF_COMMON_VALUE_BASE_H_ diff --git a/libcef/common/values_impl.cc b/libcef/common/values_impl.cc new file mode 100644 index 000000000..04efb5601 --- /dev/null +++ b/libcef/common/values_impl.cc @@ -0,0 +1,839 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/common/values_impl.h" + +#include +#include + + +// CefBinaryValueImpl implementation. + +CefRefPtr CefBinaryValue::Create(const void* data, + size_t data_size) { + DCHECK(data); + DCHECK_GT(data_size, (size_t)0); + if (!data || data_size == 0) + return NULL; + + return new CefBinaryValueImpl(static_cast(const_cast(data)), + data_size, true); +} + +// static +CefRefPtr CefBinaryValueImpl::GetOrCreateRef( + base::BinaryValue* value, + void* parent_value, + CefValueController* controller) { + DCHECK(value); + DCHECK(parent_value); + DCHECK(controller); + + CefValueController::Object* object = controller->Get(value); + if (object) + return static_cast(object); + + return new CefBinaryValueImpl(value, parent_value, + CefBinaryValueImpl::kReference, controller); +} + +CefBinaryValueImpl::CefBinaryValueImpl(base::BinaryValue* value, + bool will_delete, + bool read_only) + : CefValueBase( + value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete, + read_only, NULL) { +} + +base::BinaryValue* CefBinaryValueImpl::CopyValue() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + return const_value().DeepCopy(); +} + +base::BinaryValue* CefBinaryValueImpl::CopyOrDetachValue( + CefValueController* new_controller) { + base::BinaryValue* new_value; + + if (!will_delete()) { + // Copy the value. + new_value = CopyValue(); + } else { + // Take ownership of the value. + new_value = Detach(new_controller); + } + + DCHECK(new_value); + return new_value; +} + +bool CefBinaryValueImpl::IsValid() { + return !detached(); +} + +bool CefBinaryValueImpl::IsOwned() { + return !will_delete(); +} + +CefRefPtr CefBinaryValueImpl::Copy() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + return new CefBinaryValueImpl(const_value().DeepCopy(), NULL, + CefBinaryValueImpl::kOwnerWillDelete, NULL); +} + +size_t CefBinaryValueImpl::GetSize() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().GetSize(); +} + +size_t CefBinaryValueImpl::GetData(void* buffer, + size_t buffer_size, + size_t data_offset) { + DCHECK(buffer); + DCHECK_GT(buffer_size, (size_t)0); + if (!buffer || buffer_size == 0) + return 0; + + CEF_VALUE_VERIFY_RETURN(false, 0); + + size_t size = const_value().GetSize(); + DCHECK_LT(data_offset, size); + if (data_offset >= size) + return 0; + + size = std::min(buffer_size, size-data_offset); + const char* data = const_value().GetBuffer(); + memcpy(buffer, data+data_offset, size); + return size; +} + +CefBinaryValueImpl::CefBinaryValueImpl(base::BinaryValue* value, + void* parent_value, + ValueMode value_mode, + CefValueController* controller) + : CefValueBase( + value, parent_value, value_mode, true, controller) { +} + +CefBinaryValueImpl::CefBinaryValueImpl(char* data, + size_t data_size, + bool copy) + : CefValueBase( + copy ? base::BinaryValue::CreateWithCopiedBuffer(data, data_size) : + new base::BinaryValue(scoped_ptr(data), data_size), + NULL, kOwnerWillDelete, true, NULL) { +} + + +// CefDictionaryValueImpl implementation. + +// static +CefRefPtr CefDictionaryValue::Create() { + return new CefDictionaryValueImpl(new base::DictionaryValue(), + NULL, CefDictionaryValueImpl::kOwnerWillDelete, false, NULL); +} + +// static +CefRefPtr CefDictionaryValueImpl::GetOrCreateRef( + base::DictionaryValue* value, + void* parent_value, + bool read_only, + CefValueController* controller) { + CefValueController::Object* object = controller->Get(value); + if (object) + return static_cast(object); + + return new CefDictionaryValueImpl(value, parent_value, + CefDictionaryValueImpl::kReference, read_only, controller); +} + +CefDictionaryValueImpl::CefDictionaryValueImpl(base::DictionaryValue* value, + bool will_delete, + bool read_only) + : CefValueBase( + value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete, + read_only, NULL) { +} + +base::DictionaryValue* CefDictionaryValueImpl::CopyValue() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + return const_value().DeepCopy(); +} + +base::DictionaryValue* CefDictionaryValueImpl::CopyOrDetachValue( + CefValueController* new_controller) { + base::DictionaryValue* new_value; + + if (!will_delete()) { + // Copy the value. + new_value = CopyValue(); + } else { + // Take ownership of the value. + new_value = Detach(new_controller); + } + + DCHECK(new_value); + return new_value; +} + +bool CefDictionaryValueImpl::IsValid() { + return !detached(); +} + +bool CefDictionaryValueImpl::IsOwned() { + return !will_delete(); +} + +bool CefDictionaryValueImpl::IsReadOnly() { + return read_only(); +} + +CefRefPtr CefDictionaryValueImpl::Copy( + bool exclude_empty_children) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + base::DictionaryValue* value; + if (exclude_empty_children) { + value = const_cast( + const_value()).DeepCopyWithoutEmptyChildren(); + } else { + value = const_value().DeepCopy(); + } + + return new CefDictionaryValueImpl(value, NULL, + CefDictionaryValueImpl::kOwnerWillDelete, false, NULL); +} + +size_t CefDictionaryValueImpl::GetSize() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().size(); +} + +bool CefDictionaryValueImpl::Clear() { + CEF_VALUE_VERIFY_RETURN(true, false); + + // Detach any dependent values. + controller()->RemoveDependencies(mutable_value()); + + mutable_value()->Clear(); + return true; +} + +bool CefDictionaryValueImpl::HasKey(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().HasKey(key); +} + +bool CefDictionaryValueImpl::GetKeys(KeyList& keys) { + CEF_VALUE_VERIFY_RETURN(false, 0); + + for (base::DictionaryValue::Iterator i(const_value()); + !i.IsAtEnd(); i.Advance()) { + keys.push_back(i.key()); + } + + return true; +} + +bool CefDictionaryValueImpl::Remove(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(true, false); + return RemoveInternal(key); +} + +CefValueType CefDictionaryValueImpl::GetType(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, VTYPE_INVALID); + + const base::Value* out_value = NULL; + if (const_value().GetWithoutPathExpansion(key, &out_value)) { + switch (out_value->GetType()) { + case base::Value::TYPE_NULL: + return VTYPE_NULL; + case base::Value::TYPE_BOOLEAN: + return VTYPE_BOOL; + case base::Value::TYPE_INTEGER: + return VTYPE_INT; + case base::Value::TYPE_DOUBLE: + return VTYPE_DOUBLE; + case base::Value::TYPE_STRING: + return VTYPE_STRING; + case base::Value::TYPE_BINARY: + return VTYPE_BINARY; + case base::Value::TYPE_DICTIONARY: + return VTYPE_DICTIONARY; + case base::Value::TYPE_LIST: + return VTYPE_LIST; + } + } + + return VTYPE_INVALID; +} + +bool CefDictionaryValueImpl::GetBool(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, false); + + const base::Value* out_value = NULL; + bool ret_value = false; + + if (const_value().GetWithoutPathExpansion(key, &out_value)) + out_value->GetAsBoolean(&ret_value); + + return ret_value; +} + +int CefDictionaryValueImpl::GetInt(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, 0); + + const base::Value* out_value = NULL; + int ret_value = 0; + + if (const_value().GetWithoutPathExpansion(key, &out_value)) + out_value->GetAsInteger(&ret_value); + + return ret_value; +} + +double CefDictionaryValueImpl::GetDouble(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, 0); + + const base::Value* out_value = NULL; + double ret_value = 0; + + if (const_value().GetWithoutPathExpansion(key, &out_value)) + out_value->GetAsDouble(&ret_value); + + return ret_value; +} + +CefString CefDictionaryValueImpl::GetString(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + + const base::Value* out_value = NULL; + std::string ret_value; + + if (const_value().GetWithoutPathExpansion(key, &out_value)) + out_value->GetAsString(&ret_value); + + return ret_value; +} + +CefRefPtr CefDictionaryValueImpl::GetBinary( + const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + const base::Value* out_value = NULL; + + if (const_value().GetWithoutPathExpansion(key, &out_value) && + out_value->IsType(base::Value::TYPE_BINARY)) { + base::BinaryValue* binary_value = + static_cast(const_cast(out_value)); + return CefBinaryValueImpl::GetOrCreateRef(binary_value, + const_cast(&const_value()), controller()); + } + + return NULL; +} + +CefRefPtr CefDictionaryValueImpl::GetDictionary( + const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + const base::Value* out_value = NULL; + + if (const_value().GetWithoutPathExpansion(key, &out_value) && + out_value->IsType(base::Value::TYPE_DICTIONARY)) { + base::DictionaryValue* dict_value = + static_cast( + const_cast(out_value)); + return CefDictionaryValueImpl::GetOrCreateRef( + dict_value, + const_cast(&const_value()), + read_only(), + controller()); + } + + return NULL; +} + +CefRefPtr CefDictionaryValueImpl::GetList(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + const base::Value* out_value = NULL; + + if (const_value().GetWithoutPathExpansion(key, &out_value) && + out_value->IsType(base::Value::TYPE_LIST)) { + base::ListValue* list_value = + static_cast(const_cast(out_value)); + return CefListValueImpl::GetOrCreateRef( + list_value, + const_cast(&const_value()), + read_only(), + controller()); + } + + return NULL; +} + +bool CefDictionaryValueImpl::SetNull(const CefString& key) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + mutable_value()->SetWithoutPathExpansion(key, base::Value::CreateNullValue()); + return true; +} + +bool CefDictionaryValueImpl::SetBool(const CefString& key, bool value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + mutable_value()->SetWithoutPathExpansion(key, + new base::FundamentalValue(value)); + return true; +} + +bool CefDictionaryValueImpl::SetInt(const CefString& key, int value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + mutable_value()->SetWithoutPathExpansion(key, + new base::FundamentalValue(value)); + return true; +} + +bool CefDictionaryValueImpl::SetDouble(const CefString& key, double value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + mutable_value()->SetWithoutPathExpansion(key, + new base::FundamentalValue(value)); + return true; +} + +bool CefDictionaryValueImpl::SetString(const CefString& key, + const CefString& value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + mutable_value()->SetWithoutPathExpansion(key, + new base::StringValue(value.ToString())); + return true; +} + +bool CefDictionaryValueImpl::SetBinary(const CefString& key, + CefRefPtr value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + + CefBinaryValueImpl* impl = static_cast(value.get()); + DCHECK(impl); + + mutable_value()->SetWithoutPathExpansion(key, + impl->CopyOrDetachValue(controller())); + return true; +} + +bool CefDictionaryValueImpl::SetDictionary( + const CefString& key, CefRefPtr value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + + CefDictionaryValueImpl* impl = + static_cast(value.get()); + DCHECK(impl); + + mutable_value()->SetWithoutPathExpansion(key, + impl->CopyOrDetachValue(controller())); + return true; +} + +bool CefDictionaryValueImpl::SetList(const CefString& key, + CefRefPtr value) { + CEF_VALUE_VERIFY_RETURN(true, false); + RemoveInternal(key); + + CefListValueImpl* impl = static_cast(value.get()); + DCHECK(impl); + + mutable_value()->SetWithoutPathExpansion(key, + impl->CopyOrDetachValue(controller())); + return true; +} + +bool CefDictionaryValueImpl::RemoveInternal(const CefString& key) { + scoped_ptr out_value; + if (!mutable_value()->RemoveWithoutPathExpansion(key, &out_value)) + return false; + + // Remove the value. + controller()->Remove(out_value.get(), true); + + // Only list and dictionary types may have dependencies. + if (out_value->IsType(base::Value::TYPE_LIST) || + out_value->IsType(base::Value::TYPE_DICTIONARY)) { + controller()->RemoveDependencies(out_value.get()); + } + + return true; +} + +CefDictionaryValueImpl::CefDictionaryValueImpl( + base::DictionaryValue* value, + void* parent_value, + ValueMode value_mode, + bool read_only, + CefValueController* controller) + : CefValueBase( + value, parent_value, value_mode, read_only, controller) { +} + + +// CefListValueImpl implementation. + +// static +CefRefPtr CefListValue::Create() { + return new CefListValueImpl(new base::ListValue(), + NULL, CefListValueImpl::kOwnerWillDelete, false, NULL); +} + +// static +CefRefPtr CefListValueImpl::GetOrCreateRef( + base::ListValue* value, + void* parent_value, + bool read_only, + CefValueController* controller) { + CefValueController::Object* object = controller->Get(value); + if (object) + return static_cast(object); + + return new CefListValueImpl(value, parent_value, + CefListValueImpl::kReference, read_only, controller); +} + +CefListValueImpl::CefListValueImpl(base::ListValue* value, + bool will_delete, + bool read_only) + : CefValueBase( + value, NULL, will_delete ? kOwnerWillDelete : kOwnerNoDelete, + read_only, NULL) { +} + +base::ListValue* CefListValueImpl::CopyValue() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + return const_value().DeepCopy(); +} + +base::ListValue* CefListValueImpl::CopyOrDetachValue( + CefValueController* new_controller) { + base::ListValue* new_value; + + if (!will_delete()) { + // Copy the value. + new_value = CopyValue(); + } else { + // Take ownership of the value. + new_value = Detach(new_controller); + } + + DCHECK(new_value); + return new_value; +} + +bool CefListValueImpl::IsValid() { + return !detached(); +} + +bool CefListValueImpl::IsOwned() { + return !will_delete(); +} + +bool CefListValueImpl::IsReadOnly() { + return read_only(); +} + +CefRefPtr CefListValueImpl::Copy() { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + return new CefListValueImpl(const_value().DeepCopy(), NULL, + CefListValueImpl::kOwnerWillDelete, false, NULL); +} + +bool CefListValueImpl::SetSize(size_t size) { + CEF_VALUE_VERIFY_RETURN(true, false); + + size_t current_size = const_value().GetSize(); + if (size < current_size) { + // Clean up any values above the requested size. + for (size_t i = current_size-1; i >= size; --i) + RemoveInternal(i); + } else if (size > 0) { + // Expand the list size. + mutable_value()->Set(size-1, base::Value::CreateNullValue()); + } + return true; +} + +size_t CefListValueImpl::GetSize() { + CEF_VALUE_VERIFY_RETURN(false, 0); + return const_value().GetSize(); +} + +bool CefListValueImpl::Clear() { + CEF_VALUE_VERIFY_RETURN(true, false); + + // Detach any dependent values. + controller()->RemoveDependencies(mutable_value()); + + mutable_value()->Clear(); + return true; +} + +bool CefListValueImpl::Remove(int index) { + CEF_VALUE_VERIFY_RETURN(true, false); + return RemoveInternal(index); +} + +CefValueType CefListValueImpl::GetType(int index) { + CEF_VALUE_VERIFY_RETURN(false, VTYPE_INVALID); + + const base::Value* out_value = NULL; + if (const_value().Get(index, &out_value)) { + switch (out_value->GetType()) { + case base::Value::TYPE_NULL: + return VTYPE_NULL; + case base::Value::TYPE_BOOLEAN: + return VTYPE_BOOL; + case base::Value::TYPE_INTEGER: + return VTYPE_INT; + case base::Value::TYPE_DOUBLE: + return VTYPE_DOUBLE; + case base::Value::TYPE_STRING: + return VTYPE_STRING; + case base::Value::TYPE_BINARY: + return VTYPE_BINARY; + case base::Value::TYPE_DICTIONARY: + return VTYPE_DICTIONARY; + case base::Value::TYPE_LIST: + return VTYPE_LIST; + } + } + + return VTYPE_INVALID; +} + +bool CefListValueImpl::GetBool(int index) { + CEF_VALUE_VERIFY_RETURN(false, false); + + const base::Value* out_value = NULL; + bool ret_value = false; + + if (const_value().Get(index, &out_value)) + out_value->GetAsBoolean(&ret_value); + + return ret_value; +} + +int CefListValueImpl::GetInt(int index) { + CEF_VALUE_VERIFY_RETURN(false, 0); + + const base::Value* out_value = NULL; + int ret_value = 0; + + if (const_value().Get(index, &out_value)) + out_value->GetAsInteger(&ret_value); + + return ret_value; +} + +double CefListValueImpl::GetDouble(int index) { + CEF_VALUE_VERIFY_RETURN(false, 0); + + const base::Value* out_value = NULL; + double ret_value = 0; + + if (const_value().Get(index, &out_value)) + out_value->GetAsDouble(&ret_value); + + return ret_value; +} + +CefString CefListValueImpl::GetString(int index) { + CEF_VALUE_VERIFY_RETURN(false, CefString()); + + const base::Value* out_value = NULL; + std::string ret_value; + + if (const_value().Get(index, &out_value)) + out_value->GetAsString(&ret_value); + + return ret_value; +} + +CefRefPtr CefListValueImpl::GetBinary(int index) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + const base::Value* out_value = NULL; + + if (const_value().Get(index, &out_value) && + out_value->IsType(base::Value::TYPE_BINARY)) { + base::BinaryValue* binary_value = + static_cast(const_cast(out_value)); + return CefBinaryValueImpl::GetOrCreateRef(binary_value, + const_cast(&const_value()), controller()); + } + + return NULL; +} + +CefRefPtr CefListValueImpl::GetDictionary(int index) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + const base::Value* out_value = NULL; + + if (const_value().Get(index, &out_value) && + out_value->IsType(base::Value::TYPE_DICTIONARY)) { + base::DictionaryValue* dict_value = + static_cast( + const_cast(out_value)); + return CefDictionaryValueImpl::GetOrCreateRef( + dict_value, + const_cast(&const_value()), + read_only(), + controller()); + } + + return NULL; +} + +CefRefPtr CefListValueImpl::GetList(int index) { + CEF_VALUE_VERIFY_RETURN(false, NULL); + + const base::Value* out_value = NULL; + + if (const_value().Get(index, &out_value) && + out_value->IsType(base::Value::TYPE_LIST)) { + base::ListValue* list_value = + static_cast(const_cast(out_value)); + return CefListValueImpl::GetOrCreateRef( + list_value, + const_cast(&const_value()), + read_only(), + controller()); + } + + return NULL; +} + +bool CefListValueImpl::SetNull(int index) { + CEF_VALUE_VERIFY_RETURN(true, false); + base::Value* new_value = base::Value::CreateNullValue(); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetBool(int index, bool value) { + CEF_VALUE_VERIFY_RETURN(true, false); + base::Value* new_value = new base::FundamentalValue(value); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetInt(int index, int value) { + CEF_VALUE_VERIFY_RETURN(true, false); + base::Value* new_value = new base::FundamentalValue(value); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetDouble(int index, double value) { + CEF_VALUE_VERIFY_RETURN(true, false); + base::Value* new_value = new base::FundamentalValue(value); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetString(int index, const CefString& value) { + CEF_VALUE_VERIFY_RETURN(true, false); + base::Value* new_value = new base::StringValue(value.ToString()); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetBinary(int index, CefRefPtr value) { + CEF_VALUE_VERIFY_RETURN(true, false); + + CefBinaryValueImpl* impl = static_cast(value.get()); + DCHECK(impl); + + base::Value* new_value = impl->CopyOrDetachValue(controller()); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetDictionary(int index, + CefRefPtr value) { + CEF_VALUE_VERIFY_RETURN(true, false); + + CefDictionaryValueImpl* impl = + static_cast(value.get()); + DCHECK(impl); + + base::Value* new_value = impl->CopyOrDetachValue(controller()); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::SetList(int index, CefRefPtr value) { + CEF_VALUE_VERIFY_RETURN(true, false); + + CefListValueImpl* impl = static_cast(value.get()); + DCHECK(impl); + + base::Value* new_value = impl->CopyOrDetachValue(controller()); + if (RemoveInternal(index)) + mutable_value()->Insert(index, new_value); + else + mutable_value()->Set(index, new_value); + return true; +} + +bool CefListValueImpl::RemoveInternal(int index) { + scoped_ptr out_value; + if (!mutable_value()->Remove(index, &out_value)) + return false; + + // Remove the value. + controller()->Remove(out_value.get(), true); + + // Only list and dictionary types may have dependencies. + if (out_value->IsType(base::Value::TYPE_LIST) || + out_value->IsType(base::Value::TYPE_DICTIONARY)) { + controller()->RemoveDependencies(out_value.get()); + } + + return true; +} + +CefListValueImpl::CefListValueImpl( + base::ListValue* value, + void* parent_value, + ValueMode value_mode, + bool read_only, + CefValueController* controller) + : CefValueBase( + value, parent_value, value_mode, read_only, controller) { +} diff --git a/libcef/common/values_impl.h b/libcef/common/values_impl.h new file mode 100644 index 000000000..ef4e25c93 --- /dev/null +++ b/libcef/common/values_impl.h @@ -0,0 +1,209 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_COMMON_VALUES_IMPL_H_ +#define CEF_LIBCEF_COMMON_VALUES_IMPL_H_ +#pragma once + +#include + +#include "include/cef_values.h" +#include "libcef/common/value_base.h" + +#include "base/values.h" +#include "base/threading/platform_thread.h" + + +// CefBinaryValue implementation +class CefBinaryValueImpl + : public CefValueBase { + public: + // Get or create a reference value. + static CefRefPtr GetOrCreateRef( + base::BinaryValue* value, + void* parent_value, + CefValueController* controller); + + // Simple constructor for referencing existing value objects. + CefBinaryValueImpl(base::BinaryValue* value, + bool will_delete, + bool read_only); + + // Return a copy of the value. + base::BinaryValue* CopyValue(); + + // If a reference return a copy of the value otherwise detach the value to the + // specified |new_controller|. + base::BinaryValue* CopyOrDetachValue(CefValueController* new_controller); + + // CefBinaryValue methods. + bool IsValid() override; + bool IsOwned() override; + CefRefPtr Copy() override; + size_t GetSize() override; + size_t GetData(void* buffer, + size_t buffer_size, + size_t data_offset) override; + + private: + // See the CefValueBase constructor for usage. Binary values are always + // read-only. + CefBinaryValueImpl(base::BinaryValue* value, + void* parent_value, + ValueMode value_mode, + CefValueController* controller); + // If |copy| is false this object will take ownership of the specified |data| + // buffer instead of copying it. + CefBinaryValueImpl(char* data, + size_t data_size, + bool copy); + + // For the Create() method. + friend class CefBinaryValue; + + DISALLOW_COPY_AND_ASSIGN(CefBinaryValueImpl); +}; + + +// CefDictionaryValue implementation +class CefDictionaryValueImpl + : public CefValueBase { + public: + // Get or create a reference value. + static CefRefPtr GetOrCreateRef( + base::DictionaryValue* value, + void* parent_value, + bool read_only, + CefValueController* controller); + + // Simple constructor for referencing existing value objects. + CefDictionaryValueImpl(base::DictionaryValue* value, + bool will_delete, + bool read_only); + + // Return a copy of the value. + base::DictionaryValue* CopyValue(); + + // If a reference return a copy of the value otherwise detach the value to the + // specified |new_controller|. + base::DictionaryValue* CopyOrDetachValue(CefValueController* new_controller); + + // CefDictionaryValue methods. + bool IsValid() override; + bool IsOwned() override; + bool IsReadOnly() override; + CefRefPtr Copy( + bool exclude_empty_children) override; + size_t GetSize() override; + bool Clear() override; + bool HasKey(const CefString& key) override; + bool GetKeys(KeyList& keys) override; + bool Remove(const CefString& key) override; + CefValueType GetType(const CefString& key) override; + bool GetBool(const CefString& key) override; + int GetInt(const CefString& key) override; + double GetDouble(const CefString& key) override; + CefString GetString(const CefString& key) override; + CefRefPtr GetBinary(const CefString& key) override; + CefRefPtr GetDictionary( + const CefString& key) override; + CefRefPtr GetList(const CefString& key) override; + bool SetNull(const CefString& key) override; + bool SetBool(const CefString& key, bool value) override; + bool SetInt(const CefString& key, int value) override; + bool SetDouble(const CefString& key, double value) override; + bool SetString(const CefString& key, + const CefString& value) override; + bool SetBinary(const CefString& key, + CefRefPtr value) override; + bool SetDictionary(const CefString& key, + CefRefPtr value) override; + bool SetList(const CefString& key, + CefRefPtr value) override; + + private: + // See the CefValueBase constructor for usage. + CefDictionaryValueImpl(base::DictionaryValue* value, + void* parent_value, + ValueMode value_mode, + bool read_only, + CefValueController* controller); + + bool RemoveInternal(const CefString& key); + + // For the Create() method. + friend class CefDictionaryValue; + + DISALLOW_COPY_AND_ASSIGN(CefDictionaryValueImpl); +}; + + +// CefListValue implementation +class CefListValueImpl + : public CefValueBase { + public: + // Get or create a reference value. + static CefRefPtr GetOrCreateRef( + base::ListValue* value, + void* parent_value, + bool read_only, + CefValueController* controller); + + // Simple constructor for referencing existing value objects. + CefListValueImpl(base::ListValue* value, + bool will_delete, + bool read_only); + + // Return a copy of the value. + base::ListValue* CopyValue(); + + // If a reference return a copy of the value otherwise detach the value to the + // specified |new_controller|. + base::ListValue* CopyOrDetachValue(CefValueController* new_controller); + + /// CefListValue methods. + bool IsValid() override; + bool IsOwned() override; + bool IsReadOnly() override; + CefRefPtr Copy() override; + bool SetSize(size_t size) override; + size_t GetSize() override; + bool Clear() override; + bool Remove(int index) override; + CefValueType GetType(int index) override; + bool GetBool(int index) override; + int GetInt(int index) override; + double GetDouble(int index) override; + CefString GetString(int index) override; + CefRefPtr GetBinary(int index) override; + CefRefPtr GetDictionary(int index) override; + CefRefPtr GetList(int index) override; + bool SetNull(int index) override; + bool SetBool(int index, bool value) override; + bool SetInt(int index, int value) override; + bool SetDouble(int index, double value) override; + bool SetString(int index, const CefString& value) override; + bool SetBinary(int index, CefRefPtr value) override; + bool SetDictionary(int index, + CefRefPtr value) override; + bool SetList(int index, CefRefPtr value) override; + + private: + // See the CefValueBase constructor for usage. + CefListValueImpl(base::ListValue* value, + void* parent_value, + ValueMode value_mode, + bool read_only, + CefValueController* controller); + + bool RemoveInternal(int index); + + // For the Create() method. + friend class CefListValue; + + DISALLOW_COPY_AND_ASSIGN(CefListValueImpl); +}; + + +#endif // CEF_LIBCEF_COMMON_VALUES_IMPL_H_ diff --git a/libcef/renderer/browser_impl.cc b/libcef/renderer/browser_impl.cc new file mode 100644 index 000000000..7107740cc --- /dev/null +++ b/libcef/renderer/browser_impl.cc @@ -0,0 +1,818 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/renderer/browser_impl.h" + +#include +#include + +#include "libcef/common/cef_messages.h" +#include "libcef/common/content_client.h" +#include "libcef/common/process_message_impl.h" +#include "libcef/common/response_manager.h" +#include "libcef/renderer/content_renderer_client.h" +#include "libcef/renderer/dom_document_impl.h" +#include "libcef/renderer/thread_util.h" +#include "libcef/renderer/webkit_glue.h" + +#include "base/strings/string16.h" +#include "base/strings/string_util.h" +#include "base/strings/sys_string_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "content/public/renderer/document_state.h" +#include "content/public/renderer/navigation_state.h" +#include "content/public/renderer/render_view.h" +#include "content/renderer/render_view_impl.h" +#include "net/http/http_util.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/platform/WebURLError.h" +#include "third_party/WebKit/public/platform/WebURLResponse.h" +#include "third_party/WebKit/public/web/WebDataSource.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" +#include "third_party/WebKit/public/web/WebNode.h" +#include "third_party/WebKit/public/web/WebScriptSource.h" +#include "third_party/WebKit/public/web/WebSecurityPolicy.h" +#include "third_party/WebKit/public/web/WebView.h" + +using blink::WebFrame; +using blink::WebScriptSource; +using blink::WebString; +using blink::WebURL; +using blink::WebView; + +namespace { + +blink::WebString FilePathStringToWebString( + const base::FilePath::StringType& str) { +#if defined(OS_POSIX) + return base::WideToUTF16(base::SysNativeMBToWide(str)); +#elif defined(OS_WIN) + return base::WideToUTF16(str); +#endif +} + +} // namespace + + +// CefBrowserImpl static methods. +// ----------------------------------------------------------------------------- + +// static +CefRefPtr CefBrowserImpl::GetBrowserForView( + content::RenderView* view) { + return CefContentRendererClient::Get()->GetBrowserForView(view); +} + +// static +CefRefPtr CefBrowserImpl::GetBrowserForMainFrame( + blink::WebFrame* frame) { + return CefContentRendererClient::Get()->GetBrowserForMainFrame(frame); +} + + +// CefBrowser methods. +// ----------------------------------------------------------------------------- + +CefRefPtr CefBrowserImpl::GetHost() { + NOTREACHED() << "GetHost cannot be called from the render process"; + return NULL; +} + +bool CefBrowserImpl::CanGoBack() { + CEF_REQUIRE_RT_RETURN(false); + + return webkit_glue::CanGoBack(render_view()->GetWebView()); +} + +void CefBrowserImpl::GoBack() { + CEF_REQUIRE_RT_RETURN_VOID(); + + webkit_glue::GoBack(render_view()->GetWebView()); +} + +bool CefBrowserImpl::CanGoForward() { + CEF_REQUIRE_RT_RETURN(false); + + return webkit_glue::CanGoForward(render_view()->GetWebView()); +} + +void CefBrowserImpl::GoForward() { + CEF_REQUIRE_RT_RETURN_VOID(); + + webkit_glue::GoForward(render_view()->GetWebView()); +} + +bool CefBrowserImpl::IsLoading() { + CEF_REQUIRE_RT_RETURN(false); + + if (render_view()->GetWebView()) { + blink::WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); + if (main_frame) + return main_frame->toWebLocalFrame()->isLoading(); + } + return false; +} + +void CefBrowserImpl::Reload() { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) + render_view()->GetWebView()->mainFrame()->reload(false); +} + +void CefBrowserImpl::ReloadIgnoreCache() { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) + render_view()->GetWebView()->mainFrame()->reload(true); +} + +void CefBrowserImpl::StopLoad() { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) + render_view()->GetWebView()->mainFrame()->stopLoading(); +} + +int CefBrowserImpl::GetIdentifier() { + CEF_REQUIRE_RT_RETURN(0); + + return browser_id(); +} + +bool CefBrowserImpl::IsSame(CefRefPtr that) { + CEF_REQUIRE_RT_RETURN(false); + + CefBrowserImpl* impl = static_cast(that.get()); + return (impl == this); +} + +bool CefBrowserImpl::IsPopup() { + CEF_REQUIRE_RT_RETURN(false); + + return is_popup(); +} + +bool CefBrowserImpl::HasDocument() { + CEF_REQUIRE_RT_RETURN(false); + + if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) + return !render_view()->GetWebView()->mainFrame()->document().isNull(); + return false; +} + +CefRefPtr CefBrowserImpl::GetMainFrame() { + CEF_REQUIRE_RT_RETURN(NULL); + + if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) + return GetWebFrameImpl(render_view()->GetWebView()->mainFrame()).get(); + return NULL; +} + +CefRefPtr CefBrowserImpl::GetFocusedFrame() { + CEF_REQUIRE_RT_RETURN(NULL); + + if (render_view()->GetWebView() && + render_view()->GetWebView()->focusedFrame()) { + return GetWebFrameImpl(render_view()->GetWebView()->focusedFrame()).get(); + } + return NULL; +} + +CefRefPtr CefBrowserImpl::GetFrame(int64 identifier) { + CEF_REQUIRE_RT_RETURN(NULL); + + return GetWebFrameImpl(identifier).get(); +} + +CefRefPtr CefBrowserImpl::GetFrame(const CefString& name) { + CEF_REQUIRE_RT_RETURN(NULL); + + blink::WebView* web_view = render_view()->GetWebView(); + if (web_view) { + const blink::WebString& frame_name = name.ToString16(); + // Search by assigned frame name (Frame::name). + WebFrame* frame = web_view->findFrameByName(frame_name, + web_view->mainFrame()); + if (!frame) { + // Search by unique frame name (Frame::uniqueName). + frame = webkit_glue::FindFrameByUniqueName(frame_name, + web_view->mainFrame()); + } + if (frame) + return GetWebFrameImpl(frame).get(); + } + + return NULL; +} + +size_t CefBrowserImpl::GetFrameCount() { + CEF_REQUIRE_RT_RETURN(0); + + int count = 0; + + if (render_view()->GetWebView()) { + WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); + if (main_frame) { + WebFrame* cur = main_frame; + do { + count++; + cur = cur->traverseNext(true); + } while (cur != main_frame); + } + } + + return count; +} + +void CefBrowserImpl::GetFrameIdentifiers(std::vector& identifiers) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (identifiers.size() > 0) + identifiers.clear(); + + if (render_view()->GetWebView()) { + WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); + if (main_frame) { + WebFrame* cur = main_frame; + do { + identifiers.push_back(webkit_glue::GetIdentifier(cur)); + cur = cur->traverseNext(true); + } while (cur != main_frame); + } + } +} + +void CefBrowserImpl::GetFrameNames(std::vector& names) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (names.size() > 0) + names.clear(); + + if (render_view()->GetWebView()) { + WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); + if (main_frame) { + WebFrame* cur = main_frame; + do { + names.push_back(CefString(cur->uniqueName().utf8())); + cur = cur->traverseNext(true); + } while (cur != main_frame); + } + } +} + +bool CefBrowserImpl::SendProcessMessage(CefProcessId target_process, + CefRefPtr message) { + Cef_Request_Params params; + CefProcessMessageImpl* impl = + static_cast(message.get()); + if (impl->CopyTo(params)) { + return SendProcessMessage(target_process, params.name, ¶ms.arguments, + true); + } + + return false; +} + + +// CefBrowserImpl public methods. +// ----------------------------------------------------------------------------- + +CefBrowserImpl::CefBrowserImpl(content::RenderView* render_view, + int browser_id, + bool is_popup, + bool is_windowless) + : content::RenderViewObserver(render_view), + browser_id_(browser_id), + is_popup_(is_popup), + is_windowless_(is_windowless) { + response_manager_.reset(new CefResponseManager); +} + +CefBrowserImpl::~CefBrowserImpl() { +} + +void CefBrowserImpl::LoadRequest(const CefMsg_LoadRequest_Params& params) { + CefRefPtr framePtr = GetWebFrameImpl(params.frame_id); + if (!framePtr.get()) + return; + + WebFrame* web_frame = framePtr->web_frame(); + + blink::WebURLRequest request(params.url); + + // DidCreateDataSource checks for this value. + request.setRequestorID(-1); + + if (!params.method.empty()) + request.setHTTPMethod(base::ASCIIToUTF16(params.method)); + + if (params.referrer.is_valid()) { + WebString referrer = blink::WebSecurityPolicy::generateReferrerHeader( + static_cast(params.referrer_policy), + params.url, + WebString::fromUTF8(params.referrer.spec())); + if (!referrer.isEmpty()) + request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer); + } + + if (params.first_party_for_cookies.is_valid()) + request.setFirstPartyForCookies(params.first_party_for_cookies); + + if (!params.headers.empty()) { + for (net::HttpUtil::HeadersIterator i(params.headers.begin(), + params.headers.end(), "\n"); + i.GetNext(); ) { + request.addHTTPHeaderField(WebString::fromUTF8(i.name()), + WebString::fromUTF8(i.values())); + } + } + + if (params.upload_data.get()) { + base::string16 method = request.httpMethod(); + if (method == base::ASCIIToUTF16("GET") || + method == base::ASCIIToUTF16("HEAD")) { + request.setHTTPMethod(base::ASCIIToUTF16("POST")); + } + + if (request.httpHeaderField( + base::ASCIIToUTF16("Content-Type")).length() == 0) { + request.setHTTPHeaderField( + base::ASCIIToUTF16("Content-Type"), + base::ASCIIToUTF16("application/x-www-form-urlencoded")); + } + + blink::WebHTTPBody body; + body.initialize(); + + const ScopedVector& elements = + params.upload_data->elements(); + ScopedVector::const_iterator it = + elements.begin(); + for (; it != elements.end(); ++it) { + const net::UploadElement& element = **it; + if (element.type() == net::UploadElement::TYPE_BYTES) { + blink::WebData data; + data.assign(element.bytes(), element.bytes_length()); + body.appendData(data); + } else if (element.type() == net::UploadElement::TYPE_FILE) { + body.appendFile(FilePathStringToWebString(element.file_path().value())); + } else { + NOTREACHED(); + } + } + + request.setHTTPBody(body); + } + + web_frame->loadRequest(request); +} + +bool CefBrowserImpl::SendProcessMessage(CefProcessId target_process, + const std::string& name, + base::ListValue* arguments, + bool user_initiated) { + DCHECK_EQ(PID_BROWSER, target_process); + DCHECK(!name.empty()); + + Cef_Request_Params params; + params.name = name; + if (arguments) + params.arguments.Swap(arguments); + params.frame_id = -1; + params.user_initiated = user_initiated; + params.request_id = -1; + params.expect_response = false; + + return Send(new CefHostMsg_Request(routing_id(), params)); +} + +CefRefPtr CefBrowserImpl::GetWebFrameImpl( + blink::WebFrame* frame) { + DCHECK(frame); + int64 frame_id = webkit_glue::GetIdentifier(frame); + + // Frames are re-used between page loads. Only add the frame to the map once. + FrameMap::const_iterator it = frames_.find(frame_id); + if (it != frames_.end()) + return it->second; + + CefRefPtr framePtr(new CefFrameImpl(this, frame)); + frames_.insert(std::make_pair(frame_id, framePtr)); + + int64 parent_id = frame->parent() == NULL ? + webkit_glue::kInvalidFrameId : + webkit_glue::GetIdentifier(frame->parent()); + base::string16 name = frame->uniqueName(); + + // Notify the browser that the frame has been identified. + Send(new CefHostMsg_FrameIdentified(routing_id(), frame_id, parent_id, name)); + + return framePtr; +} + +CefRefPtr CefBrowserImpl::GetWebFrameImpl(int64 frame_id) { + if (frame_id == webkit_glue::kInvalidFrameId) { + if (render_view()->GetWebView() && render_view()->GetWebView()->mainFrame()) + return GetWebFrameImpl(render_view()->GetWebView()->mainFrame()); + return NULL; + } + + // Check if we already know about the frame. + FrameMap::const_iterator it = frames_.find(frame_id); + if (it != frames_.end()) + return it->second; + + if (render_view()->GetWebView()) { + // Check if the frame exists but we don't know about it yet. + WebFrame* main_frame = render_view()->GetWebView()->mainFrame(); + if (main_frame) { + WebFrame* cur = main_frame; + do { + if (webkit_glue::GetIdentifier(cur) == frame_id) + return GetWebFrameImpl(cur); + cur = cur->traverseNext(true); + } while (cur != main_frame); + } + } + + return NULL; +} + +void CefBrowserImpl::AddFrameObject(int64 frame_id, + CefTrackNode* tracked_object) { + CefRefPtr manager; + + if (!frame_objects_.empty()) { + FrameObjectMap::const_iterator it = frame_objects_.find(frame_id); + if (it != frame_objects_.end()) + manager = it->second; + } + + if (!manager.get()) { + manager = new CefTrackManager(); + frame_objects_.insert(std::make_pair(frame_id, manager)); + } + + manager->Add(tracked_object); +} + +bool CefBrowserImpl::is_swapped_out() const { + content::RenderViewImpl* render_view_impl = + static_cast(render_view()); + return (!render_view_impl || render_view_impl->is_swapped_out()); +} + + +// RenderViewObserver methods. +// ----------------------------------------------------------------------------- + +void CefBrowserImpl::OnDestruct() { + // Notify that the browser window has been destroyed. + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) + handler->OnBrowserDestroyed(this); + } + + response_manager_.reset(NULL); + + CefContentRendererClient::Get()->OnBrowserDestroyed(this); +} + +void CefBrowserImpl::DidStartLoading() { + OnLoadingStateChange(true); +} + +void CefBrowserImpl::DidStopLoading() { + OnLoadingStateChange(false); +} + +void CefBrowserImpl::DidFailLoad( + blink::WebLocalFrame* frame, + const blink::WebURLError& error) { + OnLoadError(frame, error); + OnLoadEnd(frame); +} + +void CefBrowserImpl::DidFinishLoad(blink::WebLocalFrame* frame) { + blink::WebDataSource* ds = frame->dataSource(); + Send(new CefHostMsg_DidFinishLoad(routing_id(), + webkit_glue::GetIdentifier(frame), + ds->request().url(), + !frame->parent(), + ds->response().httpStatusCode())); + OnLoadEnd(frame); +} + +void CefBrowserImpl::DidStartProvisionalLoad(blink::WebLocalFrame* frame) { + // Send the frame creation notification if necessary. + GetWebFrameImpl(frame); +} + +void CefBrowserImpl::DidFailProvisionalLoad( + blink::WebLocalFrame* frame, + const blink::WebURLError& error) { + OnLoadError(frame, error); +} + +void CefBrowserImpl::DidCommitProvisionalLoad(blink::WebLocalFrame* frame, + bool is_new_navigation) { + OnLoadStart(frame); +} + +void CefBrowserImpl::FrameDetached(WebFrame* frame) { + int64 frame_id = webkit_glue::GetIdentifier(frame); + + if (!frames_.empty()) { + // Remove the frame from the map. + FrameMap::iterator it = frames_.find(frame_id); + if (it != frames_.end()) { + it->second->Detach(); + frames_.erase(it); + } + } + + if (!frame_objects_.empty()) { + // Remove any tracked objects associated with the frame. + FrameObjectMap::iterator it = frame_objects_.find(frame_id); + if (it != frame_objects_.end()) + frame_objects_.erase(it); + } +} + +void CefBrowserImpl::FocusedNodeChanged(const blink::WebNode& node) { + // Notify the handler. + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) { + if (node.isNull()) { + handler->OnFocusedNodeChanged(this, GetFocusedFrame(), NULL); + } else { + const blink::WebDocument& document = node.document(); + if (!document.isNull()) { + blink::WebFrame* frame = document.frame(); + CefRefPtr documentImpl = + new CefDOMDocumentImpl(this, frame); + handler->OnFocusedNodeChanged(this, + GetWebFrameImpl(frame).get(), + documentImpl->GetOrCreateNode(node)); + documentImpl->Detach(); + } + } + } + } +} + +void CefBrowserImpl::DidCreateDataSource(blink::WebLocalFrame* frame, + blink::WebDataSource* ds) { + const blink::WebURLRequest& request = ds->request(); + if (request.requestorID() == -1) { + // Mark the request as browser-initiated so + // RenderViewImpl::decidePolicyForNavigation won't attempt to fork it. + content::DocumentState* document_state = + content::DocumentState::FromDataSource(ds); + document_state->set_navigation_state( + content::NavigationState::CreateBrowserInitiated(-1, -1, false, + ui::PAGE_TRANSITION_LINK)); + } + + if (frame->parent() == 0) { + GURL url = ds->request().url(); + if (!url.is_empty()) { + // Notify that the loading URL has changed. + Send(new CefHostMsg_LoadingURLChange(routing_id(), url)); + } + } +} + +bool CefBrowserImpl::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(CefBrowserImpl, message) + IPC_MESSAGE_HANDLER(CefMsg_Request, OnRequest) + IPC_MESSAGE_HANDLER(CefMsg_Response, OnResponse) + IPC_MESSAGE_HANDLER(CefMsg_ResponseAck, OnResponseAck) + IPC_MESSAGE_HANDLER(CefMsg_LoadRequest, LoadRequest) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + + +// RenderViewObserver::OnMessageReceived message handlers. +// ----------------------------------------------------------------------------- + +void CefBrowserImpl::OnRequest(const Cef_Request_Params& params) { + bool success = false; + std::string response; + bool expect_response_ack = false; + + TRACE_EVENT2("libcef", "CefBrowserImpl::OnRequest", + "request_id", params.request_id, + "expect_response", params.expect_response ? 1 : 0); + + if (params.user_initiated) { + // Give the user a chance to handle the request. + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr message( + new CefProcessMessageImpl(const_cast(¶ms), + false, true)); + success = handler->OnProcessMessageReceived(this, PID_BROWSER, + message.get()); + message->Detach(NULL); + } + } + } else if (params.name == "execute-code") { + // Execute code. + CefRefPtr framePtr = GetWebFrameImpl(params.frame_id); + if (framePtr.get()) { + WebFrame* web_frame = framePtr->web_frame(); + if (web_frame) { + DCHECK_EQ(params.arguments.GetSize(), (size_t)4); + + bool is_javascript = false; + std::string code, script_url; + int script_start_line = 0; + + params.arguments.GetBoolean(0, &is_javascript); + params.arguments.GetString(1, &code); + DCHECK(!code.empty()); + params.arguments.GetString(2, &script_url); + params.arguments.GetInteger(3, &script_start_line); + DCHECK_GE(script_start_line, 0); + + if (is_javascript) { + web_frame->executeScript( + WebScriptSource(base::UTF8ToUTF16(code), + GURL(script_url), + script_start_line)); + success = true; + } else { + // TODO(cef): implement support for CSS code. + NOTIMPLEMENTED(); + } + } + } + } else if (params.name == "execute-command") { + // Execute command. + CefRefPtr framePtr = GetWebFrameImpl(params.frame_id); + if (framePtr.get()) { + WebFrame* web_frame = framePtr->web_frame(); + if (web_frame) { + DCHECK_EQ(params.arguments.GetSize(), (size_t)1); + + std::string command; + + params.arguments.GetString(0, &command); + DCHECK(!command.empty()); + + if (LowerCaseEqualsASCII(command, "getsource")) { + response = web_frame->contentAsMarkup().utf8(); + success = true; + } else if (LowerCaseEqualsASCII(command, "gettext")) { + response = webkit_glue::DumpDocumentText(web_frame); + success = true; + } else if (web_frame->executeCommand(base::UTF8ToUTF16(command))) { + success = true; + } + } + } + } else if (params.name == "load-string") { + // Load a string. + CefRefPtr framePtr = GetWebFrameImpl(params.frame_id); + if (framePtr.get()) { + WebFrame* web_frame = framePtr->web_frame(); + if (web_frame) { + DCHECK_EQ(params.arguments.GetSize(), (size_t)2); + + std::string string, url; + + params.arguments.GetString(0, &string); + params.arguments.GetString(1, &url); + + web_frame->loadHTMLString(string, GURL(url)); + } + } + } else { + // Invalid request. + NOTREACHED(); + } + + if (params.expect_response) { + DCHECK_GE(params.request_id, 0); + + // Send a response to the browser. + Cef_Response_Params response_params; + response_params.request_id = params.request_id; + response_params.success = success; + response_params.response = response; + response_params.expect_response_ack = expect_response_ack; + Send(new CefHostMsg_Response(routing_id(), response_params)); + } +} + +void CefBrowserImpl::OnResponse(const Cef_Response_Params& params) { + response_manager_->RunHandler(params); + if (params.expect_response_ack) + Send(new CefHostMsg_ResponseAck(routing_id(), params.request_id)); +} + +void CefBrowserImpl::OnResponseAck(int request_id) { + response_manager_->RunAckHandler(request_id); +} + +void CefBrowserImpl::OnLoadingStateChange(bool isLoading) { + if (is_swapped_out()) + return; + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr load_handler = handler->GetLoadHandler(); + if (load_handler.get()) { + WebView* web_view = render_view()->GetWebView(); + const bool canGoBack = webkit_glue::CanGoBack(web_view); + const bool canGoForward = webkit_glue::CanGoForward(web_view); + + load_handler->OnLoadingStateChange(this, isLoading, canGoBack, + canGoForward); + } + } + } +} + +void CefBrowserImpl::OnLoadStart(blink::WebLocalFrame* frame) { + if (is_swapped_out()) + return; + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr load_handler = handler->GetLoadHandler(); + if (load_handler.get()) { + CefRefPtr cef_frame = GetWebFrameImpl(frame); + load_handler->OnLoadStart(this, cef_frame.get()); + } + } + } +} + +void CefBrowserImpl::OnLoadEnd(blink::WebLocalFrame* frame) { + if (is_swapped_out()) + return; + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr load_handler = handler->GetLoadHandler(); + if (load_handler.get()) { + CefRefPtr cef_frame = GetWebFrameImpl(frame); + int httpStatusCode = frame->dataSource()->response().httpStatusCode(); + load_handler->OnLoadEnd(this, cef_frame.get(), httpStatusCode); + } + } + } +} + +void CefBrowserImpl::OnLoadError(blink::WebLocalFrame* frame, + const blink::WebURLError& error) { + if (is_swapped_out()) + return; + + CefRefPtr app = CefContentClient::Get()->application(); + if (app.get()) { + CefRefPtr handler = + app->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr load_handler = handler->GetLoadHandler(); + if (load_handler.get()) { + CefRefPtr cef_frame = GetWebFrameImpl(frame); + const cef_errorcode_t errorCode = + static_cast(error.reason); + const std::string& errorText = error.localizedDescription.utf8(); + const GURL& failedUrl = error.unreachableURL; + load_handler->OnLoadError(this, cef_frame.get(), errorCode, errorText, + failedUrl.spec()); + } + } + } +} diff --git a/libcef/renderer/browser_impl.h b/libcef/renderer/browser_impl.h new file mode 100644 index 000000000..ee9060035 --- /dev/null +++ b/libcef/renderer/browser_impl.h @@ -0,0 +1,160 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_BROWSER_IMPL_H_ +#define CEF_LIBCEF_RENDERER_BROWSER_IMPL_H_ +#pragma once + +#include +#include +#include + +#include "include/cef_browser.h" +#include "include/cef_client.h" +#include "libcef/common/tracker.h" +#include "libcef/renderer/frame_impl.h" + +#include "base/memory/scoped_ptr.h" +#include "content/public/renderer/render_view_observer.h" + +class GURL; +struct CefMsg_LoadRequest_Params; +struct Cef_Request_Params; +struct Cef_Response_Params; +class CefContentRendererClient; +class CefResponseManager; + +namespace base { +class ListValue; +} + +// Renderer plumbing for CEF features. There is a one-to-one relationship +// between RenderView on the renderer side and RenderViewHost on the browser +// side. +// +// RenderViewObserver: Interface for observing RenderView notifications and IPC +// messages. IPC messages received by the RenderView will be forwarded to this +// RenderViewObserver implementation. IPC messages sent using +// RenderViewObserver::Send() will be forwarded to the RenderView. Use +// RenderViewObserver::routing_id() when sending IPC messages. +class CefBrowserImpl : public CefBrowser, + public content::RenderViewObserver { + public: + // Returns the browser associated with the specified RenderView. + static CefRefPtr GetBrowserForView(content::RenderView* view); + // Returns the browser associated with the specified main WebFrame. + static CefRefPtr GetBrowserForMainFrame( + blink::WebFrame* frame); + + // CefBrowser methods. + CefRefPtr GetHost() override; + bool CanGoBack() override; + void GoBack() override; + bool CanGoForward() override; + void GoForward() override; + bool IsLoading() override; + void Reload() override; + void ReloadIgnoreCache() override; + void StopLoad() override; + int GetIdentifier() override; + bool IsSame(CefRefPtr that) override; + bool IsPopup() override; + bool HasDocument() override; + CefRefPtr GetMainFrame() override; + CefRefPtr GetFocusedFrame() override; + CefRefPtr GetFrame(int64 identifier) override; + CefRefPtr GetFrame(const CefString& name) override; + size_t GetFrameCount() override; + void GetFrameIdentifiers(std::vector& identifiers) override; + void GetFrameNames(std::vector& names) override; + bool SendProcessMessage( + CefProcessId target_process, + CefRefPtr message) override; + + CefBrowserImpl(content::RenderView* render_view, + int browser_id, + bool is_popup, + bool is_windowless); + ~CefBrowserImpl() override; + + void LoadRequest(const CefMsg_LoadRequest_Params& params); + + // Avoids unnecessary string type conversions. + bool SendProcessMessage(CefProcessId target_process, + const std::string& name, + base::ListValue* arguments, + bool user_initiated); + + // Returns the matching CefFrameImpl reference or creates a new one. + CefRefPtr GetWebFrameImpl(blink::WebFrame* frame); + CefRefPtr GetWebFrameImpl(int64 frame_id); + + // Frame objects will be deleted immediately before the frame is closed. + void AddFrameObject(int64 frame_id, CefTrackNode* tracked_object); + + int browser_id() const { return browser_id_; } + bool is_popup() const { return is_popup_; } + bool is_windowless() const { return is_windowless_; } + content::RenderView* render_view() const { + return content::RenderViewObserver::render_view(); + } + + bool is_swapped_out() const; + + private: + // RenderViewObserver methods. + void OnDestruct() override; + void DidStartLoading() override; + void DidStopLoading() override; + void DidFailLoad(blink::WebLocalFrame* frame, + const blink::WebURLError& error) override; + void DidFinishLoad(blink::WebLocalFrame* frame) override; + void DidStartProvisionalLoad(blink::WebLocalFrame* frame) override; + void DidFailProvisionalLoad( + blink::WebLocalFrame* frame, + const blink::WebURLError& error) override; + void DidCommitProvisionalLoad(blink::WebLocalFrame* frame, + bool is_new_navigation) override; + void FrameDetached(blink::WebFrame* frame) override; + void FocusedNodeChanged(const blink::WebNode& node) override; + void DidCreateDataSource(blink::WebLocalFrame* frame, + blink::WebDataSource* ds) override; + bool OnMessageReceived(const IPC::Message& message) override; + + // RenderViewObserver::OnMessageReceived message handlers. + void OnRequest(const Cef_Request_Params& params); + void OnResponse(const Cef_Response_Params& params); + void OnResponseAck(int request_id); + + void OnLoadingStateChange(bool isLoading); + void OnLoadStart(blink::WebLocalFrame* frame); + void OnLoadEnd(blink::WebLocalFrame* frame); + void OnLoadError(blink::WebLocalFrame* frame, + const blink::WebURLError& error); + + // ID of the browser that this RenderView is associated with. During loading + // of cross-origin requests multiple RenderViews may be associated with the + // same browser ID. + int browser_id_; + bool is_popup_; + bool is_windowless_; + + // Map of unique frame ids to CefFrameImpl references. + typedef std::map > FrameMap; + FrameMap frames_; + + // Map of unique frame ids to CefTrackManager objects that need to be cleaned + // up when the frame is deleted. + typedef std::map > FrameObjectMap; + FrameObjectMap frame_objects_; + + // Manages response registrations. + scoped_ptr response_manager_; + + IMPLEMENT_REFCOUNTING(CefBrowserImpl); + DISALLOW_COPY_AND_ASSIGN(CefBrowserImpl); +}; + +#endif // CEF_LIBCEF_RENDERER_BROWSER_IMPL_H_ diff --git a/libcef/renderer/content_renderer_client.cc b/libcef/renderer/content_renderer_client.cc new file mode 100644 index 000000000..d9894008d --- /dev/null +++ b/libcef/renderer/content_renderer_client.cc @@ -0,0 +1,831 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/compiler_specific.h" + +#include "config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "bindings/core/v8/V8Binding.h" +#include "bindings/core/v8/V8RecursionScope.h" +MSVC_POP_WARNING(); +#undef ceil +#undef FROM_HERE +#undef LOG + +#include "libcef/renderer/content_renderer_client.h" + +#include "libcef/browser/context.h" +#include "libcef/common/cef_messages.h" +#include "libcef/common/cef_switches.h" +#include "libcef/common/content_client.h" +#include "libcef/common/request_impl.h" +#include "libcef/common/values_impl.h" +#include "libcef/renderer/browser_impl.h" +#include "libcef/renderer/render_frame_observer.h" +#include "libcef/renderer/render_message_filter.h" +#include "libcef/renderer/render_process_observer.h" +#include "libcef/renderer/thread_util.h" +#include "libcef/renderer/v8_impl.h" +#include "libcef/renderer/webkit_glue.h" + +#include "base/command_line.h" +#include "base/files/file_util.h" +#include "base/path_service.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/renderer/loadtimes_extension_bindings.h" +#include "chrome/renderer/pepper/chrome_pdf_print_client.h" +#include "chrome/renderer/printing/print_web_view_helper.h" +#include "chrome/renderer/spellchecker/spellcheck.h" +#include "chrome/renderer/spellchecker/spellcheck_provider.h" +#include "components/pdf/renderer/ppb_pdf_impl.h" +#include "components/web_cache/renderer/web_cache_render_process_observer.h" +#include "content/child/child_thread.h" +#include "content/child/worker_task_runner.h" +#include "content/common/frame_messages.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/render_process_host.h" +#include "content/public/common/content_constants.h" +#include "content/public/common/content_paths.h" +#include "content/public/renderer/render_thread.h" +#include "content/public/renderer/render_view.h" +#include "content/public/renderer/render_view_visitor.h" +#include "content/renderer/render_frame_impl.h" +#include "ipc/ipc_sync_channel.h" +#include "media/base/media.h" +#include "ppapi/c/private/ppb_pdf.h" +#include "third_party/WebKit/public/platform/WebPrerenderingSupport.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/platform/WebWorkerRunLoop.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebElement.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" +#include "third_party/WebKit/public/web/WebKit.h" +#include "third_party/WebKit/public/web/WebPluginParams.h" +#include "third_party/WebKit/public/web/WebPrerendererClient.h" +#include "third_party/WebKit/public/web/WebRuntimeFeatures.h" +#include "third_party/WebKit/public/web/WebSecurityPolicy.h" +#include "third_party/WebKit/public/web/WebView.h" +#include "v8/include/v8.h" + +#if defined(OS_WIN) +#include "base/win/iat_patch_function.h" +#endif + +namespace { + +// Stub implementation of blink::WebPrerenderingSupport. +class CefPrerenderingSupport : public blink::WebPrerenderingSupport { + private: + void add(const blink::WebPrerender& prerender) override {} + void cancel(const blink::WebPrerender& prerender) override {} + void abandon(const blink::WebPrerender& prerender) override {} +}; + +// Stub implementation of blink::WebPrerendererClient. +class CefPrerendererClient : public content::RenderViewObserver, + public blink::WebPrerendererClient { + public: + explicit CefPrerendererClient(content::RenderView* render_view) + : content::RenderViewObserver(render_view) { + DCHECK(render_view); + render_view->GetWebView()->setPrerendererClient(this); + } + + private: + ~CefPrerendererClient() override {} + + void willAddPrerender(blink::WebPrerender* prerender) override {} +}; + +// Implementation of SequencedTaskRunner for WebWorker threads. +class CefWebWorkerTaskRunner : public base::SequencedTaskRunner, + public content::WorkerTaskRunner::Observer { + public: + CefWebWorkerTaskRunner(content::WorkerTaskRunner* runner, + int worker_id) + : runner_(runner), + worker_id_(worker_id) { + DCHECK(runner_); + DCHECK_GT(worker_id_, 0); + DCHECK(RunsTasksOnCurrentThread()); + + // Adds an observer for the current thread. + runner_->AddStopObserver(this); + } + + // SequencedTaskRunner methods: + bool PostNonNestableDelayedTask( + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) override { + return PostDelayedTask(from_here, task, delay); + } + + // TaskRunner methods: + bool PostDelayedTask(const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) override { + if (delay != base::TimeDelta()) + LOG(WARNING) << "Delayed tasks are not supported on WebWorker threads"; + runner_->PostTask(worker_id_, task); + return true; + } + + bool RunsTasksOnCurrentThread() const override { + return (runner_->CurrentWorkerId() == worker_id_); + } + + // WorkerTaskRunner::Observer methods: + void OnWorkerRunLoopStopped() override { + CefContentRendererClient::Get()->RemoveWorkerTaskRunner(worker_id_); + } + + private: + content::WorkerTaskRunner* runner_; + int worker_id_; +}; + +class CefPrintWebViewHelperDelegate : + public printing::PrintWebViewHelper::Delegate { + public: + CefPrintWebViewHelperDelegate() {} + + bool CancelPrerender(content::RenderView* render_view, + int routing_id) override { + return false; + } + + blink::WebElement GetPdfElement(blink::WebLocalFrame* frame) override { + return blink::WebElement(); + } + + private: + DISALLOW_COPY_AND_ASSIGN(CefPrintWebViewHelperDelegate); +}; + +#if defined(OS_WIN) +static base::win::IATPatchFunction g_iat_patch_createdca; +HDC WINAPI CreateDCAPatch(LPCSTR driver_name, + LPCSTR device_name, + LPCSTR output, + const void* init_data) { + DCHECK(std::string("DISPLAY") == std::string(driver_name)); + DCHECK(!device_name); + DCHECK(!output); + DCHECK(!init_data); + + // CreateDC fails behind the sandbox, but not CreateCompatibleDC. + return CreateCompatibleDC(NULL); +} + +static base::win::IATPatchFunction g_iat_patch_get_font_data; +DWORD WINAPI GetFontDataPatch(HDC hdc, + DWORD table, + DWORD offset, + LPVOID buffer, + DWORD length) { + int rv = GetFontData(hdc, table, offset, buffer, length); + if (rv == GDI_ERROR && hdc) { + HFONT font = static_cast(GetCurrentObject(hdc, OBJ_FONT)); + + LOGFONT logfont; + if (GetObject(font, sizeof(LOGFONT), &logfont)) { + std::vector font_data; + content::RenderThread::Get()->PreCacheFont(logfont); + rv = GetFontData(hdc, table, offset, buffer, length); + content::RenderThread::Get()->ReleaseCachedFonts(); + } + } + return rv; +} +#endif // OS_WIN + +} // namespace + +CefContentRendererClient::CefContentRendererClient() + : devtools_agent_count_(0), + uncaught_exception_stack_size_(0), + single_process_cleanup_complete_(false) { +} + +CefContentRendererClient::~CefContentRendererClient() { +} + +// static +CefContentRendererClient* CefContentRendererClient::Get() { + return static_cast( + CefContentClient::Get()->renderer()); +} + +CefRefPtr CefContentRendererClient::GetBrowserForView( + content::RenderView* view) { + CEF_REQUIRE_RT_RETURN(NULL); + + BrowserMap::const_iterator it = browsers_.find(view); + if (it != browsers_.end()) + return it->second; + return NULL; +} + +CefRefPtr CefContentRendererClient::GetBrowserForMainFrame( + blink::WebFrame* frame) { + CEF_REQUIRE_RT_RETURN(NULL); + + BrowserMap::const_iterator it = browsers_.begin(); + for (; it != browsers_.end(); ++it) { + content::RenderView* render_view = it->second->render_view(); + if (render_view && render_view->GetWebView() && + render_view->GetWebView()->mainFrame() == frame) { + return it->second; + } + } + + return NULL; +} + +void CefContentRendererClient::OnBrowserDestroyed(CefBrowserImpl* browser) { + BrowserMap::iterator it = browsers_.begin(); + for (; it != browsers_.end(); ++it) { + if (it->second.get() == browser) { + browsers_.erase(it); + return; + } + } + + // No browser was found in the map. + NOTREACHED(); +} + +void CefContentRendererClient::WebKitInitialized() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + // Create global objects associated with the default Isolate. + CefV8IsolateCreated(); + + blink::WebRuntimeFeatures::enableMediaPlayer( + media::IsMediaLibraryInitialized()); + + // TODO(cef): Enable these once the implementation supports it. + blink::WebRuntimeFeatures::enableNotifications(false); + +#if defined(OS_WIN) + // Need to patch a few functions for font loading to work correctly. + // From chrome/renderer/chrome_render_process_observer.cc. + base::FilePath pdf; + if (PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf) && + base::PathExists(pdf)) { + g_iat_patch_createdca.Patch( + pdf.value().c_str(), "gdi32.dll", "CreateDCA", CreateDCAPatch); + g_iat_patch_get_font_data.Patch( + pdf.value().c_str(), "gdi32.dll", "GetFontData", GetFontDataPatch); + } +#endif // defined(OS_WIN) + + const CefContentClient::SchemeInfoList* schemes = + CefContentClient::Get()->GetCustomSchemes(); + if (!schemes->empty()) { + // Register the custom schemes. + CefContentClient::SchemeInfoList::const_iterator it = schemes->begin(); + for (; it != schemes->end(); ++it) { + const CefContentClient::SchemeInfo& info = *it; + const blink::WebString& scheme = + blink::WebString::fromUTF8(info.scheme_name); + if (info.is_standard) { + // Standard schemes must also be registered as CORS enabled to support + // CORS-restricted requests (for example, XMLHttpRequest redirects). + blink::WebSecurityPolicy::registerURLSchemeAsCORSEnabled(scheme); + } + if (info.is_local) + blink::WebSecurityPolicy::registerURLSchemeAsLocal(scheme); + if (info.is_display_isolated) + blink::WebSecurityPolicy::registerURLSchemeAsDisplayIsolated(scheme); + } + } + + if (!cross_origin_whitelist_entries_.empty()) { + // Add the cross-origin white list entries. + for (size_t i = 0; i < cross_origin_whitelist_entries_.size(); ++i) { + const Cef_CrossOriginWhiteListEntry_Params& entry = + cross_origin_whitelist_entries_[i]; + GURL gurl = GURL(entry.source_origin); + blink::WebSecurityPolicy::addOriginAccessWhitelistEntry( + gurl, + blink::WebString::fromUTF8(entry.target_protocol), + blink::WebString::fromUTF8(entry.target_domain), + entry.allow_target_subdomains); + } + cross_origin_whitelist_entries_.clear(); + } + + // The number of stack trace frames to capture for uncaught exceptions. + if (command_line->HasSwitch(switches::kUncaughtExceptionStackSize)) { + int uncaught_exception_stack_size = 0; + base::StringToInt( + command_line->GetSwitchValueASCII( + switches::kUncaughtExceptionStackSize), + &uncaught_exception_stack_size); + + if (uncaught_exception_stack_size > 0) { + uncaught_exception_stack_size_ = uncaught_exception_stack_size; + CefV8SetUncaughtExceptionStackSize(uncaught_exception_stack_size_); + } + } + + // Notify the render process handler. + CefRefPtr application = CefContentClient::Get()->application(); + if (application.get()) { + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (handler.get()) + handler->OnWebKitInitialized(); + } +} + +void CefContentRendererClient::OnRenderProcessShutdown() { + // Destroy global objects associated with the default Isolate. + CefV8IsolateDestroyed(); +} + +void CefContentRendererClient::DevToolsAgentAttached() { + CEF_REQUIRE_RT(); + ++devtools_agent_count_; +} + +void CefContentRendererClient::DevToolsAgentDetached() { + CEF_REQUIRE_RT(); + --devtools_agent_count_; + if (devtools_agent_count_ == 0 && uncaught_exception_stack_size_ > 0) { + // When the last DevToolsAgent is detached the stack size is set to 0. + // Restore the user-specified stack size here. + CefV8SetUncaughtExceptionStackSize(uncaught_exception_stack_size_); + + // And do the same for any WebWorker threads. + WorkerTaskRunnerMap map_copy; + + { + base::AutoLock lock_scope(worker_task_runner_lock_); + map_copy = worker_task_runner_map_; + } + + WorkerTaskRunnerMap::const_iterator it = map_copy.begin(); + for (; it != map_copy.end(); ++it) { + it->second->PostTask(FROM_HERE, + base::Bind(CefV8SetUncaughtExceptionStackSize, + uncaught_exception_stack_size_)); + } + } +} + +scoped_refptr + CefContentRendererClient::GetCurrentTaskRunner() { + // Check if currently on the render thread. + if (CEF_CURRENTLY_ON_RT()) + return render_task_runner_; + + // Check if a WebWorker exists for the current thread. + content::WorkerTaskRunner* worker_runner = + content::WorkerTaskRunner::Instance(); + int worker_id = worker_runner->CurrentWorkerId(); + if (worker_id > 0) { + base::AutoLock lock_scope(worker_task_runner_lock_); + WorkerTaskRunnerMap::const_iterator it = + worker_task_runner_map_.find(worker_id); + if (it != worker_task_runner_map_.end()) + return it->second; + + scoped_refptr task_runner = + new CefWebWorkerTaskRunner(worker_runner, worker_id); + worker_task_runner_map_[worker_id] = task_runner; + return task_runner; + } + + return NULL; +} + +scoped_refptr + CefContentRendererClient::GetWorkerTaskRunner(int worker_id) { + base::AutoLock lock_scope(worker_task_runner_lock_); + WorkerTaskRunnerMap::const_iterator it = + worker_task_runner_map_.find(worker_id); + if (it != worker_task_runner_map_.end()) + return it->second; + + return NULL; +} + +void CefContentRendererClient::RemoveWorkerTaskRunner(int worker_id) { + base::AutoLock lock_scope(worker_task_runner_lock_); + WorkerTaskRunnerMap::iterator it = worker_task_runner_map_.find(worker_id); + if (it != worker_task_runner_map_.end()) + worker_task_runner_map_.erase(it); +} + +void CefContentRendererClient::RunSingleProcessCleanup() { + DCHECK(content::RenderProcessHost::run_renderer_in_process()); + + // Make sure the render thread was actually started. + if (!render_task_runner_.get()) + return; + + if (content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { + RunSingleProcessCleanupOnUIThread(); + } else { + content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, + base::Bind(&CefContentRendererClient::RunSingleProcessCleanupOnUIThread, + base::Unretained(this))); + } + + // Wait for the render thread cleanup to complete. Spin instead of using + // base::WaitableEvent because calling Wait() is not allowed on the UI + // thread. + bool complete = false; + do { + { + base::AutoLock lock_scope(single_process_cleanup_lock_); + complete = single_process_cleanup_complete_; + } + if (!complete) + base::PlatformThread::YieldCurrentThread(); + } while (!complete); +} + +void CefContentRendererClient::RenderThreadStarted() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + render_task_runner_ = base::MessageLoopProxy::current(); + observer_.reset(new CefRenderProcessObserver()); + web_cache_observer_.reset(new web_cache::WebCacheRenderProcessObserver()); + + content::RenderThread* thread = content::RenderThread::Get(); + thread->AddObserver(observer_.get()); + thread->AddObserver(web_cache_observer_.get()); + thread->GetChannel()->AddFilter(new CefRenderMessageFilter); + thread->RegisterExtension(extensions_v8::LoadTimesExtension::Get()); + + if (!command_line->HasSwitch(switches::kDisableSpellChecking)) { + spellcheck_.reset(new SpellCheck()); + thread->AddObserver(spellcheck_.get()); + } + + if (content::RenderProcessHost::run_renderer_in_process()) { + // When running in single-process mode register as a destruction observer + // on the render thread's MessageLoop. + base::MessageLoop::current()->AddDestructionObserver(this); + } + + // Note that under Linux, the media library will normally already have + // been initialized by the Zygote before this instance became a Renderer. + base::FilePath media_path; + PathService::Get(content::DIR_MEDIA_LIBS, &media_path); + if (!media_path.empty()) + media::InitializeMediaLibrary(media_path); + + blink::WebPrerenderingSupport::initialize(new CefPrerenderingSupport()); + + // Retrieve the new render thread information synchronously. + CefProcessHostMsg_GetNewRenderThreadInfo_Params params; + thread->Send(new CefProcessHostMsg_GetNewRenderThreadInfo(¶ms)); + + // Cross-origin entries need to be added after WebKit is initialized. + cross_origin_whitelist_entries_ = params.cross_origin_whitelist_entries; + + pdf_print_client_.reset(new ChromePDFPrintClient()); + pdf::PPB_PDF_Impl::SetPrintClient(pdf_print_client_.get()); + + // Notify the render process handler. + CefRefPtr application = CefContentClient::Get()->application(); + if (application.get()) { + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr listValuePtr( + new CefListValueImpl(¶ms.extra_info, false, true)); + handler->OnRenderThreadCreated(listValuePtr.get()); + listValuePtr->Detach(NULL); + } + } +} + +void CefContentRendererClient::RenderFrameCreated( + content::RenderFrame* render_frame) { + new CefRenderFrameObserver(render_frame); + BrowserCreated(render_frame->GetRenderView(), render_frame); +} + +void CefContentRendererClient::RenderViewCreated( + content::RenderView* render_view) { + BrowserCreated(render_view, render_view->GetMainRenderFrame()); +} + +bool CefContentRendererClient::OverrideCreatePlugin( + content::RenderFrame* render_frame, + blink::WebLocalFrame* frame, + const blink::WebPluginParams& params, + blink::WebPlugin** plugin) { + CefRefPtr browser = + CefBrowserImpl::GetBrowserForMainFrame(frame->top()); + if (!browser.get() || !browser->is_windowless()) + return false; + +#if defined(ENABLE_PLUGINS) + if (base::UTF16ToASCII(params.mimeType) == content::kBrowserPluginMimeType) + return false; + + content::RenderFrameImpl* render_frame_impl = + static_cast(render_frame); + + content::WebPluginInfo info; + std::string mime_type; + bool found = false; + render_frame_impl->Send( + new FrameHostMsg_GetPluginInfo( + render_frame_impl->GetRoutingID(), + params.url, + frame->top()->document().url(), + params.mimeType.utf8(), + &found, + &info, + &mime_type)); + if (!found) + return false; + + bool flash = LowerCaseEqualsASCII(mime_type, + "application/x-shockwave-flash"); + bool silverlight = StartsWithASCII(mime_type, + "application/x-silverlight", false); + + if (flash) { + // "wmode" values of "opaque" or "transparent" are allowed. + size_t size = params.attributeNames.size(); + for (size_t i = 0; i < size; ++i) { + std::string name = params.attributeNames[i].utf8(); + if (name == "wmode") { + std::string value = params.attributeValues[i].utf8(); + if (value == "opaque" || value == "transparent") + flash = false; + break; + } + } + } + + if (flash || silverlight) { + // Force Flash and Silverlight plugins to use windowless mode. + blink::WebPluginParams params_to_use = params; + params_to_use.mimeType = blink::WebString::fromUTF8(mime_type); + + size_t size = params.attributeNames.size(); + blink::WebVector new_names(size+1), + new_values(size+1); + + for (size_t i = 0; i < size; ++i) { + new_names[i] = params.attributeNames[i]; + new_values[i] = params.attributeValues[i]; + } + + if (flash) { + new_names[size] = "wmode"; + new_values[size] = "opaque"; + } else if (silverlight) { + new_names[size] = "windowless"; + new_values[size] = "true"; + } + + params_to_use.attributeNames.swap(new_names); + params_to_use.attributeValues.swap(new_values); + + *plugin = render_frame_impl->CreatePlugin( + frame, info, params_to_use, + content::RenderFrame::POWER_SAVER_MODE_ESSENTIAL); + return true; + } +#endif // defined(ENABLE_PLUGINS) + + return false; +} + +bool CefContentRendererClient::HandleNavigation( + content::RenderFrame* render_frame, + content::DocumentState* document_state, + int opener_id, + blink::WebFrame* frame, + const blink::WebURLRequest& request, + blink::WebNavigationType type, + blink::WebNavigationPolicy default_policy, + bool is_redirect) { + CefRefPtr application = CefContentClient::Get()->application(); + if (application.get()) { + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr browserPtr = + CefBrowserImpl::GetBrowserForMainFrame(frame->top()); + DCHECK(browserPtr.get()); + if (browserPtr.get()) { + CefRefPtr framePtr = browserPtr->GetWebFrameImpl(frame); + CefRefPtr requestPtr(CefRequest::Create()); + CefRequestImpl* requestImpl = + static_cast(requestPtr.get()); + requestImpl->Set(request); + requestImpl->SetReadOnly(true); + + cef_navigation_type_t navigation_type = NAVIGATION_OTHER; + switch (type) { + case blink::WebNavigationTypeLinkClicked: + navigation_type = NAVIGATION_LINK_CLICKED; + break; + case blink::WebNavigationTypeFormSubmitted: + navigation_type = NAVIGATION_FORM_SUBMITTED; + break; + case blink::WebNavigationTypeBackForward: + navigation_type = NAVIGATION_BACK_FORWARD; + break; + case blink::WebNavigationTypeReload: + navigation_type = NAVIGATION_RELOAD; + break; + case blink::WebNavigationTypeFormResubmitted: + navigation_type = NAVIGATION_FORM_RESUBMITTED; + break; + case blink::WebNavigationTypeOther: + navigation_type = NAVIGATION_OTHER; + break; + } + + if (handler->OnBeforeNavigation(browserPtr.get(), framePtr.get(), + requestPtr.get(), navigation_type, + is_redirect)) { + return true; + } + } + } + } + + return false; +} + +void CefContentRendererClient::DidCreateScriptContext( + blink::WebFrame* frame, v8::Handle context, + int extension_group, int world_id) { + CefRefPtr browserPtr = + CefBrowserImpl::GetBrowserForMainFrame(frame->top()); + DCHECK(browserPtr.get()); + if (!browserPtr.get()) + return; + + CefRefPtr framePtr = browserPtr->GetWebFrameImpl(frame); + + v8::Isolate* isolate = blink::mainThreadIsolate(); + v8::HandleScope handle_scope(isolate); + v8::Context::Scope scope(context); + blink::V8RecursionScope recursion_scope(isolate); + + CefRefPtr contextPtr(new CefV8ContextImpl(isolate, context)); + + // Notify the render process handler. + CefRefPtr application = CefContentClient::Get()->application(); + if (application.get()) { + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (handler.get()) + handler->OnContextCreated(browserPtr.get(), framePtr.get(), contextPtr); + } +} + +const void* CefContentRendererClient::CreatePPAPIInterface( + const std::string& interface_name) { +#if defined(ENABLE_PLUGINS) + // Used for in-process PDF plugin. + if (interface_name == PPB_PDF_INTERFACE) + return pdf::PPB_PDF_Impl::GetInterface(); +#endif + return NULL; +} + +void CefContentRendererClient::WillReleaseScriptContext( + blink::WebLocalFrame* frame, + v8::Handle context, + int world_id) { + // Notify the render process handler. + CefRefPtr application = CefContentClient::Get()->application(); + if (application.get()) { + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (handler.get()) { + CefRefPtr browserPtr = + CefBrowserImpl::GetBrowserForMainFrame(frame->top()); + DCHECK(browserPtr.get()); + if (browserPtr.get()) { + CefRefPtr framePtr = browserPtr->GetWebFrameImpl(frame); + + v8::Isolate* isolate = blink::mainThreadIsolate(); + v8::HandleScope handle_scope(isolate); + v8::Context::Scope scope(context); + blink::V8RecursionScope recursion_scope(isolate); + + CefRefPtr contextPtr( + new CefV8ContextImpl(isolate, context)); + + handler->OnContextReleased(browserPtr.get(), framePtr.get(), + contextPtr); + } + } + } + + CefV8ReleaseContext(context); +} + +void CefContentRendererClient::WillDestroyCurrentMessageLoop() { + base::AutoLock lock_scope(single_process_cleanup_lock_); + single_process_cleanup_complete_ = true; +} + +void CefContentRendererClient::BrowserCreated( + content::RenderView* render_view, + content::RenderFrame* render_frame) { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + + // Retrieve the browser information synchronously. This will also register + // the routing ids with the browser info object in the browser process. + CefProcessHostMsg_GetNewBrowserInfo_Params params; + content::RenderThread::Get()->Send( + new CefProcessHostMsg_GetNewBrowserInfo( + render_view->GetRoutingID(), + render_frame->GetRoutingID(), + ¶ms)); + DCHECK_GT(params.browser_id, 0); + + // Don't create another browser object if one already exists for the view. + if (GetBrowserForView(render_view).get()) + return; + +#if defined(OS_MACOSX) + // FIXME: It would be better if this API would be a callback from the + // WebKit layer, or if it would be exposed as an WebView instance method; the + // current implementation uses a static variable, and WebKit needs to be + // patched in order to make it work for each WebView instance + render_view->GetWebView()->setUseExternalPopupMenusThisInstance( + !params.is_windowless); +#endif + + CefRefPtr browser = + new CefBrowserImpl(render_view, params.browser_id, params.is_popup, + params.is_windowless); + browsers_.insert(std::make_pair(render_view, browser)); + + new CefPrerendererClient(render_view); + new printing::PrintWebViewHelper( + render_view, + false, + true, + make_scoped_ptr( + new CefPrintWebViewHelperDelegate())); + + if (!command_line->HasSwitch(switches::kDisableSpellChecking)) + new SpellCheckProvider(render_view, spellcheck_.get()); + + // Notify the render process handler. + CefRefPtr application = CefContentClient::Get()->application(); + if (application.get()) { + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (handler.get()) + handler->OnBrowserCreated(browser.get()); + } +} + +void CefContentRendererClient::RunSingleProcessCleanupOnUIThread() { + DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)); + + // Clean up the single existing RenderProcessHost. + content::RenderProcessHost* host = NULL; + content::RenderProcessHost::iterator iterator( + content::RenderProcessHost::AllHostsIterator()); + if (!iterator.IsAtEnd()) { + host = iterator.GetCurrentValue(); + host->Cleanup(); + iterator.Advance(); + DCHECK(iterator.IsAtEnd()); + } + DCHECK(host); + + // Clear the run_renderer_in_process() flag to avoid a DCHECK in the + // RenderProcessHost destructor. + content::RenderProcessHost::SetRunRendererInProcess(false); + + // Deletion of the RenderProcessHost object will stop the render thread and + // result in a call to WillDestroyCurrentMessageLoop. + // Cleanup() will cause deletion to be posted as a task on the UI thread but + // this task will only execute when running in multi-threaded message loop + // mode (because otherwise the UI message loop has already stopped). Therefore + // we need to explicitly delete the object when not running in this mode. + if (!CefContext::Get()->settings().multi_threaded_message_loop) + delete host; +} diff --git a/libcef/renderer/content_renderer_client.h b/libcef/renderer/content_renderer_client.h new file mode 100644 index 000000000..4dde06deb --- /dev/null +++ b/libcef/renderer/content_renderer_client.h @@ -0,0 +1,150 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_CONTENT_RENDERER_CLIENT_H_ +#define CEF_LIBCEF_RENDERER_CONTENT_RENDERER_CLIENT_H_ +#pragma once + +#include +#include +#include +#include + +#include "libcef/renderer/browser_impl.h" + +#include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop/message_loop.h" +#include "base/sequenced_task_runner.h" +#include "content/public/renderer/content_renderer_client.h" + +namespace web_cache { +class WebCacheRenderProcessObserver; +} + +class CefRenderProcessObserver; +struct Cef_CrossOriginWhiteListEntry_Params; +class ChromePDFPrintClient; +class SpellCheck; + +class CefContentRendererClient : public content::ContentRendererClient, + public base::MessageLoop::DestructionObserver { + public: + CefContentRendererClient(); + ~CefContentRendererClient() override; + + // Returns the singleton CefContentRendererClient instance. + static CefContentRendererClient* Get(); + + // Returns the browser associated with the specified RenderView. + CefRefPtr GetBrowserForView(content::RenderView* view); + + // Returns the browser associated with the specified main WebFrame. + CefRefPtr GetBrowserForMainFrame(blink::WebFrame* frame); + + // Called from CefBrowserImpl::OnDestruct(). + void OnBrowserDestroyed(CefBrowserImpl* browser); + + // Render thread task runner. + base::SequencedTaskRunner* render_task_runner() const { + return render_task_runner_.get(); + } + + int uncaught_exception_stack_size() const { + return uncaught_exception_stack_size_; + } + + void WebKitInitialized(); + void OnRenderProcessShutdown(); + + void DevToolsAgentAttached(); + void DevToolsAgentDetached(); + + // Returns the task runner for the current thread. If this is a WebWorker + // thread and the task runner does not already exist it will be created. + // Returns NULL if the current thread is not a valid render process thread. + scoped_refptr GetCurrentTaskRunner(); + + // Returns the task runner for the specified worker ID or NULL if the + // specified worker ID is not valid. + scoped_refptr GetWorkerTaskRunner(int worker_id); + + // Remove the task runner associated with the specified worker ID. + void RemoveWorkerTaskRunner(int worker_id); + + // Perform cleanup work that needs to occur before shutdown when running in + // single-process mode. Blocks until cleanup is complete. + void RunSingleProcessCleanup(); + + // ContentRendererClient implementation. + void RenderThreadStarted() override; + void RenderFrameCreated(content::RenderFrame* render_frame) override; + void RenderViewCreated(content::RenderView* render_view) override; + bool OverrideCreatePlugin( + content::RenderFrame* render_frame, + blink::WebLocalFrame* frame, + const blink::WebPluginParams& params, + blink::WebPlugin** plugin) override; + bool HandleNavigation(content::RenderFrame* render_frame, + content::DocumentState* document_state, + int opener_id, + blink::WebFrame* frame, + const blink::WebURLRequest& request, + blink::WebNavigationType type, + blink::WebNavigationPolicy default_policy, + bool is_redirect) override; + void DidCreateScriptContext(blink::WebFrame* frame, + v8::Handle context, + int extension_group, + int world_id) override; + const void* CreatePPAPIInterface( + const std::string& interface_name) override; + + void WillReleaseScriptContext(blink::WebLocalFrame* frame, + v8::Handle context, + int world_id); + + // MessageLoop::DestructionObserver implementation. + void WillDestroyCurrentMessageLoop() override; + + private: + void BrowserCreated(content::RenderView* render_view, + content::RenderFrame* render_frame); + + // Perform cleanup work for single-process mode. + void RunSingleProcessCleanupOnUIThread(); + + scoped_refptr render_task_runner_; + scoped_ptr observer_; + scoped_ptr web_cache_observer_; + scoped_ptr spellcheck_; + + // Map of RenderView pointers to CefBrowserImpl references. + typedef std::map > BrowserMap; + BrowserMap browsers_; + + // Cross-origin white list entries that need to be registered with WebKit. + typedef std::vector CrossOriginList; + CrossOriginList cross_origin_whitelist_entries_; + + scoped_ptr pdf_print_client_; + + int devtools_agent_count_; + int uncaught_exception_stack_size_; + + // Map of worker thread IDs to task runners. Access must be protected by + // |worker_task_runner_lock_|. + typedef std::map > + WorkerTaskRunnerMap; + WorkerTaskRunnerMap worker_task_runner_map_; + base::Lock worker_task_runner_lock_; + + // Used in single-process mode to test when cleanup is complete. + // Access must be protected by |single_process_cleanup_lock_|. + bool single_process_cleanup_complete_; + base::Lock single_process_cleanup_lock_; +}; + +#endif // CEF_LIBCEF_RENDERER_CONTENT_RENDERER_CLIENT_H_ diff --git a/libcef/renderer/dom_document_impl.cc b/libcef/renderer/dom_document_impl.cc new file mode 100644 index 000000000..d0e47e840 --- /dev/null +++ b/libcef/renderer/dom_document_impl.cc @@ -0,0 +1,238 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/renderer/dom_document_impl.h" +#include "libcef/renderer/dom_node_impl.h" +#include "libcef/renderer/thread_util.h" + +#include "base/logging.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebElement.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebNode.h" +#include "third_party/WebKit/public/web/WebRange.h" + +using blink::WebDocument; +using blink::WebElement; +using blink::WebFrame; +using blink::WebNode; +using blink::WebRange; +using blink::WebString; +using blink::WebURL; + + +CefDOMDocumentImpl::CefDOMDocumentImpl(CefBrowserImpl* browser, + WebFrame* frame) + : browser_(browser), + frame_(frame) { + const WebDocument& document = frame_->document(); + DCHECK(!document.isNull()); +} + +CefDOMDocumentImpl::~CefDOMDocumentImpl() { + CEF_REQUIRE_RT(); + + // Verify that the Detach() method has been called. + DCHECK(frame_ == NULL); +} + +CefDOMDocumentImpl::Type CefDOMDocumentImpl::GetType() { + if (!VerifyContext()) + return DOM_DOCUMENT_TYPE_UNKNOWN; + + const WebDocument& document = frame_->document(); + if (document.isHTMLDocument()) + return DOM_DOCUMENT_TYPE_HTML; + if (document.isXHTMLDocument()) + return DOM_DOCUMENT_TYPE_XHTML; + if (document.isPluginDocument()) + return DOM_DOCUMENT_TYPE_PLUGIN; + return DOM_DOCUMENT_TYPE_UNKNOWN; +} + +CefRefPtr CefDOMDocumentImpl::GetDocument() { + const WebDocument& document = frame_->document(); + return GetOrCreateNode(document.document()); +} + +CefRefPtr CefDOMDocumentImpl::GetBody() { + const WebDocument& document = frame_->document(); + return GetOrCreateNode(document.body()); +} + +CefRefPtr CefDOMDocumentImpl::GetHead() { + WebDocument document = frame_->document(); + return GetOrCreateNode(document.head()); +} + +CefString CefDOMDocumentImpl::GetTitle() { + CefString str; + if (!VerifyContext()) + return str; + + const WebDocument& document = frame_->document(); + const WebString& title = document.title(); + if (!title.isNull()) + str = title; + + return str; +} + +CefRefPtr CefDOMDocumentImpl::GetElementById(const CefString& id) { + const WebDocument& document = frame_->document(); + return GetOrCreateNode(document.getElementById(base::string16(id))); +} + +CefRefPtr CefDOMDocumentImpl::GetFocusedNode() { + const WebDocument& document = frame_->document(); + return GetOrCreateNode(document.focusedElement()); +} + +bool CefDOMDocumentImpl::HasSelection() { + if (!VerifyContext()) + return false; + + return frame_->hasSelection(); +} + +int CefDOMDocumentImpl::GetSelectionStartOffset() { + if (!VerifyContext() || !frame_->hasSelection()) + return 0; + + const WebRange& range = frame_->selectionRange(); + if (range.isNull()) + return 0; + + return range.startOffset(); +} + +int CefDOMDocumentImpl::GetSelectionEndOffset() { + if (!VerifyContext() || !frame_->hasSelection()) + return 0; + + const WebRange& range = frame_->selectionRange(); + if (range.isNull()) + return 0; + + return range.endOffset(); +} + +CefString CefDOMDocumentImpl::GetSelectionAsMarkup() { + CefString str; + if (!VerifyContext() || !frame_->hasSelection()) + return str; + + const WebString& markup = frame_->selectionAsMarkup(); + if (!markup.isNull()) + str = markup; + + return str; +} + +CefString CefDOMDocumentImpl::GetSelectionAsText() { + CefString str; + if (!VerifyContext() || !frame_->hasSelection()) + return str; + + const WebString& text = frame_->selectionAsText(); + if (!text.isNull()) + str = text; + + return str; +} + +CefString CefDOMDocumentImpl::GetBaseURL() { + CefString str; + if (!VerifyContext()) + return str; + + const WebDocument& document = frame_->document(); + const WebURL& url = document.baseURL(); + if (!url.isNull()) { + GURL gurl = url; + str = gurl.spec(); + } + + return str; +} + +CefString CefDOMDocumentImpl::GetCompleteURL(const CefString& partialURL) { + CefString str; + if (!VerifyContext()) + return str; + + const WebDocument& document = frame_->document(); + const WebURL& url = document.completeURL(base::string16(partialURL)); + if (!url.isNull()) { + GURL gurl = url; + str = gurl.spec(); + } + + return str; +} + +CefRefPtr CefDOMDocumentImpl::GetOrCreateNode( + const blink::WebNode& node) { + if (!VerifyContext()) + return NULL; + + // Nodes may potentially be null. + if (node.isNull()) + return NULL; + + if (!node_map_.empty()) { + // Locate the existing node, if any. + NodeMap::const_iterator it = node_map_.find(node); + if (it != node_map_.end()) + return it->second; + } + + // Create the new node object. + CefRefPtr nodeImpl(new CefDOMNodeImpl(this, node)); + node_map_.insert(std::make_pair(node, nodeImpl.get())); + return nodeImpl; +} + +void CefDOMDocumentImpl::RemoveNode(const blink::WebNode& node) { + if (!VerifyContext()) + return; + + if (!node_map_.empty()) { + NodeMap::iterator it = node_map_.find(node); + if (it != node_map_.end()) + node_map_.erase(it); + } +} + +void CefDOMDocumentImpl::Detach() { + if (!VerifyContext()) + return; + + // If you hit this assert it means that you are keeping references to node + // objects beyond the valid scope. + DCHECK(node_map_.empty()); + + // If you hit this assert it means that you are keeping references to this + // document object beyond the valid scope. + DCHECK(HasOneRef()); + + if (!node_map_.empty()) { + NodeMap::const_iterator it = node_map_.begin(); + for (; it != node_map_.end(); ++it) + static_cast(it->second)->Detach(); + node_map_.clear(); + } + + frame_ = NULL; +} + +bool CefDOMDocumentImpl::VerifyContext() { + if (!CEF_CURRENTLY_ON_RT() || frame_ == NULL) { + NOTREACHED(); + return false; + } + return true; +} diff --git a/libcef/renderer/dom_document_impl.h b/libcef/renderer/dom_document_impl.h new file mode 100644 index 000000000..b38b2ab86 --- /dev/null +++ b/libcef/renderer/dom_document_impl.h @@ -0,0 +1,64 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DOM_DOCUMENT_IMPL_H_ +#define CEF_LIBCEF_DOM_DOCUMENT_IMPL_H_ +#pragma once + +#include +#include "include/cef_dom.h" + +namespace blink { +class WebFrame; +class WebNode; +}; + +class CefBrowserImpl; + +class CefDOMDocumentImpl : public CefDOMDocument { + public: + CefDOMDocumentImpl(CefBrowserImpl* browser, + blink::WebFrame* frame); + ~CefDOMDocumentImpl() override; + + // CefDOMDocument methods. + Type GetType() override; + CefRefPtr GetDocument() override; + CefRefPtr GetBody() override; + CefRefPtr GetHead() override; + CefString GetTitle() override; + CefRefPtr GetElementById(const CefString& id) override; + CefRefPtr GetFocusedNode() override; + bool HasSelection() override; + int GetSelectionStartOffset() override; + int GetSelectionEndOffset() override; + CefString GetSelectionAsMarkup() override; + CefString GetSelectionAsText() override; + CefString GetBaseURL() override; + CefString GetCompleteURL(const CefString& partialURL) override; + + CefBrowserImpl* GetBrowser() { return browser_; } + blink::WebFrame* GetFrame() { return frame_; } + + // The document maintains a map of all existing node objects. + CefRefPtr GetOrCreateNode(const blink::WebNode& node); + void RemoveNode(const blink::WebNode& node); + + // Must be called before the object is destroyed. + void Detach(); + + // Verify that the object exists and is being accessed on the UI thread. + bool VerifyContext(); + + protected: + CefBrowserImpl* browser_; + blink::WebFrame* frame_; + + typedef std::map NodeMap; + NodeMap node_map_; + + IMPLEMENT_REFCOUNTING(CefDOMDocumentImpl); +}; + +#endif // CEF_LIBCEF_DOM_DOCUMENT_IMPL_H_ diff --git a/libcef/renderer/dom_node_impl.cc b/libcef/renderer/dom_node_impl.cc new file mode 100644 index 000000000..6d4f3502e --- /dev/null +++ b/libcef/renderer/dom_node_impl.cc @@ -0,0 +1,415 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "libcef/renderer/dom_node_impl.h" +#include "libcef/common/tracker.h" +#include "libcef/renderer/browser_impl.h" +#include "libcef/renderer/dom_document_impl.h" +#include "libcef/renderer/thread_util.h" +#include "libcef/renderer/webkit_glue.h" + +#include "base/logging.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebDOMEvent.h" +#include "third_party/WebKit/public/web/WebElement.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebFormControlElement.h" +#include "third_party/WebKit/public/web/WebInputElement.h" +#include "third_party/WebKit/public/web/WebNode.h" +#include "third_party/WebKit/public/web/WebSelectElement.h" + +using blink::WebDocument; +using blink::WebDOMEvent; +using blink::WebElement; +using blink::WebFrame; +using blink::WebFormControlElement; +using blink::WebInputElement; +using blink::WebNode; +using blink::WebSelectElement; +using blink::WebString; + +CefDOMNodeImpl::CefDOMNodeImpl(CefRefPtr document, + const blink::WebNode& node) + : document_(document), + node_(node) { +} + +CefDOMNodeImpl::~CefDOMNodeImpl() { + CEF_REQUIRE_RT(); + + if (document_.get() && !node_.isNull()) { + // Remove the node from the document. + document_->RemoveNode(node_); + } +} + +CefDOMNodeImpl::Type CefDOMNodeImpl::GetType() { + if (!VerifyContext()) + return DOM_NODE_TYPE_UNSUPPORTED; + + switch (node_.nodeType()) { + case WebNode::ElementNode: + return DOM_NODE_TYPE_ELEMENT; + case WebNode::AttributeNode: + return DOM_NODE_TYPE_ATTRIBUTE; + case WebNode::TextNode: + return DOM_NODE_TYPE_TEXT; + case WebNode::CDataSectionNode: + return DOM_NODE_TYPE_CDATA_SECTION; + case WebNode::ProcessingInstructionsNode: + return DOM_NODE_TYPE_PROCESSING_INSTRUCTIONS; + case WebNode::CommentNode: + return DOM_NODE_TYPE_COMMENT; + case WebNode::DocumentNode: + return DOM_NODE_TYPE_DOCUMENT; + case WebNode::DocumentTypeNode: + return DOM_NODE_TYPE_DOCUMENT_TYPE; + case WebNode::DocumentFragmentNode: + return DOM_NODE_TYPE_DOCUMENT_FRAGMENT; + default: + return DOM_NODE_TYPE_UNSUPPORTED; + } +} + +bool CefDOMNodeImpl::IsText() { + if (!VerifyContext()) + return false; + + return node_.isTextNode(); +} + +bool CefDOMNodeImpl::IsElement() { + if (!VerifyContext()) + return false; + + return node_.isElementNode(); +} + +// Logic copied from RenderViewImpl::IsEditableNode. +bool CefDOMNodeImpl::IsEditable() { + if (!VerifyContext()) + return false; + + if (node_.isContentEditable()) + return true; + + if (node_.isElementNode()) { + const WebElement& element = node_.toConst(); + if (element.isTextFormControlElement()) + return true; + + // Also return true if it has an ARIA role of 'textbox'. + for (unsigned i = 0; i < element.attributeCount(); ++i) { + if (LowerCaseEqualsASCII(element.attributeLocalName(i), "role")) { + if (LowerCaseEqualsASCII(element.attributeValue(i), "textbox")) + return true; + break; + } + } + } + + return false; +} + +bool CefDOMNodeImpl::IsFormControlElement() { + if (!VerifyContext()) + return false; + + if (node_.isElementNode()) { + const WebElement& element = node_.toConst(); + return element.isFormControlElement(); + } + + return false; +} + +CefString CefDOMNodeImpl::GetFormControlElementType() { + CefString str; + if (!VerifyContext()) + return str; + + if (node_.isElementNode()) { + const WebElement& element = node_.toConst(); + if (element.isFormControlElement()) { + // Retrieve the type from the form control element. + const WebFormControlElement& formElement = + node_.toConst(); + + const base::string16& form_control_type = formElement.formControlType(); + str = form_control_type; + } + } + + return str; +} + +bool CefDOMNodeImpl::IsSame(CefRefPtr that) { + if (!VerifyContext()) + return false; + + CefDOMNodeImpl* impl = static_cast(that.get()); + if (!impl || !impl->VerifyContext()) + return false; + + return node_.equals(impl->node_); +} + +CefString CefDOMNodeImpl::GetName() { + CefString str; + if (!VerifyContext()) + return str; + + const WebString& name = node_.nodeName(); + if (!name.isNull()) + str = name; + + return str; +} + +CefString CefDOMNodeImpl::GetValue() { + CefString str; + if (!VerifyContext()) + return str; + + if (node_.isElementNode()) { + const WebElement& element = node_.toConst(); + if (element.isFormControlElement()) { + // Retrieve the value from the form control element. + const WebFormControlElement& formElement = + node_.toConst(); + + base::string16 value; + const base::string16& form_control_type = formElement.formControlType(); + if (form_control_type == base::ASCIIToUTF16("text")) { + const WebInputElement& input_element = + formElement.toConst(); + value = input_element.value(); + } else if (form_control_type == base::ASCIIToUTF16("select-one")) { + const WebSelectElement& select_element = + formElement.toConst(); + value = select_element.value(); + } + + base::TrimWhitespace(value, base::TRIM_LEADING, &value); + str = value; + } + } + + if (str.empty()) { + const WebString& value = node_.nodeValue(); + if (!value.isNull()) + str = value; + } + + return str; +} + +bool CefDOMNodeImpl::SetValue(const CefString& value) { + if (!VerifyContext()) + return false; + + if (node_.isElementNode()) + return false; + + return webkit_glue::SetNodeValue(node_, base::string16(value)); +} + +CefString CefDOMNodeImpl::GetAsMarkup() { + CefString str; + if (!VerifyContext()) + return str; + + const WebString& markup = node_.createMarkup(); + if (!markup.isNull()) + str = markup; + + return str; +} + +CefRefPtr CefDOMNodeImpl::GetDocument() { + if (!VerifyContext()) + return NULL; + + return document_.get(); +} + +CefRefPtr CefDOMNodeImpl::GetParent() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(node_.parentNode()); +} + +CefRefPtr CefDOMNodeImpl::GetPreviousSibling() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(node_.previousSibling()); +} + +CefRefPtr CefDOMNodeImpl::GetNextSibling() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(node_.nextSibling()); +} + +bool CefDOMNodeImpl::HasChildren() { + if (!VerifyContext()) + return false; + + return node_.hasChildNodes(); +} + +CefRefPtr CefDOMNodeImpl::GetFirstChild() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(node_.firstChild()); +} + +CefRefPtr CefDOMNodeImpl::GetLastChild() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(node_.lastChild()); +} + +CefString CefDOMNodeImpl::GetElementTagName() { + CefString str; + if (!VerifyContext()) + return str; + + if (!node_.isElementNode()) { + NOTREACHED(); + return str; + } + + const WebElement& element = node_.toConst(); + const WebString& tagname = element.tagName(); + if (!tagname.isNull()) + str = tagname; + + return str; +} + +bool CefDOMNodeImpl::HasElementAttributes() { + if (!VerifyContext()) + return false; + + if (!node_.isElementNode()) { + NOTREACHED(); + return false; + } + + const WebElement& element = node_.toConst(); + return (element.attributeCount() > 0); +} + +bool CefDOMNodeImpl::HasElementAttribute(const CefString& attrName) { + if (!VerifyContext()) + return false; + + if (!node_.isElementNode()) { + NOTREACHED(); + return false; + } + + const WebElement& element = node_.toConst(); + return element.hasAttribute(base::string16(attrName)); +} + +CefString CefDOMNodeImpl::GetElementAttribute(const CefString& attrName) { + CefString str; + if (!VerifyContext()) + return str; + + if (!node_.isElementNode()) { + NOTREACHED(); + return str; + } + + const WebElement& element = node_.toConst(); + const WebString& attr = element.getAttribute(base::string16(attrName)); + if (!attr.isNull()) + str = attr; + + return str; +} + +void CefDOMNodeImpl::GetElementAttributes(AttributeMap& attrMap) { + if (!VerifyContext()) + return; + + if (!node_.isElementNode()) { + NOTREACHED(); + return; + } + + const WebElement& element = node_.toConst(); + unsigned int len = element.attributeCount(); + if (len == 0) + return; + + for (unsigned int i = 0; i < len; ++i) { + base::string16 name = element.attributeLocalName(i); + base::string16 value = element.attributeValue(i); + attrMap.insert(std::make_pair(name, value)); + } +} + +bool CefDOMNodeImpl::SetElementAttribute(const CefString& attrName, + const CefString& value) { + if (!VerifyContext()) + return false; + + if (!node_.isElementNode()) { + NOTREACHED(); + return false; + } + + WebElement element = node_.to(); + return element.setAttribute(base::string16(attrName), + base::string16(value)); +} + +CefString CefDOMNodeImpl::GetElementInnerText() { + CefString str; + if (!VerifyContext()) + return str; + + if (!node_.isElementNode()) { + NOTREACHED(); + return str; + } + + WebElement element = node_.to(); + const WebString& text = element.innerText(); + if (!text.isNull()) + str = text; + + return str; +} + +void CefDOMNodeImpl::Detach() { + document_ = NULL; + node_.assign(WebNode()); +} + +bool CefDOMNodeImpl::VerifyContext() { + if (!document_.get()) { + NOTREACHED(); + return false; + } + if (!document_->VerifyContext()) + return false; + if (node_.isNull()) { + NOTREACHED(); + return false; + } + return true; +} diff --git a/libcef/renderer/dom_node_impl.h b/libcef/renderer/dom_node_impl.h new file mode 100644 index 000000000..d2d33ef2a --- /dev/null +++ b/libcef/renderer/dom_node_impl.h @@ -0,0 +1,61 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DOM_NODE_IMPL_H_ +#define CEF_LIBCEF_DOM_NODE_IMPL_H_ +#pragma once + +#include "include/cef_dom.h" +#include "third_party/WebKit/public/web/WebNode.h" + +class CefDOMDocumentImpl; + +class CefDOMNodeImpl : public CefDOMNode { + public: + CefDOMNodeImpl(CefRefPtr document, + const blink::WebNode& node); + ~CefDOMNodeImpl() override; + + // CefDOMNode methods. + Type GetType() override; + bool IsText() override; + bool IsElement() override; + bool IsEditable() override; + bool IsFormControlElement() override; + CefString GetFormControlElementType() override; + bool IsSame(CefRefPtr that) override; + CefString GetName() override; + CefString GetValue() override; + bool SetValue(const CefString& value) override; + CefString GetAsMarkup() override; + CefRefPtr GetDocument() override; + CefRefPtr GetParent() override; + CefRefPtr GetPreviousSibling() override; + CefRefPtr GetNextSibling() override; + bool HasChildren() override; + CefRefPtr GetFirstChild() override; + CefRefPtr GetLastChild() override; + CefString GetElementTagName() override; + bool HasElementAttributes() override; + bool HasElementAttribute(const CefString& attrName) override; + CefString GetElementAttribute(const CefString& attrName) override; + void GetElementAttributes(AttributeMap& attrMap) override; + bool SetElementAttribute(const CefString& attrName, + const CefString& value) override; + CefString GetElementInnerText() override; + + // Will be called from CefDOMDocumentImpl::Detach(). + void Detach(); + + // Verify that the object exists and is being accessed on the UI thread. + bool VerifyContext(); + + protected: + CefRefPtr document_; + blink::WebNode node_; + + IMPLEMENT_REFCOUNTING(CefDOMNodeImpl); +}; + +#endif // CEF_LIBCEF_DOM_NODE_IMPL_H_ diff --git a/libcef/renderer/frame_impl.cc b/libcef/renderer/frame_impl.cc new file mode 100644 index 000000000..64bc37739 --- /dev/null +++ b/libcef/renderer/frame_impl.cc @@ -0,0 +1,272 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/renderer/frame_impl.h" + +#include "libcef/common/cef_messages.h" +#include "libcef/common/http_header_utils.h" +#include "libcef/common/request_impl.h" +#include "libcef/renderer/browser_impl.h" +#include "libcef/renderer/dom_document_impl.h" +#include "libcef/renderer/thread_util.h" +#include "libcef/renderer/v8_impl.h" +#include "libcef/renderer/webkit_glue.h" + +#include "third_party/WebKit/public/platform/WebData.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebKit.h" +#include "third_party/WebKit/public/web/WebView.h" +#include "third_party/WebKit/public/web/WebScriptSource.h" + +using blink::WebString; + +CefFrameImpl::CefFrameImpl(CefBrowserImpl* browser, + blink::WebFrame* frame) + : browser_(browser), + frame_(frame), + frame_id_(webkit_glue::GetIdentifier(frame)) { +} + +CefFrameImpl::~CefFrameImpl() { +} + +bool CefFrameImpl::IsValid() { + CEF_REQUIRE_RT_RETURN(false); + + return (frame_ != NULL); +} + +void CefFrameImpl::Undo() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("Undo")); +} + +void CefFrameImpl::Redo() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("Redo")); +} + +void CefFrameImpl::Cut() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("Cut")); +} + +void CefFrameImpl::Copy() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("Copy")); +} + +void CefFrameImpl::Paste() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("Paste")); +} + +void CefFrameImpl::Delete() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("Delete")); +} + +void CefFrameImpl::SelectAll() { + CEF_REQUIRE_RT_RETURN_VOID(); + if (frame_) + frame_->executeCommand(WebString::fromUTF8("SelectAll")); +} + +void CefFrameImpl::ViewSource() { + NOTREACHED() << "ViewSource cannot be called from the renderer process"; +} + +void CefFrameImpl::GetSource(CefRefPtr visitor) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (frame_) { + CefString content = std::string(frame_->contentAsMarkup().utf8()); + visitor->Visit(content); + } +} + +void CefFrameImpl::GetText(CefRefPtr visitor) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (frame_) { + CefString content = webkit_glue::DumpDocumentText(frame_); + visitor->Visit(content); + } +} + +void CefFrameImpl::LoadRequest(CefRefPtr request) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (!browser_) + return; + + CefMsg_LoadRequest_Params params; + params.url = GURL(std::string(request->GetURL())); + params.method = request->GetMethod(); + params.frame_id = frame_id_; + params.first_party_for_cookies = + GURL(std::string(request->GetFirstPartyForCookies())); + + CefRequest::HeaderMap headerMap; + request->GetHeaderMap(headerMap); + if (!headerMap.empty()) + params.headers = HttpHeaderUtils::GenerateHeaders(headerMap); + + CefRefPtr postData = request->GetPostData(); + if (postData.get()) { + CefPostDataImpl* impl = static_cast(postData.get()); + params.upload_data = new net::UploadData(); + impl->Get(*params.upload_data.get()); + } + + params.load_flags = request->GetFlags(); + + browser_->LoadRequest(params); +} + +void CefFrameImpl::LoadURL(const CefString& url) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (!browser_) + return; + + CefMsg_LoadRequest_Params params; + params.url = GURL(url.ToString()); + params.method = "GET"; + params.frame_id = frame_id_; + + browser_->LoadRequest(params); +} + +void CefFrameImpl::LoadString(const CefString& string, + const CefString& url) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (frame_) { + GURL gurl = GURL(url.ToString()); + frame_->loadHTMLString(string.ToString(), gurl); + } +} + +void CefFrameImpl::ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, + int startLine) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (jsCode.empty()) + return; + if (startLine < 0) + startLine = 0; + + if (frame_) { + GURL gurl = GURL(scriptUrl.ToString()); + frame_->executeScript( + blink::WebScriptSource(jsCode.ToString16(), gurl, startLine)); + } +} + +bool CefFrameImpl::IsMain() { + CEF_REQUIRE_RT_RETURN(false); + + if (frame_) + return (frame_->parent() == NULL); + return false; +} + +bool CefFrameImpl::IsFocused() { + CEF_REQUIRE_RT_RETURN(false); + + if (frame_ && frame_->view()) + return (frame_->view()->focusedFrame() == frame_); + return false; +} + +CefString CefFrameImpl::GetName() { + CefString name; + CEF_REQUIRE_RT_RETURN(name); + + if (frame_) + name = frame_->uniqueName(); + return name; +} + +int64 CefFrameImpl::GetIdentifier() { + CEF_REQUIRE_RT_RETURN(0); + + return frame_id_; +} + +CefRefPtr CefFrameImpl::GetParent() { + CEF_REQUIRE_RT_RETURN(NULL); + + if (frame_) { + blink::WebFrame* parent = frame_->parent(); + if (parent) + return browser_->GetWebFrameImpl(parent).get(); + } + + return NULL; +} + +CefString CefFrameImpl::GetURL() { + CefString url; + CEF_REQUIRE_RT_RETURN(url); + + if (frame_) { + GURL gurl = frame_->document().url(); + url = gurl.spec(); + } + return url; +} + +CefRefPtr CefFrameImpl::GetBrowser() { + CEF_REQUIRE_RT_RETURN(NULL); + + return browser_; +} + +CefRefPtr CefFrameImpl::GetV8Context() { + CEF_REQUIRE_RT_RETURN(NULL); + + if (frame_) { + v8::Isolate* isolate = blink::mainThreadIsolate(); + v8::HandleScope handle_scope(isolate); + return new CefV8ContextImpl(isolate, frame_->mainWorldScriptContext()); + } else { + return NULL; + } +} + +void CefFrameImpl::VisitDOM(CefRefPtr visitor) { + CEF_REQUIRE_RT_RETURN_VOID(); + + if (!frame_) + return; + + // Create a CefDOMDocumentImpl object that is valid only for the scope of this + // method. + CefRefPtr documentImpl; + const blink::WebDocument& document = frame_->document(); + if (!document.isNull()) + documentImpl = new CefDOMDocumentImpl(browser_, frame_); + + visitor->Visit(documentImpl.get()); + + if (documentImpl.get()) + documentImpl->Detach(); +} + +void CefFrameImpl::Detach() { + browser_ = NULL; + frame_ = NULL; +} diff --git a/libcef/renderer/frame_impl.h b/libcef/renderer/frame_impl.h new file mode 100644 index 000000000..605346d7c --- /dev/null +++ b/libcef/renderer/frame_impl.h @@ -0,0 +1,70 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_FRAME_IMPL_H_ +#define CEF_LIBCEF_RENDERER_FRAME_IMPL_H_ +#pragma once + +#include +#include "include/cef_frame.h" +#include "include/cef_v8.h" + +class CefBrowserImpl; + +namespace blink { +class WebFrame; +} + +// Implementation of CefFrame. CefFrameImpl objects are owned by the +// CefBrowerImpl and will be detached when the browser is notified that the +// associated renderer WebFrame will close. +class CefFrameImpl : public CefFrame { + public: + CefFrameImpl(CefBrowserImpl* browser, + blink::WebFrame* frame); + ~CefFrameImpl() override; + + // CefFrame implementation. + bool IsValid() override; + void Undo() override; + void Redo() override; + void Cut() override; + void Copy() override; + void Paste() override; + void Delete() override; + void SelectAll() override; + void ViewSource() override; + void GetSource(CefRefPtr visitor) override; + void GetText(CefRefPtr visitor) override; + void LoadRequest(CefRefPtr request) override; + void LoadURL(const CefString& url) override; + void LoadString(const CefString& string, + const CefString& url) override; + void ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, + int startLine) override; + bool IsMain() override; + bool IsFocused() override; + CefString GetName() override; + int64 GetIdentifier() override; + CefRefPtr GetParent() override; + CefString GetURL() override; + CefRefPtr GetBrowser() override; + CefRefPtr GetV8Context() override; + void VisitDOM(CefRefPtr visitor) override; + + void Detach(); + + blink::WebFrame* web_frame() const { return frame_; } + + protected: + CefBrowserImpl* browser_; + blink::WebFrame* frame_; + int64 frame_id_; + + IMPLEMENT_REFCOUNTING(CefFrameImpl); + DISALLOW_EVIL_CONSTRUCTORS(CefFrameImpl); +}; + +#endif // CEF_LIBCEF_RENDERER_FRAME_IMPL_H_ diff --git a/libcef/renderer/render_frame_observer.cc b/libcef/renderer/render_frame_observer.cc new file mode 100644 index 000000000..d76462ed1 --- /dev/null +++ b/libcef/renderer/render_frame_observer.cc @@ -0,0 +1,24 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +#include "libcef/renderer/render_frame_observer.h" + +#include "libcef/renderer/content_renderer_client.h" + +#include "content/public/renderer/render_frame.h" + +CefRenderFrameObserver::CefRenderFrameObserver( + content::RenderFrame* render_frame) + : content::RenderFrameObserver(render_frame) { +} + +CefRenderFrameObserver::~CefRenderFrameObserver() { +} + +void CefRenderFrameObserver::WillReleaseScriptContext( + v8::Handle context, + int world_id) { + CefContentRendererClient::Get()->WillReleaseScriptContext( + render_frame()->GetWebFrame(), context, world_id); +} diff --git a/libcef/renderer/render_frame_observer.h b/libcef/renderer/render_frame_observer.h new file mode 100644 index 000000000..cb8cdc32c --- /dev/null +++ b/libcef/renderer/render_frame_observer.h @@ -0,0 +1,26 @@ +// Copyright 2014 The Chromium Embedded Framework Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +#ifndef LIBCEF_RENDERER_RENDER_FRAME_OBSERVER_H_ +#define LIBCEF_RENDERER_RENDER_FRAME_OBSERVER_H_ + +#include "content/public/renderer/render_frame_observer.h" + +namespace content { +class RenderFrame; +} + +class CefRenderFrameObserver : public content::RenderFrameObserver { + public: + explicit CefRenderFrameObserver(content::RenderFrame* render_frame); + ~CefRenderFrameObserver() override; + + void WillReleaseScriptContext(v8::Handle context, + int world_id) override; + + private: + DISALLOW_COPY_AND_ASSIGN(CefRenderFrameObserver); +}; + +#endif // LIBCEF_RENDERER_RENDER_FRAME_OBSERVER_H_ diff --git a/libcef/renderer/render_message_filter.cc b/libcef/renderer/render_message_filter.cc new file mode 100644 index 000000000..676b37ff0 --- /dev/null +++ b/libcef/renderer/render_message_filter.cc @@ -0,0 +1,75 @@ +/// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/renderer/render_message_filter.h" +#include "libcef/renderer/thread_util.h" +#include "libcef/common/cef_messages.h" + +#include "base/bind.h" +#include "base/message_loop/message_loop.h" +#include "content/common/devtools_messages.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/web/WebSecurityPolicy.h" +#include "url/gurl.h" +#include "url/url_util.h" + +CefRenderMessageFilter::CefRenderMessageFilter() + : sender_(NULL) { +} + +CefRenderMessageFilter::~CefRenderMessageFilter() { +} + +void CefRenderMessageFilter::OnFilterAdded(IPC::Sender* sender) { + sender_ = sender; +} + +void CefRenderMessageFilter::OnFilterRemoved() { +} + +bool CefRenderMessageFilter::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + if (message.type() == DevToolsAgentMsg_Attach::ID || + message.type() == DevToolsAgentMsg_Detach::ID) { + // Observe the DevTools messages but don't handle them. + handled = false; + } + + IPC_BEGIN_MESSAGE_MAP(CefRenderMessageFilter, message) + IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnDevToolsAgentAttach) + IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDevToolsAgentDetach) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void CefRenderMessageFilter::OnDevToolsAgentAttach( + const std::string& host_id) { + CEF_POST_TASK_RT( + base::Bind(&CefRenderMessageFilter::OnDevToolsAgentAttach_RT, this)); +} + +void CefRenderMessageFilter::OnDevToolsAgentDetach() { + // CefContentRendererClient::DevToolsAgentDetached() needs to be called after + // the IPC message has been handled by DevToolsAgent. A workaround for this is + // to first post to the IO thread and then post to the renderer thread. + base::MessageLoop::current()->PostTask(FROM_HERE, + base::Bind(&CefRenderMessageFilter::OnDevToolsAgentDetach_IOT, this)); +} + +void CefRenderMessageFilter::OnDevToolsAgentAttach_RT() { + CEF_REQUIRE_RT(); + CefContentRendererClient::Get()->DevToolsAgentAttached(); +} + +void CefRenderMessageFilter::OnDevToolsAgentDetach_IOT() { + CEF_POST_TASK_RT( + base::Bind(&CefRenderMessageFilter::OnDevToolsAgentDetach_RT, this)); +} + +void CefRenderMessageFilter::OnDevToolsAgentDetach_RT() { + CEF_REQUIRE_RT(); + CefContentRendererClient::Get()->DevToolsAgentDetached(); +} diff --git a/libcef/renderer/render_message_filter.h b/libcef/renderer/render_message_filter.h new file mode 100644 index 000000000..7ba73e123 --- /dev/null +++ b/libcef/renderer/render_message_filter.h @@ -0,0 +1,39 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_RENDER_MESSAGE_FILTER_H_ +#define CEF_LIBCEF_RENDERER_RENDER_MESSAGE_FILTER_H_ + +#include +#include "ipc/ipc_channel_proxy.h" +#include "ipc/message_filter.h" + +// This class sends and receives control messages on the renderer process. +class CefRenderMessageFilter : public IPC::MessageFilter { + public: + CefRenderMessageFilter(); + ~CefRenderMessageFilter() override; + + // IPC::ChannelProxy::MessageFilter implementation. + void OnFilterAdded(IPC::Sender* sender) override; + void OnFilterRemoved() override; + bool OnMessageReceived(const IPC::Message& message) override; + + private: + // Message handlers called on the IO thread. + void OnDevToolsAgentAttach(const std::string& host_id); + void OnDevToolsAgentDetach(); + + void OnDevToolsAgentAttach_RT(); + void OnDevToolsAgentDetach_IOT(); + void OnDevToolsAgentDetach_RT(); + + IPC::Sender* sender_; + + DISALLOW_COPY_AND_ASSIGN(CefRenderMessageFilter); +}; + + +#endif // CEF_LIBCEF_RENDERER_RENDER_MESSAGE_FILTER_H_ diff --git a/libcef/renderer/render_process_observer.cc b/libcef/renderer/render_process_observer.cc new file mode 100644 index 000000000..b0b21400b --- /dev/null +++ b/libcef/renderer/render_process_observer.cc @@ -0,0 +1,65 @@ +/// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/renderer/render_process_observer.h" +#include "libcef/common/cef_messages.h" +#include "libcef/common/net_resource_provider.h" +#include "libcef/renderer/content_renderer_client.h" + +#include "net/base/net_module.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/web/WebSecurityPolicy.h" + +CefRenderProcessObserver::CefRenderProcessObserver() { + net::NetModule::SetResourceProvider(NetResourceProvider); +} + +CefRenderProcessObserver::~CefRenderProcessObserver() { +} + +bool CefRenderProcessObserver::OnControlMessageReceived( + const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(CefRenderProcessObserver, message) + IPC_MESSAGE_HANDLER(CefProcessMsg_ModifyCrossOriginWhitelistEntry, + OnModifyCrossOriginWhitelistEntry) + IPC_MESSAGE_HANDLER(CefProcessMsg_ClearCrossOriginWhitelist, + OnClearCrossOriginWhitelist) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void CefRenderProcessObserver::WebKitInitialized() { + CefContentRendererClient::Get()->WebKitInitialized(); +} + +void CefRenderProcessObserver::OnRenderProcessShutdown() { + CefContentRendererClient::Get()->OnRenderProcessShutdown(); +} + +void CefRenderProcessObserver::OnModifyCrossOriginWhitelistEntry( + bool add, + const Cef_CrossOriginWhiteListEntry_Params& params) { + GURL gurl = GURL(params.source_origin); + if (add) { + blink::WebSecurityPolicy::addOriginAccessWhitelistEntry( + gurl, + blink::WebString::fromUTF8(params.target_protocol), + blink::WebString::fromUTF8(params.target_domain), + params.allow_target_subdomains); + } else { + blink::WebSecurityPolicy::removeOriginAccessWhitelistEntry( + gurl, + blink::WebString::fromUTF8(params.target_protocol), + blink::WebString::fromUTF8(params.target_domain), + params.allow_target_subdomains); + } +} + +void CefRenderProcessObserver::OnClearCrossOriginWhitelist() { + blink::WebSecurityPolicy::resetOriginAccessWhitelists(); +} diff --git a/libcef/renderer/render_process_observer.h b/libcef/renderer/render_process_observer.h new file mode 100644 index 000000000..68891d00a --- /dev/null +++ b/libcef/renderer/render_process_observer.h @@ -0,0 +1,35 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_RENDER_PROCESS_OBSERVER_H_ +#define CEF_LIBCEF_RENDERER_RENDER_PROCESS_OBSERVER_H_ + +#include "base/compiler_specific.h" +#include "content/public/renderer/render_process_observer.h" + +struct Cef_CrossOriginWhiteListEntry_Params; + +// This class sends and receives control messages on the renderer process. +class CefRenderProcessObserver : public content::RenderProcessObserver { + public: + CefRenderProcessObserver(); + ~CefRenderProcessObserver() override; + + // RenderProcessObserver implementation. + bool OnControlMessageReceived(const IPC::Message& message) override; + void WebKitInitialized() override; + void OnRenderProcessShutdown() override; + + private: + // Message handlers called on the render thread. + void OnModifyCrossOriginWhitelistEntry( + bool add, + const Cef_CrossOriginWhiteListEntry_Params& params); + void OnClearCrossOriginWhitelist(); + + DISALLOW_COPY_AND_ASSIGN(CefRenderProcessObserver); +}; + +#endif // CEF_LIBCEF_RENDERER_RENDER_PROCESS_OBSERVER_H_ diff --git a/libcef/renderer/render_urlrequest_impl.cc b/libcef/renderer/render_urlrequest_impl.cc new file mode 100644 index 000000000..8f537a7ae --- /dev/null +++ b/libcef/renderer/render_urlrequest_impl.cc @@ -0,0 +1,379 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "libcef/renderer/render_urlrequest_impl.h" +#include "libcef/common/request_impl.h" +#include "libcef/common/response_impl.h" + +#include "base/logging.h" +#include "base/message_loop/message_loop.h" +#include "third_party/WebKit/public/platform/Platform.h" +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/platform/WebURL.h" +#include "third_party/WebKit/public/platform/WebURLError.h" +#include "third_party/WebKit/public/platform/WebURLLoader.h" +#include "third_party/WebKit/public/platform/WebURLLoaderClient.h" +#include "third_party/WebKit/public/platform/WebURLRequest.h" +#include "third_party/WebKit/public/platform/WebURLResponse.h" + +using blink::WebString; +using blink::WebURL; +using blink::WebURLError; +using blink::WebURLLoader; +using blink::WebURLRequest; +using blink::WebURLResponse; + + +namespace { + +class CefWebURLLoaderClient : public blink::WebURLLoaderClient { + public: + CefWebURLLoaderClient(CefRenderURLRequest::Context* context, + int request_flags); + ~CefWebURLLoaderClient() override; + + // blink::WebURLLoaderClient methods. + void willSendRequest( + WebURLLoader* loader, + WebURLRequest& newRequest, + const WebURLResponse& redirectResponse) override; + void didSendData( + WebURLLoader* loader, + unsigned long long bytesSent, + unsigned long long totalBytesToBeSent) override; + void didReceiveResponse( + WebURLLoader* loader, + const WebURLResponse& response) override; + void didDownloadData(WebURLLoader* loader, + int dataLength, + int encodedDataLength) override; + void didReceiveData(WebURLLoader* loader, + const char* data, + int dataLength, + int encodedDataLength) override; + void didReceiveCachedMetadata(WebURLLoader* loader, + const char* data, + int dataLength) override; + void didFinishLoading(WebURLLoader* loader, + double finishTime, + int64_t totalEncodedDataLength) override; + void didFail(WebURLLoader* loader, + const WebURLError& error) override; + + protected: + // The context_ pointer will outlive this object. + CefRenderURLRequest::Context* context_; + int request_flags_; +}; + +} // namespace + + +// CefRenderURLRequest::Context ----------------------------------------------- + +class CefRenderURLRequest::Context + : public base::RefCountedThreadSafe { + public: + Context(CefRefPtr url_request, + CefRefPtr request, + CefRefPtr client) + : url_request_(url_request), + request_(request), + client_(client), + message_loop_proxy_(base::MessageLoop::current()->message_loop_proxy()), + status_(UR_IO_PENDING), + error_code_(ERR_NONE), + upload_data_size_(0), + got_upload_progress_complete_(false), + download_data_received_(0), + download_data_total_(-1) { + // Mark the request as read-only. + static_cast(request_.get())->SetReadOnly(true); + } + + inline bool CalledOnValidThread() { + return message_loop_proxy_->BelongsToCurrentThread(); + } + + bool Start() { + DCHECK(CalledOnValidThread()); + + GURL url = GURL(request_->GetURL().ToString()); + if (!url.is_valid()) + return false; + + loader_.reset(blink::Platform::current()->createURLLoader()); + url_client_.reset(new CefWebURLLoaderClient(this, request_->GetFlags())); + + WebURLRequest urlRequest; + static_cast(request_.get())->Get(urlRequest); + + if (urlRequest.reportUploadProgress()) { + // Attempt to determine the upload data size. + CefRefPtr post_data = request_->GetPostData(); + if (post_data.get()) { + CefPostData::ElementVector elements; + post_data->GetElements(elements); + if (elements.size() == 1 && elements[0]->GetType() == PDE_TYPE_BYTES) { + CefPostDataElementImpl* impl = + static_cast(elements[0].get()); + upload_data_size_ = impl->GetBytesCount(); + } + } + } + + loader_->loadAsynchronously(urlRequest, url_client_.get()); + return true; + } + + void Cancel() { + DCHECK(CalledOnValidThread()); + + // The request may already be complete. + if (!loader_.get() || status_ != UR_IO_PENDING) + return; + + status_ = UR_CANCELED; + error_code_ = ERR_ABORTED; + + // Will result in a call to OnError(). + loader_->cancel(); + } + + void OnResponse(const WebURLResponse& response) { + DCHECK(CalledOnValidThread()); + + response_ = CefResponse::Create(); + CefResponseImpl* responseImpl = + static_cast(response_.get()); + responseImpl->Set(response); + responseImpl->SetReadOnly(true); + + download_data_total_ = response.expectedContentLength(); + } + + void OnError(const WebURLError& error) { + DCHECK(CalledOnValidThread()); + + if (status_ == UR_IO_PENDING) { + status_ = UR_FAILED; + error_code_ = static_cast(error.reason); + } + + OnComplete(); + } + + void OnComplete() { + DCHECK(CalledOnValidThread()); + + if (status_ == UR_IO_PENDING) { + status_ = UR_SUCCESS; + NotifyUploadProgressIfNecessary(); + } + + if (loader_.get()) + loader_.reset(NULL); + + DCHECK(url_request_.get()); + client_->OnRequestComplete(url_request_.get()); + + // This may result in the Context object being deleted. + url_request_ = NULL; + } + + void OnDownloadProgress(int64 current) { + DCHECK(CalledOnValidThread()); + DCHECK(url_request_.get()); + + NotifyUploadProgressIfNecessary(); + + download_data_received_ += current; + client_->OnDownloadProgress(url_request_.get(), download_data_received_, + download_data_total_); + } + + void OnDownloadData(const char* data, int dataLength) { + DCHECK(CalledOnValidThread()); + DCHECK(url_request_.get()); + client_->OnDownloadData(url_request_.get(), data, dataLength); + } + + void OnUploadProgress(int64 current, int64 total) { + DCHECK(CalledOnValidThread()); + DCHECK(url_request_.get()); + if (current == total) + got_upload_progress_complete_ = true; + client_->OnUploadProgress(url_request_.get(), current, total); + } + + CefRefPtr request() { return request_; } + CefRefPtr client() { return client_; } + CefURLRequest::Status status() { return status_; } + CefURLRequest::ErrorCode error_code() { return error_code_; } + CefRefPtr response() { return response_; } + + private: + friend class base::RefCountedThreadSafe; + + virtual ~Context() {} + + void NotifyUploadProgressIfNecessary() { + if (!got_upload_progress_complete_ && upload_data_size_ > 0) { + // URLFetcher sends upload notifications using a timer and will not send + // a notification if the request completes too quickly. We therefore + // send the notification here if necessary. + client_->OnUploadProgress(url_request_.get(), upload_data_size_, + upload_data_size_); + got_upload_progress_complete_ = true; + } + } + + // Members only accessed on the initialization thread. + CefRefPtr url_request_; + CefRefPtr request_; + CefRefPtr client_; + scoped_refptr message_loop_proxy_; + CefURLRequest::Status status_; + CefURLRequest::ErrorCode error_code_; + CefRefPtr response_; + scoped_ptr loader_; + scoped_ptr url_client_; + int64 upload_data_size_; + bool got_upload_progress_complete_; + int64 download_data_received_; + int64 download_data_total_; +}; + + +// CefWebURLLoaderClient -------------------------------------------------- + +namespace { + +CefWebURLLoaderClient::CefWebURLLoaderClient( + CefRenderURLRequest::Context* context, + int request_flags) + : context_(context), + request_flags_(request_flags) { +} + +CefWebURLLoaderClient::~CefWebURLLoaderClient() { +} + +void CefWebURLLoaderClient::willSendRequest( + WebURLLoader* loader, + WebURLRequest& newRequest, + const WebURLResponse& redirectResponse) { +} + +void CefWebURLLoaderClient::didSendData( + WebURLLoader* loader, + unsigned long long bytesSent, + unsigned long long totalBytesToBeSent) { + if (request_flags_ & UR_FLAG_REPORT_UPLOAD_PROGRESS) + context_->OnUploadProgress(bytesSent, totalBytesToBeSent); +} + +void CefWebURLLoaderClient::didReceiveResponse( + WebURLLoader* loader, + const WebURLResponse& response) { + context_->OnResponse(response); +} + +void CefWebURLLoaderClient::didDownloadData(WebURLLoader* loader, + int dataLength, + int encodedDataLength) { +} + +void CefWebURLLoaderClient::didReceiveData(WebURLLoader* loader, + const char* data, + int dataLength, + int encodedDataLength) { + context_->OnDownloadProgress(dataLength); + + if (!(request_flags_ & UR_FLAG_NO_DOWNLOAD_DATA)) + context_->OnDownloadData(data, dataLength); +} + +void CefWebURLLoaderClient::didReceiveCachedMetadata(WebURLLoader* loader, + const char* data, + int dataLength) { +} + +void CefWebURLLoaderClient::didFinishLoading(WebURLLoader* loader, + double finishTime, + int64_t totalEncodedDataLength) { + context_->OnComplete(); +} + +void CefWebURLLoaderClient::didFail(WebURLLoader* loader, + const WebURLError& error) { + context_->OnError(error); +} + + +} // namespace + + +// CefRenderURLRequest -------------------------------------------------------- + +CefRenderURLRequest::CefRenderURLRequest( + CefRefPtr request, + CefRefPtr client) { + context_ = new Context(this, request, client); +} + +CefRenderURLRequest::~CefRenderURLRequest() { +} + +bool CefRenderURLRequest::Start() { + if (!VerifyContext()) + return false; + return context_->Start(); +} + +CefRefPtr CefRenderURLRequest::GetRequest() { + if (!VerifyContext()) + return NULL; + return context_->request(); +} + +CefRefPtr CefRenderURLRequest::GetClient() { + if (!VerifyContext()) + return NULL; + return context_->client(); +} + +CefURLRequest::Status CefRenderURLRequest::GetRequestStatus() { + if (!VerifyContext()) + return UR_UNKNOWN; + return context_->status(); +} + +CefURLRequest::ErrorCode CefRenderURLRequest::GetRequestError() { + if (!VerifyContext()) + return ERR_NONE; + return context_->error_code(); +} + +CefRefPtr CefRenderURLRequest::GetResponse() { + if (!VerifyContext()) + return NULL; + return context_->response(); +} + +void CefRenderURLRequest::Cancel() { + if (!VerifyContext()) + return; + return context_->Cancel(); +} + +bool CefRenderURLRequest::VerifyContext() { + DCHECK(context_.get()); + if (!context_->CalledOnValidThread()) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + return true; +} diff --git a/libcef/renderer/render_urlrequest_impl.h b/libcef/renderer/render_urlrequest_impl.h new file mode 100644 index 000000000..5db7e993b --- /dev/null +++ b/libcef/renderer/render_urlrequest_impl.h @@ -0,0 +1,37 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_RENDER_URLREQUEST_IMPL_H_ +#define CEF_LIBCEF_RENDERER_RENDER_URLREQUEST_IMPL_H_ + +#include "include/cef_urlrequest.h" +#include "base/memory/ref_counted.h" + +class CefRenderURLRequest : public CefURLRequest { + public: + class Context; + + CefRenderURLRequest(CefRefPtr request, + CefRefPtr client); + ~CefRenderURLRequest() override; + + bool Start(); + + // CefURLRequest methods. + CefRefPtr GetRequest() override; + CefRefPtr GetClient() override; + Status GetRequestStatus() override; + ErrorCode GetRequestError() override; + CefRefPtr GetResponse() override; + void Cancel() override; + + private: + bool VerifyContext(); + + scoped_refptr context_; + + IMPLEMENT_REFCOUNTING(CefRenderURLRequest); +}; + +#endif // CEF_LIBCEF_RENDERER_RENDER_URLREQUEST_IMPL_H_ diff --git a/libcef/renderer/thread_util.h b/libcef/renderer/thread_util.h new file mode 100644 index 000000000..1867ef607 --- /dev/null +++ b/libcef/renderer/thread_util.h @@ -0,0 +1,59 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_THREAD_UTIL_H_ +#define CEF_LIBCEF_RENDERER_THREAD_UTIL_H_ +#pragma once + +#include "libcef/renderer/content_renderer_client.h" + +#include "base/location.h" +#include "base/logging.h" +#include "content/public/renderer/render_thread.h" + +#define CEF_CURRENTLY_ON_RT() (!!content::RenderThread::Get()) + +#define CEF_REQUIRE_RT() DCHECK(CEF_CURRENTLY_ON_RT()) + +#define CEF_REQUIRE_RT_RETURN(var) \ + if (!CEF_CURRENTLY_ON_RT()) { \ + NOTREACHED() << "called on invalid thread"; \ + return var; \ + } + +#define CEF_REQUIRE_RT_RETURN_VOID() \ + if (!CEF_CURRENTLY_ON_RT()) { \ + NOTREACHED() << "called on invalid thread"; \ + return; \ + } + +#define CEF_RENDER_LOOP() \ + (CefContentRendererClient::Get()->render_task_runner()) + +#define CEF_POST_TASK_RT(task) \ + CEF_RENDER_LOOP()->PostTask(FROM_HERE, task) +#define CEF_POST_DELAYED_TASK_RT(task, delay_ms) \ + CEF_RENDER_LOOP()->PostDelayedTask(FROM_HERE, task, \ + base::TimeDelta::FromMilliseconds(delay_ms)) + +// Use this template in conjuction with RefCountedThreadSafe when you want to +// ensure that an object is deleted on the render thread. +struct CefDeleteOnRenderThread { + template + static void Destruct(const T* x) { + if (CEF_CURRENTLY_ON_RT()) { + delete x; + } else { + if (!CEF_RENDER_LOOP()->DeleteSoon(FROM_HERE, x)) { +#if defined(UNIT_TEST) + // Only logged under unit testing because leaks at shutdown + // are acceptable under normal circumstances. + LOG(ERROR) << "DeleteSoon failed on thread " << thread; +#endif // UNIT_TEST + } + } + } +}; + +#endif // CEF_LIBCEF_RENDERER_THREAD_UTIL_H_ diff --git a/libcef/renderer/v8_impl.cc b/libcef/renderer/v8_impl.cc new file mode 100644 index 000000000..fba61140e --- /dev/null +++ b/libcef/renderer/v8_impl.cc @@ -0,0 +1,2134 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// MSVC++ requires this to be set before any other includes to get M_PI. +// Otherwise there will be compile errors in wtf/MathExtras.h. +#define _USE_MATH_DEFINES + +#include +#include + +#include "base/command_line.h" +#include "base/compiler_specific.h" + +#include "config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "core/frame/Frame.h" +#include "core/frame/LocalFrame.h" +#include "core/workers/WorkerGlobalScope.h" +#include "bindings/core/v8/ScriptController.h" +#include "bindings/core/v8/V8Binding.h" +MSVC_POP_WARNING(); +#undef FROM_HERE +#undef LOG + +#include "libcef/renderer/v8_impl.h" + +#include "libcef/common/cef_switches.h" +#include "libcef/common/content_client.h" +#include "libcef/common/task_runner_impl.h" +#include "libcef/common/tracker.h" +#include "libcef/renderer/browser_impl.h" +#include "libcef/renderer/thread_util.h" +#include "libcef/renderer/webkit_glue.h" + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "base/strings/string_number_conversions.h" +#include "base/threading/thread_local.h" +#include "third_party/WebKit/public/web/WebKit.h" +#include "third_party/WebKit/public/web/WebFrame.h" +#include "third_party/WebKit/public/web/WebLocalFrame.h" +#include "third_party/WebKit/public/web/WebScriptController.h" +#include "url/gurl.h" + +namespace { + +static const char kCefTrackObject[] = "Cef::TrackObject"; +static const char kCefContextState[] = "Cef::ContextState"; + +void MessageListenerCallbackImpl(v8::Handle message, + v8::Handle data); + +// Manages memory and state information associated with a single Isolate. +class CefV8IsolateManager { + public: + CefV8IsolateManager() + : isolate_(v8::Isolate::GetCurrent()), + task_runner_(CefContentRendererClient::Get()->GetCurrentTaskRunner()), + context_safety_impl_(IMPL_HASH), + message_listener_registered_(false), + worker_id_(0) { + DCHECK(isolate_); + DCHECK(task_runner_.get()); + + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kContextSafetyImplementation)) { + std::string value = command_line->GetSwitchValueASCII( + switches::kContextSafetyImplementation); + int mode; + if (base::StringToInt(value, &mode)) { + if (mode < 0) + context_safety_impl_ = IMPL_DISABLED; + else if (mode == 1) + context_safety_impl_ = IMPL_VALUE; + } + } + } + ~CefV8IsolateManager() { + DCHECK_EQ(isolate_, v8::Isolate::GetCurrent()); + DCHECK(context_map_.empty()); + } + + scoped_refptr GetContextState( + v8::Handle context) { + DCHECK_EQ(isolate_, v8::Isolate::GetCurrent()); + DCHECK(context.IsEmpty() || isolate_ == context->GetIsolate()); + + if (context_safety_impl_ == IMPL_DISABLED) + return scoped_refptr(); + + if (context.IsEmpty()) { + if (isolate_->InContext()) + context = isolate_->GetCurrentContext(); + else + return scoped_refptr(); + } + + if (context_safety_impl_ == IMPL_HASH) { + int hash = context->Global()->GetIdentityHash(); + ContextMap::const_iterator it = context_map_.find(hash); + if (it != context_map_.end()) + return it->second; + + scoped_refptr state = new CefV8ContextState(); + context_map_.insert(std::make_pair(hash, state)); + + return state; + } else { + v8::Handle key = + v8::String::NewFromUtf8(isolate_, kCefContextState); + + v8::Handle object = context->Global(); + v8::Handle value = object->GetHiddenValue(key); + if (!value.IsEmpty()) { + return static_cast( + v8::External::Cast(*value)->Value()); + } + + scoped_refptr state = new CefV8ContextState(); + object->SetHiddenValue(key, v8::External::New(isolate_, state.get())); + + // Reference will be released in ReleaseContext. + state->AddRef(); + + return state; + } + } + + void ReleaseContext(v8::Handle context) { + DCHECK_EQ(isolate_, v8::Isolate::GetCurrent()); + DCHECK_EQ(isolate_, context->GetIsolate()); + + if (context_safety_impl_ == IMPL_DISABLED) + return; + + if (context_safety_impl_ == IMPL_HASH) { + int hash = context->Global()->GetIdentityHash(); + ContextMap::iterator it = context_map_.find(hash); + if (it != context_map_.end()) { + it->second->Detach(); + context_map_.erase(it); + } + } else { + v8::Handle key = + v8::String::NewFromUtf8(isolate_, kCefContextState); + v8::Handle object = context->Global(); + v8::Handle value = object->GetHiddenValue(key); + if (value.IsEmpty()) + return; + + scoped_refptr state = + static_cast(v8::External::Cast(*value)->Value()); + state->Detach(); + object->DeleteHiddenValue(key); + + // Match the AddRef in GetContextState. + state->Release(); + } + } + + void AddGlobalTrackObject(CefTrackNode* object) { + DCHECK_EQ(isolate_, v8::Isolate::GetCurrent()); + global_manager_.Add(object); + } + + void DeleteGlobalTrackObject(CefTrackNode* object) { + DCHECK_EQ(isolate_, v8::Isolate::GetCurrent()); + global_manager_.Delete(object); + } + + void SetUncaughtExceptionStackSize(int stack_size) { + if (stack_size <= 0) + return; + + if (!message_listener_registered_) { + v8::V8::AddMessageListener(&MessageListenerCallbackImpl); + message_listener_registered_ = true; + } + + v8::V8::SetCaptureStackTraceForUncaughtExceptions(true, + stack_size, v8::StackTrace::kDetailed); + } + + void SetWorkerAttributes(int worker_id, const GURL& worker_url) { + worker_id_ = worker_id; + worker_url_ = worker_url; + } + + v8::Isolate* isolate() const { return isolate_; } + scoped_refptr task_runner() const { + return task_runner_; + } + + int worker_id() const { + return worker_id_; + } + + const GURL& worker_url() const { + return worker_url_; + } + + private: + v8::Isolate* isolate_; + scoped_refptr task_runner_; + + enum ContextSafetyImpl { + IMPL_DISABLED, + IMPL_HASH, + IMPL_VALUE, + }; + ContextSafetyImpl context_safety_impl_; + + // Used with IMPL_HASH. + typedef std::map > ContextMap; + ContextMap context_map_; + + // Used for globally tracked objects that are not associated with a particular + // context. + CefTrackManager global_manager_; + + // True if the message listener has been registered. + bool message_listener_registered_; + + // Attributes associated with WebWorker threads. + int worker_id_; + GURL worker_url_; +}; + +// Chromium uses the default Isolate for the main render process thread and a +// new Isolate for each WebWorker thread. Continue this pattern by tracking +// Isolate information on a per-thread basis. This implementation will need to +// be re-worked (perhaps using a map keyed on v8::Isolate::GetCurrent()) if +// in the future Chromium begins using the same Isolate across multiple threads. +class CefV8StateManager { +public: + CefV8StateManager() { + } + + void CreateIsolateManager() { + DCHECK(!current_tls_.Get()); + current_tls_.Set(new CefV8IsolateManager()); + } + + void DestroyIsolateManager() { + DCHECK(current_tls_.Get()); + delete current_tls_.Get(); + current_tls_.Set(NULL); + } + + CefV8IsolateManager* GetIsolateManager() { + CefV8IsolateManager* manager = current_tls_.Get(); + DCHECK(manager); + return manager; + } + + private: + base::ThreadLocalPointer current_tls_; +}; + +base::LazyInstance g_v8_state = LAZY_INSTANCE_INITIALIZER; + +CefV8IsolateManager* GetIsolateManager() { + return g_v8_state.Pointer()->GetIsolateManager(); +} + +class V8TrackObject : public CefTrackNode { + public: + explicit V8TrackObject(v8::Isolate* isolate) + : isolate_(isolate), + external_memory_(0) { + DCHECK(isolate_); + isolate_->AdjustAmountOfExternalAllocatedMemory( + static_cast(sizeof(V8TrackObject))); + } + ~V8TrackObject() { + isolate_->AdjustAmountOfExternalAllocatedMemory( + -static_cast(sizeof(V8TrackObject)) - external_memory_); + } + + inline int GetExternallyAllocatedMemory() { + return external_memory_; + } + + int AdjustExternallyAllocatedMemory(int change_in_bytes) { + int new_value = external_memory_ + change_in_bytes; + if (new_value < 0) { + NOTREACHED() << "External memory usage cannot be less than 0 bytes"; + change_in_bytes = -(external_memory_); + new_value = 0; + } + + if (change_in_bytes != 0) + isolate_->AdjustAmountOfExternalAllocatedMemory(change_in_bytes); + external_memory_ = new_value; + + return new_value; + } + + inline void SetAccessor(CefRefPtr accessor) { + accessor_ = accessor; + } + + inline CefRefPtr GetAccessor() { + return accessor_; + } + + inline void SetHandler(CefRefPtr handler) { + handler_ = handler; + } + + inline CefRefPtr GetHandler() { + return handler_; + } + + inline void SetUserData(CefRefPtr user_data) { + user_data_ = user_data; + } + + inline CefRefPtr GetUserData() { + return user_data_; + } + + // Attach this track object to the specified V8 object. + void AttachTo(v8::Handle object) { + object->SetHiddenValue(v8::String::NewFromUtf8(isolate_, kCefTrackObject), + v8::External::New(isolate_, this)); + } + + // Retrieve the track object for the specified V8 object. + static V8TrackObject* Unwrap(v8::Isolate* isolate, + v8::Handle object) { + DCHECK(isolate); + v8::Local value = + object->GetHiddenValue( + v8::String::NewFromUtf8(isolate, kCefTrackObject)); + if (!value.IsEmpty()) + return static_cast(v8::External::Cast(*value)->Value()); + + return NULL; + } + + private: + v8::Isolate* isolate_; + CefRefPtr accessor_; + CefRefPtr handler_; + CefRefPtr user_data_; + int external_memory_; +}; + +class V8TrackString : public CefTrackNode { + public: + explicit V8TrackString(const std::string& str) : string_(str) {} + const char* GetString() { return string_.c_str(); } + + private: + std::string string_; +}; + + +// Convert a CefString to a V8::String. +v8::Handle GetV8String(v8::Isolate* isolate, + const CefString& str) { +#if defined(CEF_STRING_TYPE_UTF16) + // Already a UTF16 string. + return v8::String::NewFromTwoByte( + isolate, + reinterpret_cast( + const_cast(str.c_str())), + v8::String::kNormalString, + str.length()); +#elif defined(CEF_STRING_TYPE_UTF8) + // Already a UTF8 string. + return v8::String::NewFromUtf8(isolate, + const_cast(str.c_str()), + v8::String::kNormalString, + str.length()); +#else + // Convert the string to UTF8. + std::string tmpStr = str; + return v8::String::NewFromUtf8(isolate, + tmpStr.c_str(), + v8::String::kNormalString, + tmpStr.length()); +#endif +} + +#if defined(CEF_STRING_TYPE_UTF16) +void v8impl_string_dtor(char16* str) { + delete [] str; +} +#elif defined(CEF_STRING_TYPE_UTF8) +void v8impl_string_dtor(char* str) { + delete [] str; +} +#endif + +// Convert a v8::String to CefString. +void GetCefString(v8::Handle str, CefString& out) { + if (str.IsEmpty()) + return; + +#if defined(CEF_STRING_TYPE_WIDE) + // Allocate enough space for a worst-case conversion. + int len = str->Utf8Length(); + if (len == 0) + return; + char* buf = new char[len + 1]; + str->WriteUtf8(buf, len + 1); + + // Perform conversion to the wide type. + cef_string_t* retws = out.GetWritableStruct(); + cef_string_utf8_to_wide(buf, len, retws); + + delete [] buf; +#else // !defined(CEF_STRING_TYPE_WIDE) +#if defined(CEF_STRING_TYPE_UTF16) + int len = str->Length(); + if (len == 0) + return; + char16* buf = new char16[len + 1]; + str->Write(reinterpret_cast(buf), 0, len + 1); +#else + // Allocate enough space for a worst-case conversion. + int len = str->Utf8Length(); + if (len == 0) + return; + char* buf = new char[len + 1]; + str->WriteUtf8(buf, len + 1); +#endif + + // Don't perform an extra string copy. + out.clear(); + cef_string_t* retws = out.GetWritableStruct(); + retws->str = buf; + retws->length = len; + retws->dtor = v8impl_string_dtor; +#endif // !defined(CEF_STRING_TYPE_WIDE) +} + +// V8 function callback. +void FunctionCallbackImpl(const v8::FunctionCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + + CefV8Handler* handler = + static_cast(v8::External::Cast(*info.Data())->Value()); + + CefV8ValueList params; + for (int i = 0; i < info.Length(); i++) + params.push_back(new CefV8ValueImpl(isolate, info[i])); + + CefString func_name; + GetCefString(v8::Handle::Cast(info.Callee()->GetName()), + func_name); + CefRefPtr object = new CefV8ValueImpl(isolate, info.This()); + CefRefPtr retval; + CefString exception; + + if (handler->Execute(func_name, object, params, retval, exception)) { + if (!exception.empty()) { + info.GetReturnValue().Set( + isolate->ThrowException( + v8::Exception::Error(GetV8String(isolate, exception)))); + return; + } else { + CefV8ValueImpl* rv = static_cast(retval.get()); + if (rv && rv->IsValid()) { + info.GetReturnValue().Set(rv->GetV8Value(true)); + return; + } + } + } + + info.GetReturnValue().SetUndefined(); +} + +// V8 Accessor callbacks +void AccessorGetterCallbackImpl( + v8::Local property, + const v8::PropertyCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + + v8::Handle obj = info.This(); + + CefRefPtr accessorPtr; + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + accessorPtr = tracker->GetAccessor(); + + if (accessorPtr.get()) { + CefRefPtr retval; + CefRefPtr object = new CefV8ValueImpl(isolate, obj); + CefString name, exception; + GetCefString(property, name); + if (accessorPtr->Get(name, object, retval, exception)) { + if (!exception.empty()) { + info.GetReturnValue().Set( + isolate->ThrowException( + v8::Exception::Error(GetV8String(isolate, exception)))); + return; + } else { + CefV8ValueImpl* rv = static_cast(retval.get()); + if (rv && rv->IsValid()) { + info.GetReturnValue().Set(rv->GetV8Value(true)); + return; + } + } + } + } + + return info.GetReturnValue().SetUndefined(); +} + +void AccessorSetterCallbackImpl( + v8::Local property, + v8::Local value, + const v8::PropertyCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + + v8::Handle obj = info.This(); + + CefRefPtr accessorPtr; + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + accessorPtr = tracker->GetAccessor(); + + if (accessorPtr.get()) { + CefRefPtr object = new CefV8ValueImpl(isolate, obj); + CefRefPtr cefValue = new CefV8ValueImpl(isolate, value); + CefString name, exception; + GetCefString(property, name); + accessorPtr->Set(name, object, cefValue, exception); + if (!exception.empty()) { + isolate->ThrowException( + v8::Exception::Error(GetV8String(isolate, exception))); + return; + } + } +} + +v8::Local CallV8Function(v8::Handle context, + v8::Handle function, + v8::Handle receiver, + int argc, + v8::Handle args[], + v8::Isolate* isolate) { + v8::Local func_rv; + + // Execute the function call using the ScriptController so that inspector + // instrumentation works. + if (CEF_CURRENTLY_ON_RT()) { + RefPtr frame = blink::toFrameIfNotDetached(context); + DCHECK(frame); + if (frame && + frame->script().canExecuteScripts(blink::AboutToExecuteScript)) { + func_rv = frame->script().callFunction(function, receiver, argc, args); + } + } else { + func_rv = blink::ScriptController::callFunction( + blink::toExecutionContext(context), + function, receiver, argc, args, isolate); + } + + return func_rv; +} + + +// V8 extension registration. + +class ExtensionWrapper : public v8::Extension { + public: + ExtensionWrapper(const char* extension_name, + const char* javascript_code, + CefV8Handler* handler) + : v8::Extension(extension_name, javascript_code), handler_(handler) { + } + + v8::Handle GetNativeFunctionTemplate( + v8::Isolate* isolate, + v8::Handle name) override { + if (!handler_) + return v8::Handle(); + + return v8::FunctionTemplate::New(isolate, + FunctionCallbackImpl, + v8::External::New(isolate, handler_)); + } + + private: + CefV8Handler* handler_; +}; + +class CefV8ExceptionImpl : public CefV8Exception { + public: + explicit CefV8ExceptionImpl(v8::Handle message) + : line_number_(0), + start_position_(0), + end_position_(0), + start_column_(0), + end_column_(0) { + if (message.IsEmpty()) + return; + + GetCefString(message->Get(), message_); + GetCefString(message->GetSourceLine(), source_line_); + + if (!message->GetScriptResourceName().IsEmpty()) + GetCefString(message->GetScriptResourceName()->ToString(), script_); + + line_number_ = message->GetLineNumber(); + start_position_ = message->GetStartPosition(); + end_position_ = message->GetEndPosition(); + start_column_ = message->GetStartColumn(); + end_column_ = message->GetEndColumn(); + } + + CefString GetMessage() override { return message_; } + CefString GetSourceLine() override { return source_line_; } + CefString GetScriptResourceName() override { return script_; } + int GetLineNumber() override { return line_number_; } + int GetStartPosition() override { return start_position_; } + int GetEndPosition() override { return end_position_; } + int GetStartColumn() override { return start_column_; } + int GetEndColumn() override { return end_column_; } + + protected: + CefString message_; + CefString source_line_; + CefString script_; + int line_number_; + int start_position_; + int end_position_; + int start_column_; + int end_column_; + + IMPLEMENT_REFCOUNTING(CefV8ExceptionImpl); +}; + +void MessageListenerCallbackImpl(v8::Handle message, + v8::Handle data) { + CefRefPtr application = CefContentClient::Get()->application(); + if (!application.get()) + return; + + CefRefPtr handler = + application->GetRenderProcessHandler(); + if (!handler.get()) + return; + + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr context = CefV8Context::GetCurrentContext(); + v8::Handle v8Stack = message->GetStackTrace(); + DCHECK(!v8Stack.IsEmpty()); + CefRefPtr stackTrace = + new CefV8StackTraceImpl(isolate, v8Stack); + + CefRefPtr exception = new CefV8ExceptionImpl(message); + + if (CEF_CURRENTLY_ON_RT()) { + handler->OnUncaughtException(context->GetBrowser(), context->GetFrame(), + context, exception, stackTrace); + } +} + +} // namespace + + +// Global functions. + +void CefV8IsolateCreated() { + g_v8_state.Pointer()->CreateIsolateManager(); +} + +void CefV8IsolateDestroyed() { + g_v8_state.Pointer()->DestroyIsolateManager(); +} + +void CefV8ReleaseContext(v8::Handle context) { + GetIsolateManager()->ReleaseContext(context); +} + +void CefV8SetUncaughtExceptionStackSize(int stack_size) { + GetIsolateManager()->SetUncaughtExceptionStackSize(stack_size); +} + +void CefV8SetWorkerAttributes(int worker_id, const GURL& worker_url) { + GetIsolateManager()->SetWorkerAttributes(worker_id, worker_url); +} + +bool CefRegisterExtension(const CefString& extension_name, + const CefString& javascript_code, + CefRefPtr handler) { + // Verify that this method was called on the correct thread. + CEF_REQUIRE_RT_RETURN(false); + + CefV8IsolateManager* isolate_manager = GetIsolateManager(); + + V8TrackString* name = new V8TrackString(extension_name); + isolate_manager->AddGlobalTrackObject(name); + V8TrackString* code = new V8TrackString(javascript_code); + isolate_manager->AddGlobalTrackObject(code); + + if (handler.get()) { + // The reference will be released when the process exits. + V8TrackObject* object = new V8TrackObject(isolate_manager->isolate()); + object->SetHandler(handler); + isolate_manager->AddGlobalTrackObject(object); + } + + ExtensionWrapper* wrapper = new ExtensionWrapper( + name->GetString(), + code->GetString(), + handler.get()); + + content::RenderThread::Get()->RegisterExtension(wrapper); + return true; +} + + +// Helper macros + +#define CEF_V8_HAS_ISOLATE() (!!GetIsolateManager()) +#define CEF_V8_REQUIRE_ISOLATE_RETURN(var) \ + if (!CEF_V8_HAS_ISOLATE()) { \ + NOTREACHED() << "V8 isolate is not valid"; \ + return var; \ + } + +#define CEF_V8_CURRENTLY_ON_MLT() \ + (!handle_.get() || handle_->BelongsToCurrentThread()) +#define CEF_V8_REQUIRE_MLT_RETURN(var) \ + CEF_V8_REQUIRE_ISOLATE_RETURN(var); \ + if (!CEF_V8_CURRENTLY_ON_MLT()) { \ + NOTREACHED() << "called on incorrect thread"; \ + return var; \ + } + +#define CEF_V8_HANDLE_IS_VALID() (handle_.get() && handle_->IsValid()) +#define CEF_V8_REQUIRE_VALID_HANDLE_RETURN(ret) \ + CEF_V8_REQUIRE_MLT_RETURN(ret); \ + if (!CEF_V8_HANDLE_IS_VALID()) { \ + NOTREACHED() << "V8 handle is not valid"; \ + return ret; \ + } + +#define CEF_V8_IS_VALID() \ + (CEF_V8_HAS_ISOLATE() && \ + CEF_V8_CURRENTLY_ON_MLT() && \ + CEF_V8_HANDLE_IS_VALID()) + +#define CEF_V8_REQUIRE_OBJECT_RETURN(ret) \ + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(ret); \ + if (type_ != TYPE_OBJECT) { \ + NOTREACHED() << "V8 value is not an object"; \ + return ret; \ + } + + +// CefV8HandleBase + +CefV8HandleBase::~CefV8HandleBase() { + DCHECK(BelongsToCurrentThread()); +} + +bool CefV8HandleBase::BelongsToCurrentThread() const { + return task_runner_->RunsTasksOnCurrentThread(); +} + +CefV8HandleBase::CefV8HandleBase(v8::Isolate* isolate, + v8::Handle context) + : isolate_(isolate) { + DCHECK(isolate_); + + CefV8IsolateManager* manager = GetIsolateManager(); + DCHECK(manager); + DCHECK_EQ(isolate_, manager->isolate()); + + task_runner_ = manager->task_runner(); + context_state_ = manager->GetContextState(context); +} + + +// CefV8Context + +// static +CefRefPtr CefV8Context::GetCurrentContext() { + CefRefPtr context; + CEF_V8_REQUIRE_ISOLATE_RETURN(context); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + if (isolate->InContext()) { + v8::HandleScope handle_scope(isolate); + context = new CefV8ContextImpl(isolate, isolate->GetCurrentContext()); + } + return context; +} + +// static +CefRefPtr CefV8Context::GetEnteredContext() { + CefRefPtr context; + CEF_V8_REQUIRE_ISOLATE_RETURN(context); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + if (isolate->InContext()) { + v8::HandleScope handle_scope(isolate); + context = new CefV8ContextImpl(isolate, isolate->GetEnteredContext()); + } + return context; +} + +// static +bool CefV8Context::InContext() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + return isolate->InContext(); +} + + +// CefV8ContextImpl + +CefV8ContextImpl::CefV8ContextImpl(v8::Isolate* isolate, + v8::Handle context) + : handle_(new Handle(isolate, context, context)) +#ifndef NDEBUG + , enter_count_(0) +#endif +{ // NOLINT(whitespace/braces) +} + +CefV8ContextImpl::~CefV8ContextImpl() { + DLOG_ASSERT(0 == enter_count_); +} + +CefRefPtr CefV8ContextImpl::GetTaskRunner() { + return new CefTaskRunnerImpl(handle_->task_runner()); +} + +bool CefV8ContextImpl::IsValid() { + return CEF_V8_IS_VALID(); +} + +CefRefPtr CefV8ContextImpl::GetBrowser() { + CefRefPtr browser; + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(browser); + + // Return NULL for WebWorkers. + if (!CEF_CURRENTLY_ON_RT()) + return browser; + + blink::WebFrame* webframe = GetWebFrame(); + if (webframe) + browser = CefBrowserImpl::GetBrowserForMainFrame(webframe->top()); + + return browser; +} + +CefRefPtr CefV8ContextImpl::GetFrame() { + CefRefPtr frame; + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(frame); + + // Return NULL for WebWorkers. + if (!CEF_CURRENTLY_ON_RT()) + return frame; + + blink::WebFrame* webframe = GetWebFrame(); + if (webframe) { + CefRefPtr browser = + CefBrowserImpl::GetBrowserForMainFrame(webframe->top()); + frame = browser->GetFrame(webkit_glue::GetIdentifier(webframe)); + } + + return frame; +} + +CefRefPtr CefV8ContextImpl::GetGlobal() { + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(NULL); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle context = GetV8Context(); + v8::Context::Scope context_scope(context); + return new CefV8ValueImpl(isolate, context->Global()); +} + +bool CefV8ContextImpl::Enter() { + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + + blink::V8PerIsolateData::from(isolate)->incrementRecursionLevel(); + handle_->GetNewV8Handle()->Enter(); +#ifndef NDEBUG + ++enter_count_; +#endif + return true; +} + +bool CefV8ContextImpl::Exit() { + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(handle_->isolate()); + + DLOG_ASSERT(enter_count_ > 0); + handle_->GetNewV8Handle()->Exit(); + blink::V8PerIsolateData::from(isolate)->decrementRecursionLevel(); +#ifndef NDEBUG + --enter_count_; +#endif + return true; +} + +bool CefV8ContextImpl::IsSame(CefRefPtr that) { + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(false); + + CefV8ContextImpl* impl = static_cast(that.get()); + if (!impl || !impl->IsValid()) + return false; + + return (handle_->GetPersistentV8Handle() == + impl->handle_->GetPersistentV8Handle()); +} + +bool CefV8ContextImpl::Eval(const CefString& code, + CefRefPtr& retval, + CefRefPtr& exception) { + CEF_V8_REQUIRE_VALID_HANDLE_RETURN(false); + + if (code.empty()) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Local context = GetV8Context(); + v8::Context::Scope context_scope(context); + v8::Local obj = context->Global(); + + // Retrieve the eval function. + v8::Local val = obj->Get(v8::String::NewFromUtf8(isolate, "eval")); + if (val.IsEmpty() || !val->IsFunction()) + return false; + + v8::Local func = v8::Local::Cast(val); + v8::Handle code_val = GetV8String(isolate, code); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + + retval = NULL; + exception = NULL; + + v8::Local func_rv = + CallV8Function(context, func, obj, 1, &code_val, handle_->isolate()); + + if (try_catch.HasCaught()) { + exception = new CefV8ExceptionImpl(try_catch.Message()); + return false; + } else if (!func_rv.IsEmpty()) { + retval = new CefV8ValueImpl(isolate, func_rv); + } + return true; +} + +v8::Handle CefV8ContextImpl::GetV8Context() { + return handle_->GetNewV8Handle(); +} + +blink::WebFrame* CefV8ContextImpl::GetWebFrame() { + CEF_REQUIRE_RT(); + v8::HandleScope handle_scope(handle_->isolate()); + v8::Context::Scope context_scope(GetV8Context()); + return blink::WebLocalFrame::frameForCurrentContext(); +} + + +// CefV8ValueImpl::Handle + +CefV8ValueImpl::Handle::Handle(v8::Isolate* isolate, + v8::Handle context, + handleType v, + CefTrackNode* tracker) + : CefV8HandleBase(isolate, context), + handle_(isolate, v), + tracker_(tracker), + should_persist_(false), + is_set_weak_(false) { +} + +CefV8ValueImpl::Handle::~Handle() { + DCHECK(BelongsToCurrentThread()); + + if (tracker_) { + if (is_set_weak_) { + if (context_state_.get()) { + // If the associated context is still valid then delete |tracker_|. + // Otherwise, |tracker_| will already have been deleted. + if (context_state_->IsValid()) + context_state_->DeleteTrackObject(tracker_); + } else { + GetIsolateManager()->DeleteGlobalTrackObject(tracker_); + } + + isolate_->AdjustAmountOfExternalAllocatedMemory( + -static_cast(sizeof(Handle))); + } else { + delete tracker_; + } + } + + // Always call Reset() on a persistent handle to avoid the + // CHECK(state() != NEAR_DEATH) in V8's PostGarbageCollectionProcessing. + handle_.Reset(); +} + +CefV8ValueImpl::Handle::handleType +CefV8ValueImpl::Handle::GetNewV8Handle(bool should_persist) { + DCHECK(IsValid()); + if (should_persist && !should_persist_) + should_persist_ = true; + return handleType::New(isolate(), handle_); +} + +CefV8ValueImpl::Handle::persistentType& +CefV8ValueImpl::Handle::GetPersistentV8Handle() { + return handle_; +} + +void CefV8ValueImpl::Handle::SetWeakIfNecessary() { + if (!BelongsToCurrentThread()) { + task_runner()->PostTask(FROM_HERE, + base::Bind(&CefV8ValueImpl::Handle::SetWeakIfNecessary, this)); + return; + } + + // Persist the handle (call SetWeak) if: + // A. The handle has been passed into a V8 function or used as a return value + // from a V8 callback, and + // B. The associated context, if any, is still valid. + if (should_persist_ && (!context_state_.get() || context_state_->IsValid())) { + is_set_weak_ = true; + + if (tracker_) { + if (context_state_.get()) { + // |tracker_| will be deleted when: + // A. The associated context is released, or + // B. Destructor is called for the weak handle. + DCHECK(context_state_->IsValid()); + context_state_->AddTrackObject(tracker_); + } else { + // |tracker_| will be deleted when: + // A. The process shuts down, or + // B. Destructor is called for the weak handle. + GetIsolateManager()->AddGlobalTrackObject(tracker_); + } + } + + isolate_->AdjustAmountOfExternalAllocatedMemory( + static_cast(sizeof(Handle))); + + // The added reference will be released in Destructor. + AddRef(); + handle_.SetWeak(this, Destructor); + } +} + +// static +void CefV8ValueImpl::Handle::Destructor( + const v8::WeakCallbackData& data) { + data.GetParameter()->Release(); +} + + +// CefV8Value + +// static +CefRefPtr CefV8Value::CreateUndefined() { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitUndefined(); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateNull() { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitNull(); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateBool(bool value) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitBool(value); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateInt(int32 value) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitInt(value); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateUInt(uint32 value) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitUInt(value); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateDouble(double value) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitDouble(value); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateDate(const CefTime& value) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitDate(value); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateString(const CefString& value) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + v8::Isolate* isolate = GetIsolateManager()->isolate(); + CefRefPtr impl = new CefV8ValueImpl(isolate); + CefString str(value); + impl->InitString(str); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateObject( + CefRefPtr accessor) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + + v8::Isolate* isolate = GetIsolateManager()->isolate(); + v8::HandleScope handle_scope(isolate); + + v8::Local context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + NOTREACHED() << "not currently in a V8 context"; + return NULL; + } + + // Create the new V8 object. + v8::Local obj = v8::Object::New(isolate); + + // Create a tracker object that will cause the user data and/or accessor + // reference to be released when the V8 object is destroyed. + V8TrackObject* tracker = new V8TrackObject(isolate); + tracker->SetAccessor(accessor); + + // Attach the tracker object. + tracker->AttachTo(obj); + + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitObject(obj, tracker); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateArray(int length) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + + v8::Isolate* isolate = GetIsolateManager()->isolate(); + v8::HandleScope handle_scope(isolate); + + v8::Local context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + NOTREACHED() << "not currently in a V8 context"; + return NULL; + } + + // Create a tracker object that will cause the user data reference to be + // released when the V8 object is destroyed. + V8TrackObject* tracker = new V8TrackObject(isolate); + + // Create the new V8 array. + v8::Local arr = v8::Array::New(isolate, length); + + // Attach the tracker object. + tracker->AttachTo(arr); + + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitObject(arr, tracker); + return impl.get(); +} + +// static +CefRefPtr CefV8Value::CreateFunction( + const CefString& name, + CefRefPtr handler) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + + if (!handler.get()) { + NOTREACHED() << "invalid parameter"; + return NULL; + } + + v8::Isolate* isolate = GetIsolateManager()->isolate(); + v8::HandleScope handle_scope(isolate); + + v8::Local context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + NOTREACHED() << "not currently in a V8 context"; + return NULL; + } + + // Create a new V8 function template. + v8::Local tmpl = v8::FunctionTemplate::New(isolate); + + v8::Local data = v8::External::New(isolate, handler.get()); + + // Set the function handler callback. + tmpl->SetCallHandler(FunctionCallbackImpl, data); + + // Retrieve the function object and set the name. + v8::Local func = tmpl->GetFunction(); + if (func.IsEmpty()) { + NOTREACHED() << "failed to create V8 function"; + return NULL; + } + + func->SetName(GetV8String(isolate, name)); + + // Create a tracker object that will cause the user data and/or handler + // reference to be released when the V8 object is destroyed. + V8TrackObject* tracker = new V8TrackObject(isolate); + tracker->SetHandler(handler); + + // Attach the tracker object. + tracker->AttachTo(func); + + // Create the CefV8ValueImpl and provide a tracker object that will cause + // the handler reference to be released when the V8 object is destroyed. + CefRefPtr impl = new CefV8ValueImpl(isolate); + impl->InitObject(func, tracker); + return impl.get(); +} + + +// CefV8ValueImpl + +CefV8ValueImpl::CefV8ValueImpl(v8::Isolate* isolate) + : isolate_(isolate), + type_(TYPE_INVALID), + rethrow_exceptions_(false) { + DCHECK(isolate_); +} + +CefV8ValueImpl::CefV8ValueImpl(v8::Isolate* isolate, + v8::Handle value) + : isolate_(isolate), + type_(TYPE_INVALID), + rethrow_exceptions_(false) { + DCHECK(isolate_); + InitFromV8Value(value); +} + +CefV8ValueImpl::~CefV8ValueImpl() { + if (type_ == TYPE_STRING) + cef_string_clear(&string_value_); + if (handle_.get()) + handle_->SetWeakIfNecessary(); +} + +void CefV8ValueImpl::InitFromV8Value(v8::Handle value) { + if (value->IsUndefined()) { + InitUndefined(); + } else if (value->IsNull()) { + InitNull(); + } else if (value->IsTrue()) { + InitBool(true); + } else if (value->IsFalse()) { + InitBool(false); + } else if (value->IsBoolean()) { + InitBool(value->ToBoolean()->Value()); + } else if (value->IsInt32()) { + InitInt(value->ToInt32()->Value()); + } else if (value->IsUint32()) { + InitUInt(value->ToUint32()->Value()); + } else if (value->IsNumber()) { + InitDouble(value->ToNumber()->Value()); + } else if (value->IsDate()) { + // Convert from milliseconds to seconds. + InitDate(CefTime(value->ToNumber()->Value() / 1000)); + } else if (value->IsString()) { + CefString rv; + GetCefString(value->ToString(), rv); + InitString(rv); + } else if (value->IsObject()) { + InitObject(value, NULL); + } +} + +void CefV8ValueImpl::InitUndefined() { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_UNDEFINED; +} + +void CefV8ValueImpl::InitNull() { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_NULL; +} + +void CefV8ValueImpl::InitBool(bool value) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_BOOL; + bool_value_ = value; +} + +void CefV8ValueImpl::InitInt(int32 value) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_INT; + int_value_ = value; +} + +void CefV8ValueImpl::InitUInt(uint32 value) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_UINT; + uint_value_ = value; +} + +void CefV8ValueImpl::InitDouble(double value) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_DOUBLE; + double_value_ = value; +} + +void CefV8ValueImpl::InitDate(const CefTime& value) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_DATE; + date_value_ = value; +} + +void CefV8ValueImpl::InitString(CefString& value) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_STRING; + // Take ownership of the underling string value. + const cef_string_t* str = value.GetStruct(); + if (str) { + string_value_ = *str; + cef_string_t* writable_struct = value.GetWritableStruct(); + writable_struct->str = NULL; + writable_struct->length = 0; + } else { + string_value_.str = NULL; + string_value_.length = 0; + } +} + +void CefV8ValueImpl::InitObject(v8::Handle value, CefTrackNode* tracker) { + DCHECK_EQ(type_, TYPE_INVALID); + type_ = TYPE_OBJECT; + handle_ = new Handle(isolate_, v8::Handle(), value, tracker); +} + +v8::Handle CefV8ValueImpl::GetV8Value(bool should_persist) { + switch (type_) { + case TYPE_UNDEFINED: + return v8::Undefined(isolate_); + case TYPE_NULL: + return v8::Null(isolate_); + case TYPE_BOOL: + return v8::Boolean::New(isolate_, bool_value_); + case TYPE_INT: + return v8::Int32::New(isolate_, int_value_); + case TYPE_UINT: + return v8::Uint32::New(isolate_, uint_value_); + case TYPE_DOUBLE: + return v8::Number::New(isolate_, double_value_); + case TYPE_DATE: + // Convert from seconds to milliseconds. + return v8::Date::New(isolate_, CefTime(date_value_).GetDoubleT() * 1000); + case TYPE_STRING: + return GetV8String(isolate_, CefString(&string_value_)); + case TYPE_OBJECT: + return handle_->GetNewV8Handle(should_persist); + default: + break; + } + + NOTREACHED() << "Invalid type for CefV8ValueImpl"; + return v8::Handle(); +} + +bool CefV8ValueImpl::IsValid() { + if (!CEF_V8_HAS_ISOLATE() || type_ == TYPE_INVALID || + (type_ == TYPE_OBJECT && + (!handle_->BelongsToCurrentThread() || !handle_->IsValid()))) { + return false; + } + return true; +} + +bool CefV8ValueImpl::IsUndefined() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_UNDEFINED); +} + +bool CefV8ValueImpl::IsNull() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_NULL); +} + +bool CefV8ValueImpl::IsBool() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_BOOL); +} + +bool CefV8ValueImpl::IsInt() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_INT || type_ == TYPE_UINT); +} + +bool CefV8ValueImpl::IsUInt() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_INT || type_ == TYPE_UINT); +} + +bool CefV8ValueImpl::IsDouble() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_INT || type_ == TYPE_UINT || type_ == TYPE_DOUBLE); +} + +bool CefV8ValueImpl::IsDate() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_DATE); +} + +bool CefV8ValueImpl::IsString() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_STRING); +} + +bool CefV8ValueImpl::IsObject() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + return (type_ == TYPE_OBJECT); +} + +bool CefV8ValueImpl::IsArray() { + CEF_V8_REQUIRE_MLT_RETURN(false); + if (type_ == TYPE_OBJECT) { + v8::HandleScope handle_scope(handle_->isolate()); + return handle_->GetNewV8Handle(false)->IsArray(); + } else { + return false; + } +} + +bool CefV8ValueImpl::IsFunction() { + CEF_V8_REQUIRE_MLT_RETURN(false); + if (type_ == TYPE_OBJECT) { + v8::HandleScope handle_scope(handle_->isolate()); + return handle_->GetNewV8Handle(false)->IsFunction(); + } else { + return false; + } +} + +bool CefV8ValueImpl::IsSame(CefRefPtr that) { + CEF_V8_REQUIRE_MLT_RETURN(false); + + CefV8ValueImpl* thatValue = static_cast(that.get()); + if (!thatValue || !thatValue->IsValid() || type_ != thatValue->type_) + return false; + + switch (type_) { + case TYPE_UNDEFINED: + case TYPE_NULL: + return true; + case TYPE_BOOL: + return (bool_value_ == thatValue->bool_value_); + case TYPE_INT: + return (int_value_ == thatValue->int_value_); + case TYPE_UINT: + return (uint_value_ == thatValue->uint_value_); + case TYPE_DOUBLE: + return (double_value_ == thatValue->double_value_); + case TYPE_DATE: + return (CefTime(date_value_).GetTimeT() == + CefTime(thatValue->date_value_).GetTimeT()); + case TYPE_STRING: + return (CefString(&string_value_) == + CefString(&thatValue->string_value_)); + case TYPE_OBJECT: { + return (handle_->GetPersistentV8Handle() == + thatValue->handle_->GetPersistentV8Handle()); + } + default: + break; + } + + return false; +} + +bool CefV8ValueImpl::GetBoolValue() { + CEF_V8_REQUIRE_ISOLATE_RETURN(false); + if (type_ == TYPE_BOOL) + return bool_value_; + return false; +} + +int32 CefV8ValueImpl::GetIntValue() { + CEF_V8_REQUIRE_ISOLATE_RETURN(0); + if (type_ == TYPE_INT || type_ == TYPE_UINT) + return int_value_; + return 0; +} + +uint32 CefV8ValueImpl::GetUIntValue() { + CEF_V8_REQUIRE_ISOLATE_RETURN(0); + if (type_ == TYPE_INT || type_ == TYPE_UINT) + return uint_value_; + return 0; +} + +double CefV8ValueImpl::GetDoubleValue() { + CEF_V8_REQUIRE_ISOLATE_RETURN(0.); + if (type_ == TYPE_DOUBLE) + return double_value_; + else if (type_ == TYPE_INT) + return int_value_; + else if (type_ == TYPE_UINT) + return uint_value_; + return 0.; +} + +CefTime CefV8ValueImpl::GetDateValue() { + CEF_V8_REQUIRE_ISOLATE_RETURN(CefTime(0.)); + if (type_ == TYPE_DATE) + return date_value_; + return CefTime(0.); +} + +CefString CefV8ValueImpl::GetStringValue() { + CefString rv; + CEF_V8_REQUIRE_ISOLATE_RETURN(rv); + if (type_ == TYPE_STRING) + rv = CefString(&string_value_); + return rv; +} + +bool CefV8ValueImpl::IsUserCreated() { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + return (tracker != NULL); +} + +bool CefV8ValueImpl::HasException() { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + return (last_exception_.get() != NULL); +} + +CefRefPtr CefV8ValueImpl::GetException() { + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + return last_exception_; +} + +bool CefV8ValueImpl::ClearException() { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + last_exception_ = NULL; + return true; +} + +bool CefV8ValueImpl::WillRethrowExceptions() { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + return rethrow_exceptions_; +} + +bool CefV8ValueImpl::SetRethrowExceptions(bool rethrow) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + rethrow_exceptions_ = rethrow; + return true; +} + +bool CefV8ValueImpl::HasValue(const CefString& key) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + return obj->Has(GetV8String(isolate, key)); +} + +bool CefV8ValueImpl::HasValue(int index) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope(handle_->isolate()); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + return obj->Has(index); +} + +bool CefV8ValueImpl::DeleteValue(const CefString& key) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool del = obj->Delete(GetV8String(isolate, key)); + return (!HasCaught(try_catch) && del); +} + +bool CefV8ValueImpl::DeleteValue(int index) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope(handle_->isolate()); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool del = obj->Delete(index); + return (!HasCaught(try_catch) && del); +} + +CefRefPtr CefV8ValueImpl::GetValue(const CefString& key) { + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + v8::Local ret_value = obj->Get(GetV8String(isolate, key)); + if (!HasCaught(try_catch) && !ret_value.IsEmpty()) + return new CefV8ValueImpl(isolate, ret_value); + return NULL; +} + +CefRefPtr CefV8ValueImpl::GetValue(int index) { + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return NULL; + } + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + v8::Local ret_value = obj->Get(v8::Number::New(isolate, index)); + if (!HasCaught(try_catch) && !ret_value.IsEmpty()) + return new CefV8ValueImpl(isolate, ret_value); + return NULL; +} + +bool CefV8ValueImpl::SetValue(const CefString& key, + CefRefPtr value, + PropertyAttribute attribute) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + CefV8ValueImpl* impl = static_cast(value.get()); + if (impl && impl->IsValid()) { + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool set; + // TODO(cef): This usage may not exactly match the previous implementation. + // Set will trigger interceptors and/or accessors whereas ForceSet will not. + // It might be better to split this functionality into separate methods. + if (attribute == V8_PROPERTY_ATTRIBUTE_NONE) { + set = obj->Set(GetV8String(isolate, key), impl->GetV8Value(true)); + } else { + set = obj->ForceSet(GetV8String(isolate, key), + impl->GetV8Value(true), + static_cast(attribute)); + } + return (!HasCaught(try_catch) && set); + } else { + NOTREACHED() << "invalid input parameter"; + return false; + } +} + +bool CefV8ValueImpl::SetValue(int index, CefRefPtr value) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + CefV8ValueImpl* impl = static_cast(value.get()); + if (impl && impl->IsValid()) { + v8::HandleScope handle_scope(handle_->isolate()); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool set = obj->Set(index, impl->GetV8Value(true)); + return (!HasCaught(try_catch) && set); + } else { + NOTREACHED() << "invalid input parameter"; + return false; + } +} + +bool CefV8ValueImpl::SetValue(const CefString& key, AccessControl settings, + PropertyAttribute attribute) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + CefRefPtr accessorPtr; + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + accessorPtr = tracker->GetAccessor(); + + // Verify that an accessor exists for this object. + if (!accessorPtr.get()) + return false; + + v8::AccessorGetterCallback getter = AccessorGetterCallbackImpl; + v8::AccessorSetterCallback setter = + (attribute & V8_PROPERTY_ATTRIBUTE_READONLY) ? + NULL : AccessorSetterCallbackImpl; + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool set = obj->SetAccessor(GetV8String(isolate, key), getter, setter, obj, + static_cast(settings), + static_cast(attribute)); + return (!HasCaught(try_catch) && set); +} + +bool CefV8ValueImpl::GetKeys(std::vector& keys) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + v8::Local arr_keys = obj->GetPropertyNames(); + uint32_t len = arr_keys->Length(); + for (uint32_t i = 0; i < len; ++i) { + v8::Local value = arr_keys->Get(v8::Integer::New(isolate, i)); + CefString str; + GetCefString(value->ToString(), str); + keys.push_back(str); + } + return true; +} + +bool CefV8ValueImpl::SetUserData(CefRefPtr user_data) { + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) { + tracker->SetUserData(user_data); + return true; + } + + return false; +} + +CefRefPtr CefV8ValueImpl::GetUserData() { + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + return tracker->GetUserData(); + + return NULL; +} + +int CefV8ValueImpl::GetExternallyAllocatedMemory() { + CEF_V8_REQUIRE_OBJECT_RETURN(0); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + return tracker->GetExternallyAllocatedMemory(); + + return 0; +} + +int CefV8ValueImpl::AdjustExternallyAllocatedMemory(int change_in_bytes) { + CEF_V8_REQUIRE_OBJECT_RETURN(0); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + v8::Handle obj = value->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + return tracker->AdjustExternallyAllocatedMemory(change_in_bytes); + + return 0; +} + +int CefV8ValueImpl::GetArrayLength() { + CEF_V8_REQUIRE_OBJECT_RETURN(0); + + v8::HandleScope handle_scope(handle_->isolate()); + v8::Handle value = handle_->GetNewV8Handle(false); + if (!value->IsArray()) { + NOTREACHED() << "V8 value is not an array"; + return 0; + } + + v8::Handle obj = value->ToObject(); + v8::Local arr = v8::Handle::Cast(obj); + return arr->Length(); +} + +CefString CefV8ValueImpl::GetFunctionName() { + CefString rv; + CEF_V8_REQUIRE_OBJECT_RETURN(rv); + + v8::HandleScope handle_scope(handle_->isolate()); + v8::Handle value = handle_->GetNewV8Handle(false); + if (!value->IsFunction()) { + NOTREACHED() << "V8 value is not a function"; + return rv; + } + + v8::Handle obj = value->ToObject(); + v8::Handle func = v8::Handle::Cast(obj); + GetCefString(v8::Handle::Cast(func->GetName()), rv); + return rv; +} + +CefRefPtr CefV8ValueImpl::GetFunctionHandler() { + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + if (!value->IsFunction()) { + NOTREACHED() << "V8 value is not a function"; + return 0; + } + + v8::Handle obj = value->ToObject(); + V8TrackObject* tracker = V8TrackObject::Unwrap(isolate, obj); + if (tracker) + return tracker->GetHandler(); + + return NULL; +} + +CefRefPtr CefV8ValueImpl::ExecuteFunction( + CefRefPtr object, + const CefV8ValueList& arguments) { + // An empty context value defaults to the current context. + CefRefPtr context; + return ExecuteFunctionWithContext(context, object, arguments); +} + +CefRefPtr CefV8ValueImpl::ExecuteFunctionWithContext( + CefRefPtr context, + CefRefPtr object, + const CefV8ValueList& arguments) { + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + v8::Isolate* isolate = handle_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle value = handle_->GetNewV8Handle(false); + if (!value->IsFunction()) { + NOTREACHED() << "V8 value is not a function"; + return 0; + } + + if (context.get() && !context->IsValid()) { + NOTREACHED() << "invalid V8 context parameter"; + return NULL; + } + if (object.get() && (!object->IsValid() || !object->IsObject())) { + NOTREACHED() << "invalid V8 object parameter"; + return NULL; + } + + int argc = arguments.size(); + if (argc > 0) { + for (int i = 0; i < argc; ++i) { + if (!arguments[i].get() || !arguments[i]->IsValid()) { + NOTREACHED() << "invalid V8 arguments parameter"; + return NULL; + } + } + } + + v8::Local context_local; + if (context.get()) { + CefV8ContextImpl* context_impl = + static_cast(context.get()); + context_local = context_impl->GetV8Context(); + } else { + context_local = isolate->GetCurrentContext(); + } + + v8::Context::Scope context_scope(context_local); + + v8::Handle obj = value->ToObject(); + v8::Handle func = v8::Handle::Cast(obj); + v8::Handle recv; + + // Default to the global object if no object was provided. + if (object.get()) { + CefV8ValueImpl* recv_impl = static_cast(object.get()); + recv = v8::Handle::Cast(recv_impl->GetV8Value(true)); + } else { + recv = context_local->Global(); + } + + v8::Handle *argv = NULL; + if (argc > 0) { + argv = new v8::Handle[argc]; + for (int i = 0; i < argc; ++i) { + argv[i] = + static_cast(arguments[i].get())->GetV8Value(true); + } + } + + CefRefPtr retval; + + { + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + + v8::Local func_rv = + CallV8Function(context_local, func, recv, argc, argv, + handle_->isolate()); + + if (!HasCaught(try_catch) && !func_rv.IsEmpty()) + retval = new CefV8ValueImpl(isolate, func_rv); + } + + if (argv) + delete [] argv; + + return retval; +} + +bool CefV8ValueImpl::HasCaught(v8::TryCatch& try_catch) { + if (try_catch.HasCaught()) { + last_exception_ = new CefV8ExceptionImpl(try_catch.Message()); + if (rethrow_exceptions_) + try_catch.ReThrow(); + return true; + } else { + if (last_exception_.get()) + last_exception_ = NULL; + return false; + } +} + + +// CefV8StackTrace + +// static +CefRefPtr CefV8StackTrace::GetCurrent(int frame_limit) { + CEF_V8_REQUIRE_ISOLATE_RETURN(NULL); + + v8::Isolate* isolate = GetIsolateManager()->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Handle stackTrace = + v8::StackTrace::CurrentStackTrace( + isolate, frame_limit, v8::StackTrace::kDetailed); + if (stackTrace.IsEmpty()) + return NULL; + return new CefV8StackTraceImpl(isolate, stackTrace); +} + + +// CefV8StackTraceImpl + +CefV8StackTraceImpl::CefV8StackTraceImpl( + v8::Isolate* isolate, + v8::Handle handle) { + int frame_count = handle->GetFrameCount(); + if (frame_count > 0) { + frames_.reserve(frame_count); + for (int i = 0; i < frame_count; ++i) + frames_.push_back(new CefV8StackFrameImpl(isolate, handle->GetFrame(i))); + } +} + +CefV8StackTraceImpl::~CefV8StackTraceImpl() { +} + +bool CefV8StackTraceImpl::IsValid() { + return true; +} + +int CefV8StackTraceImpl::GetFrameCount() { + return frames_.size(); +} + +CefRefPtr CefV8StackTraceImpl::GetFrame(int index) { + if (index < 0 || index >= static_cast(frames_.size())) + return NULL; + return frames_[index]; +} + + +// CefV8StackFrameImpl + +CefV8StackFrameImpl::CefV8StackFrameImpl( + v8::Isolate* isolate, + v8::Handle handle) + : line_number_(0), + column_(0), + is_eval_(false), + is_constructor_(false) { + if (handle.IsEmpty()) + return; + GetCefString(v8::Handle::Cast(handle->GetScriptName()), + script_name_); + GetCefString( + v8::Handle::Cast(handle->GetScriptNameOrSourceURL()), + script_name_or_source_url_); + GetCefString(v8::Handle::Cast(handle->GetFunctionName()), + function_name_); + line_number_ = handle->GetLineNumber(); + column_ = handle->GetColumn(); + is_eval_ = handle->IsEval(); + is_constructor_ = handle->IsConstructor(); +} + +CefV8StackFrameImpl::~CefV8StackFrameImpl() { +} + +bool CefV8StackFrameImpl::IsValid() { + return true; +} + +CefString CefV8StackFrameImpl::GetScriptName() { + return script_name_; +} + +CefString CefV8StackFrameImpl::GetScriptNameOrSourceURL() { + return script_name_or_source_url_; +} + +CefString CefV8StackFrameImpl::GetFunctionName() { + return function_name_; +} + +int CefV8StackFrameImpl::GetLineNumber() { + return line_number_; +} + +int CefV8StackFrameImpl::GetColumn() { + return column_; +} + +bool CefV8StackFrameImpl::IsEval() { + return is_eval_; +} + +bool CefV8StackFrameImpl::IsConstructor() { + return is_constructor_; +} diff --git a/libcef/renderer/v8_impl.h b/libcef/renderer/v8_impl.h new file mode 100644 index 000000000..4d3f40f1c --- /dev/null +++ b/libcef/renderer/v8_impl.h @@ -0,0 +1,401 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_V8_IMPL_H_ +#define CEF_LIBCEF_RENDERER_V8_IMPL_H_ +#pragma once + +#include + +#include "include/cef_v8.h" +#include "libcef/common/tracker.h" + +#include "v8/include/v8.h" +#include "base/location.h" +#include "base/logging.h" +#include "base/memory/ref_counted.h" +#include "base/sequenced_task_runner.h" + +class CefTrackNode; +class GURL; + +namespace blink { +class WebFrame; +}; + +// Call after a V8 Isolate has been created and entered for the first time. +void CefV8IsolateCreated(); + +// Call before a V8 Isolate is exited and destroyed. +void CefV8IsolateDestroyed(); + +// Call to detach all handles associated with the specified context. +void CefV8ReleaseContext(v8::Handle context); + +// Set the stack size for uncaught exceptions. +void CefV8SetUncaughtExceptionStackSize(int stack_size); + +// Set attributes associated with a WebWorker thread. +void CefV8SetWorkerAttributes(int worker_id, const GURL& worker_url); + +// Used to detach handles when the associated context is released. +class CefV8ContextState : public base::RefCounted { + public: + CefV8ContextState() : valid_(true) {} + + bool IsValid() { return valid_; } + void Detach() { + DCHECK(valid_); + valid_ = false; + track_manager_.DeleteAll(); + } + + void AddTrackObject(CefTrackNode* object) { + DCHECK(valid_); + track_manager_.Add(object); + } + + void DeleteTrackObject(CefTrackNode* object) { + DCHECK(valid_); + track_manager_.Delete(object); + } + + private: + friend class base::RefCounted; + + ~CefV8ContextState() {} + + bool valid_; + CefTrackManager track_manager_; +}; + + +// Use this template in conjuction with RefCountedThreadSafe to ensure that a +// V8 object is deleted on the correct thread. +struct CefV8DeleteOnMessageLoopThread { + template + static void Destruct(const T* x) { + if (x->task_runner()->RunsTasksOnCurrentThread()) { + delete x; + } else { + if (!x->task_runner()->DeleteSoon(FROM_HERE, x)) { +#if defined(UNIT_TEST) + // Only logged under unit testing because leaks at shutdown + // are acceptable under normal circumstances. + LOG(ERROR) << "DeleteSoon failed on thread " << thread; +#endif // UNIT_TEST + } + } + } +}; + +// Base class for V8 Handle types. +class CefV8HandleBase : + public base::RefCountedThreadSafe { + public: + // Returns true if there is no underlying context or if the underlying context + // is valid. + bool IsValid() const { + return (!context_state_.get() || context_state_->IsValid()); + } + + bool BelongsToCurrentThread() const; + + v8::Isolate* isolate() const { return isolate_; } + scoped_refptr task_runner() const { + return task_runner_; + } + + protected: + friend class base::DeleteHelper; + friend class base::RefCountedThreadSafe; + friend struct CefV8DeleteOnMessageLoopThread; + + // |context| is the context that owns this handle. If empty the current + // context will be used. + CefV8HandleBase(v8::Isolate* isolate, + v8::Handle context); + virtual ~CefV8HandleBase(); + + protected: + v8::Isolate* isolate_; + scoped_refptr task_runner_; + scoped_refptr context_state_; +}; + +// Template for V8 Handle types. This class is used to ensure that V8 objects +// are only released on the render thread. +template +class CefV8Handle : public CefV8HandleBase { + public: + typedef v8::Local handleType; + typedef v8::Persistent persistentType; + + CefV8Handle(v8::Isolate* isolate, + v8::Handle context, + handleType v) + : CefV8HandleBase(isolate, context), + handle_(isolate, v) { + } + + handleType GetNewV8Handle() { + DCHECK(IsValid()); + return handleType::New(isolate(), handle_); + } + + persistentType& GetPersistentV8Handle() { + return handle_; + } + + protected: + ~CefV8Handle() override { + handle_.Reset(); + } + + persistentType handle_; + + DISALLOW_COPY_AND_ASSIGN(CefV8Handle); +}; + +// Specialization for v8::Value with empty implementation to avoid incorrect +// usage. +template <> +class CefV8Handle { +}; + + +class CefV8ContextImpl : public CefV8Context { + public: + CefV8ContextImpl(v8::Isolate* isolate, + v8::Handle context); + ~CefV8ContextImpl() override; + + CefRefPtr GetTaskRunner() override; + bool IsValid() override; + CefRefPtr GetBrowser() override; + CefRefPtr GetFrame() override; + CefRefPtr GetGlobal() override; + bool Enter() override; + bool Exit() override; + bool IsSame(CefRefPtr that) override; + bool Eval(const CefString& code, + CefRefPtr& retval, + CefRefPtr& exception) override; + + v8::Handle GetV8Context(); + blink::WebFrame* GetWebFrame(); + + protected: + typedef CefV8Handle Handle; + scoped_refptr handle_; + +#ifndef NDEBUG + // Used in debug builds to catch missing Exits in destructor. + int enter_count_; +#endif + + IMPLEMENT_REFCOUNTING(CefV8ContextImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8ContextImpl); +}; + +class CefV8ValueImpl : public CefV8Value { + public: + explicit CefV8ValueImpl(v8::Isolate* isolate); + CefV8ValueImpl(v8::Isolate* isolate, + v8::Handle value); + ~CefV8ValueImpl() override; + + // Used for initializing the CefV8ValueImpl. Should be called a single time + // after the CefV8ValueImpl is created. + void InitFromV8Value(v8::Handle value); + void InitUndefined(); + void InitNull(); + void InitBool(bool value); + void InitInt(int32 value); + void InitUInt(uint32 value); + void InitDouble(double value); + void InitDate(const CefTime& value); + void InitString(CefString& value); + void InitObject(v8::Handle value, CefTrackNode* tracker); + + // Creates a new V8 value for the underlying value or returns the existing + // object handle. + v8::Handle GetV8Value(bool should_persist); + + bool IsValid() override; + bool IsUndefined() override; + bool IsNull() override; + bool IsBool() override; + bool IsInt() override; + bool IsUInt() override; + bool IsDouble() override; + bool IsDate() override; + bool IsString() override; + bool IsObject() override; + bool IsArray() override; + bool IsFunction() override; + bool IsSame(CefRefPtr value) override; + bool GetBoolValue() override; + int32 GetIntValue() override; + uint32 GetUIntValue() override; + double GetDoubleValue() override; + CefTime GetDateValue() override; + CefString GetStringValue() override; + bool IsUserCreated() override; + bool HasException() override; + CefRefPtr GetException() override; + bool ClearException() override; + bool WillRethrowExceptions() override; + bool SetRethrowExceptions(bool rethrow) override; + bool HasValue(const CefString& key) override; + bool HasValue(int index) override; + bool DeleteValue(const CefString& key) override; + bool DeleteValue(int index) override; + CefRefPtr GetValue(const CefString& key) override; + CefRefPtr GetValue(int index) override; + bool SetValue(const CefString& key, CefRefPtr value, + PropertyAttribute attribute) override; + bool SetValue(int index, CefRefPtr value) override; + bool SetValue(const CefString& key, AccessControl settings, + PropertyAttribute attribute) override; + bool GetKeys(std::vector& keys) override; + bool SetUserData(CefRefPtr user_data) override; + CefRefPtr GetUserData() override; + int GetExternallyAllocatedMemory() override; + int AdjustExternallyAllocatedMemory(int change_in_bytes) override; + int GetArrayLength() override; + CefString GetFunctionName() override; + CefRefPtr GetFunctionHandler() override; + CefRefPtr ExecuteFunction( + CefRefPtr object, + const CefV8ValueList& arguments) override; + CefRefPtr ExecuteFunctionWithContext( + CefRefPtr context, + CefRefPtr object, + const CefV8ValueList& arguments) override; + + protected: + // Test for and record any exception. + bool HasCaught(v8::TryCatch& try_catch); + + class Handle : public CefV8HandleBase { + public: + typedef v8::Local handleType; + typedef v8::Persistent persistentType; + + Handle(v8::Isolate* isolate, + v8::Handle context, + handleType v, + CefTrackNode* tracker); + + handleType GetNewV8Handle(bool should_persist); + + persistentType& GetPersistentV8Handle(); + + void SetWeakIfNecessary(); + + protected: + ~Handle() override; + + private: + // Callback for weak persistent reference destruction. + static void Destructor(const v8::WeakCallbackData& data); + + persistentType handle_; + + // For Object and Function types, we need to hold on to a reference to their + // internal data or function handler objects that are reference counted. + CefTrackNode* tracker_; + + // True if the handle needs to persist due to it being passed into V8. + bool should_persist_; + + // True if the handle has been set as weak. + bool is_set_weak_; + + DISALLOW_COPY_AND_ASSIGN(Handle); + }; + + v8::Isolate* isolate_; + + enum { + TYPE_INVALID = 0, + TYPE_UNDEFINED, + TYPE_NULL, + TYPE_BOOL, + TYPE_INT, + TYPE_UINT, + TYPE_DOUBLE, + TYPE_DATE, + TYPE_STRING, + TYPE_OBJECT, + } type_; + + union { + bool bool_value_; + int32 int_value_; + uint32 uint_value_; + double double_value_; + cef_time_t date_value_; + cef_string_t string_value_; + }; + + // Used with Object, Function and Array types. + scoped_refptr handle_; + + CefRefPtr last_exception_; + bool rethrow_exceptions_; + + IMPLEMENT_REFCOUNTING(CefV8ValueImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8ValueImpl); +}; + +class CefV8StackTraceImpl : public CefV8StackTrace { + public: + CefV8StackTraceImpl(v8::Isolate* isolate, + v8::Handle handle); + ~CefV8StackTraceImpl() override; + + bool IsValid() override; + int GetFrameCount() override; + CefRefPtr GetFrame(int index) override; + + protected: + std::vector > frames_; + + IMPLEMENT_REFCOUNTING(CefV8StackTraceImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8StackTraceImpl); +}; + +class CefV8StackFrameImpl : public CefV8StackFrame { + public: + CefV8StackFrameImpl(v8::Isolate* isolate, + v8::Handle handle); + ~CefV8StackFrameImpl() override; + + bool IsValid() override; + CefString GetScriptName() override; + CefString GetScriptNameOrSourceURL() override; + CefString GetFunctionName() override; + int GetLineNumber() override; + int GetColumn() override; + bool IsEval() override; + bool IsConstructor() override; + + protected: + CefString script_name_; + CefString script_name_or_source_url_; + CefString function_name_; + int line_number_; + int column_; + bool is_eval_; + bool is_constructor_; + + IMPLEMENT_REFCOUNTING(CefV8StackFrameImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8StackFrameImpl); +}; + +#endif // CEF_LIBCEF_RENDERER_V8_IMPL_H_ diff --git a/libcef/renderer/webkit_glue.cc b/libcef/renderer/webkit_glue.cc new file mode 100644 index 000000000..e1cbbc676 --- /dev/null +++ b/libcef/renderer/webkit_glue.cc @@ -0,0 +1,124 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// MSVC++ requires this to be set before any other includes to get M_PI. +// Otherwise there will be compile errors in wtf/MathExtras.h. +#define _USE_MATH_DEFINES + +// Defines required to access Blink internals (unwrap WebNode). +#undef BLINK_IMPLEMENTATION +#define BLINK_IMPLEMENTATION 1 +#undef INSIDE_BLINK +#define INSIDE_BLINK 1 + +#include "libcef/renderer/webkit_glue.h" + +#include "base/compiler_specific.h" + +#include "config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "third_party/WebKit/public/platform/WebString.h" +#include "third_party/WebKit/public/web/WebDocument.h" +#include "third_party/WebKit/public/web/WebElement.h" +#include "third_party/WebKit/public/web/WebNode.h" +#include "third_party/WebKit/public/web/WebViewClient.h" + +#include "third_party/WebKit/Source/core/dom/Node.h" +#include "third_party/WebKit/Source/web/WebLocalFrameImpl.h" +#include "third_party/WebKit/Source/web/WebViewImpl.h" +MSVC_POP_WARNING(); +#undef LOG + +#include "base/logging.h" +#include "content/public/renderer/render_frame.h" + +namespace webkit_glue { + +const int64 kInvalidFrameId = -1; + +bool CanGoBack(blink::WebView* view) { + if (!view) + return false; + blink::WebViewImpl* impl = reinterpret_cast(view); + return (impl->client()->historyBackListCount() > 0); +} + +bool CanGoForward(blink::WebView* view) { + if (!view) + return false; + blink::WebViewImpl* impl = reinterpret_cast(view); + return (impl->client()->historyForwardListCount() > 0); +} + +void GoBack(blink::WebView* view) { + if (!view) + return; + blink::WebViewImpl* impl = reinterpret_cast(view); + if (impl->client()->historyBackListCount() > 0) + impl->client()->navigateBackForwardSoon(-1); +} + +void GoForward(blink::WebView* view) { + if (!view) + return; + blink::WebViewImpl* impl = reinterpret_cast(view); + if (impl->client()->historyForwardListCount() > 0) + impl->client()->navigateBackForwardSoon(1); +} + +std::string DumpDocumentText(blink::WebFrame* frame) { + // We use the document element's text instead of the body text here because + // not all documents have a body, such as XML documents. + blink::WebElement document_element = frame->document().documentElement(); + if (document_element.isNull()) + return std::string(); + + return document_element.innerText().utf8(); +} + +bool SetNodeValue(blink::WebNode& node, const blink::WebString& value) { + blink::Node* web_node = node.unwrap(); + web_node->setNodeValue(value); + return true; +} + +int64 GetIdentifier(blink::WebFrame* frame) { + // Each WebFrame will have an associated RenderFrame. The RenderFrame + // routing IDs are unique within a given renderer process. + content::RenderFrame* render_frame = + content::RenderFrame::FromWebFrame(frame); + DCHECK(render_frame); + if (render_frame) + return render_frame->GetRoutingID(); + return kInvalidFrameId; +} + +// Based on WebViewImpl::findFrameByName and FrameTree::find. +blink::WebFrame* FindFrameByUniqueName(const blink::WebString& unique_name, + blink::WebFrame* relative_to_frame) { + blink::Frame* start_frame = toWebLocalFrameImpl(relative_to_frame)->frame(); + if (!start_frame) + return NULL; + + const AtomicString& atomic_name = unique_name; + blink::Frame* found_frame = NULL; + + // Search the subtree starting with |start_frame|. + for (blink::Frame* frame = start_frame; + frame; + frame = frame->tree().traverseNext(start_frame)) { + if (frame->tree().uniqueName() == atomic_name) { + found_frame = frame; + break; + } + } + + if (found_frame && found_frame->isLocalFrame()) + return blink::WebLocalFrameImpl::fromFrame(toLocalFrame(found_frame)); + + return NULL; +} + +} // webkit_glue diff --git a/libcef/renderer/webkit_glue.h b/libcef/renderer/webkit_glue.h new file mode 100644 index 000000000..ae6be4e0a --- /dev/null +++ b/libcef/renderer/webkit_glue.h @@ -0,0 +1,48 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CEF_LIBCEF_RENDERER_WEBKIT_GLUE_H_ +#define CEF_LIBCEF_RENDERER_WEBKIT_GLUE_H_ + +#include +#include "base/basictypes.h" + +namespace v8 { +class Context; +template class Handle; +class Isolate; +} + +namespace blink { +class WebFrame; +class WebNode; +class WebString; +class WebView; +} + +namespace webkit_glue { + +extern const int64 kInvalidFrameId; + +bool CanGoBack(blink::WebView* view); +bool CanGoForward(blink::WebView* view); +void GoBack(blink::WebView* view); +void GoForward(blink::WebView* view); + +// Returns the text of the document element. +std::string DumpDocumentText(blink::WebFrame* frame); + +bool SetNodeValue(blink::WebNode& node, const blink::WebString& value); + +int64 GetIdentifier(blink::WebFrame* frame); + +// Find the frame with the specified |unique_name| relative to +// |relative_to_frame| in the frame hierarchy. +blink::WebFrame* FindFrameByUniqueName(const blink::WebString& unique_name, + blink::WebFrame* relative_to_frame); + +} // webkit_glue + +#endif // CEF_LIBCEF_RENDERER_WEBKIT_GLUE_H_ diff --git a/libcef/resources/about_version.html b/libcef/resources/about_version.html new file mode 100644 index 000000000..873957512 --- /dev/null +++ b/libcef/resources/about_version.html @@ -0,0 +1,123 @@ + + + + + + + About Version + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CEF$$CEF$$
Chromium$$CHROMIUM$$
OS$$OS$$
WebKit$$WEBKIT$$
JavaScript$$JAVASCRIPT$$
Flash$$FLASH$$
User Agent$$USERAGENT$$
Command Line$$COMMANDLINE$$
Module Path$$MODULEPATH$$
Cache Path$$CACHEPATH$$
+
+ + + + diff --git a/libcef/resources/cef_resources.grd b/libcef/resources/cef_resources.grd new file mode 100644 index 000000000..63dc921f6 --- /dev/null +++ b/libcef/resources/cef_resources.grd @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/libcef/resources/cef_strings.grd b/libcef/resources/cef_strings.grd new file mode 100644 index 000000000..e2924227c --- /dev/null +++ b/libcef/resources/cef_strings.grd @@ -0,0 +1,344 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + &Back + + + &Forward + + + Re&load + + + Reload no cache + + + &Stop + + + &Undo + + + &Redo + + + Cu&t + + + &Copy + + + &Paste + + + &Delete + + + Select &all + + + &Find... + + + &Print... + + + View s&ource + + + Audio Files + + + Image Files + + + Text Files + + + Video Files + + + + + Untitled Document + + + Print Failed + + + Something went wrong when trying to print. Please check your printer and try again. + + + The selected printer is not available or not installed correctly. Check your printer or try selecting another printer. + + + + + + en-US + + + &Add to dictionary + + + &No spelling suggestions + + + + diff --git a/libcef/resources/devtools_discovery_page.html b/libcef/resources/devtools_discovery_page.html new file mode 100644 index 000000000..87933d1af --- /dev/null +++ b/libcef/resources/devtools_discovery_page.html @@ -0,0 +1,54 @@ + + +CEF remote debugging + + + + + +
Inspectable WebContents
+
+ + diff --git a/libcef/resources/framework-Info.plist b/libcef/resources/framework-Info.plist new file mode 100644 index 000000000..21f1d2058 --- /dev/null +++ b/libcef/resources/framework-Info.plist @@ -0,0 +1,18 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + org.chromium.ContentShell.framework + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + FMWK + CFBundleSignature + ???? + + diff --git a/libcef/resources/grit_stub/chrome/grit/browser_resources.h b/libcef/resources/grit_stub/chrome/grit/browser_resources.h new file mode 100644 index 000000000..0d2c14a96 --- /dev/null +++ b/libcef/resources/grit_stub/chrome/grit/browser_resources.h @@ -0,0 +1,2 @@ +#include +#include diff --git a/libcef/resources/grit_stub/chrome/grit/generated_resources.h b/libcef/resources/grit_stub/chrome/grit/generated_resources.h new file mode 100644 index 000000000..0d2c14a96 --- /dev/null +++ b/libcef/resources/grit_stub/chrome/grit/generated_resources.h @@ -0,0 +1,2 @@ +#include +#include diff --git a/libcef/resources/grit_stub/chrome/grit/locale_settings.h b/libcef/resources/grit_stub/chrome/grit/locale_settings.h new file mode 100644 index 000000000..0d2c14a96 --- /dev/null +++ b/libcef/resources/grit_stub/chrome/grit/locale_settings.h @@ -0,0 +1,2 @@ +#include +#include diff --git a/libcef/resources/print_preview_page_stub.html b/libcef/resources/print_preview_page_stub.html new file mode 100644 index 000000000..18ecdcb79 --- /dev/null +++ b/libcef/resources/print_preview_page_stub.html @@ -0,0 +1 @@ + diff --git a/libcef/utility/content_utility_client.cc b/libcef/utility/content_utility_client.cc new file mode 100644 index 000000000..4d4d2f204 --- /dev/null +++ b/libcef/utility/content_utility_client.cc @@ -0,0 +1,60 @@ +// Copyright (c) 2014 the Chromium Embedded Framework authors. +// Portions Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/utility/content_utility_client.h" + +#include "chrome/common/chrome_utility_messages.h" +#include "chrome/utility/utility_message_handler.h" +#include "content/public/utility/utility_thread.h" + +#if defined(OS_WIN) +#include "libcef/utility/printing_handler.h" +#endif + +namespace { + +bool Send(IPC::Message* message) { + return content::UtilityThread::Get()->Send(message); +} + +} // namespace + +CefContentUtilityClient::CefContentUtilityClient() { +#if defined(OS_WIN) + handlers_.push_back(new PrintingHandler()); +#endif +} + +CefContentUtilityClient::~CefContentUtilityClient() { +} + +bool CefContentUtilityClient::OnMessageReceived( + const IPC::Message& message) { + bool handled = true; + + IPC_BEGIN_MESSAGE_MAP(CefContentUtilityClient, message) + IPC_MESSAGE_HANDLER(ChromeUtilityMsg_StartupPing, OnStartupPing) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + + for (Handlers::iterator it = handlers_.begin(); + !handled && it != handlers_.end(); ++it) { + handled = (*it)->OnMessageReceived(message); + } + + return handled; +} + +// static +void CefContentUtilityClient::PreSandboxStartup() { +#if defined(OS_WIN) + PrintingHandler::PreSandboxStartup(); +#endif +} + +void CefContentUtilityClient::OnStartupPing() { + Send(new ChromeUtilityHostMsg_ProcessStarted); + // Don't release the process, we assume further messages are on the way. +} diff --git a/libcef/utility/content_utility_client.h b/libcef/utility/content_utility_client.h new file mode 100644 index 000000000..2e067e806 --- /dev/null +++ b/libcef/utility/content_utility_client.h @@ -0,0 +1,33 @@ +// Copyright (c) 2014 the Chromium Embedded Framework authors. +// Portions Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef LIBCEF_UTILITY_CONTENT_UTILITY_CLIENT_H_ +#define LIBCEF_UTILITY_CONTENT_UTILITY_CLIENT_H_ + +#include "base/memory/scoped_vector.h" +#include "content/public/utility/content_utility_client.h" + +class UtilityMessageHandler; + +class CefContentUtilityClient : public content::ContentUtilityClient { + public: + CefContentUtilityClient(); + ~CefContentUtilityClient() override; + + bool OnMessageReceived(const IPC::Message& message) override; + + static void PreSandboxStartup(); + + private: + // IPC message handlers. + void OnStartupPing(); + + typedef ScopedVector Handlers; + Handlers handlers_; + + DISALLOW_COPY_AND_ASSIGN(CefContentUtilityClient); +}; + +#endif // LIBCEF_UTILITY_CONTENT_UTILITY_CLIENT_H_ diff --git a/libcef/utility/printing_handler.cc b/libcef/utility/printing_handler.cc new file mode 100644 index 000000000..82dc46a1d --- /dev/null +++ b/libcef/utility/printing_handler.cc @@ -0,0 +1,360 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "libcef/utility/printing_handler.h" + +#include "base/files/file_util.h" +#include "base/lazy_instance.h" +#include "base/path_service.h" +#include "base/scoped_native_library.h" +#include "chrome/common/chrome_paths.h" +#include "chrome/common/chrome_utility_printing_messages.h" +#include "content/public/utility/utility_thread.h" +#include "printing/page_range.h" +#include "printing/pdf_render_settings.h" + +#if defined(OS_WIN) +#include "base/win/iat_patch_function.h" +#include "printing/emf_win.h" +#include "ui/gfx/gdi_util.h" +#endif + +namespace { + +bool Send(IPC::Message* message) { + return content::UtilityThread::Get()->Send(message); +} + +void ReleaseProcessIfNeeded() { + content::UtilityThread::Get()->ReleaseProcessIfNeeded(); +} + +class PdfFunctionsBase { + public: + PdfFunctionsBase() : render_pdf_to_bitmap_func_(NULL), + get_pdf_doc_info_func_(NULL) {} + + bool Init() { + base::FilePath pdf_module_path; + if (!PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_module_path) || + !base::PathExists(pdf_module_path)) { + return false; + } + + pdf_lib_.Reset(base::LoadNativeLibrary(pdf_module_path, NULL)); + if (!pdf_lib_.is_valid()) { + LOG(WARNING) << "Couldn't load PDF plugin"; + return false; + } + + render_pdf_to_bitmap_func_ = + reinterpret_cast( + pdf_lib_.GetFunctionPointer("RenderPDFPageToBitmap")); + LOG_IF(WARNING, !render_pdf_to_bitmap_func_) << + "Missing RenderPDFPageToBitmap"; + + get_pdf_doc_info_func_ = + reinterpret_cast( + pdf_lib_.GetFunctionPointer("GetPDFDocInfo")); + LOG_IF(WARNING, !get_pdf_doc_info_func_) << "Missing GetPDFDocInfo"; + + if (!render_pdf_to_bitmap_func_ || !get_pdf_doc_info_func_ || + !PlatformInit(pdf_module_path, pdf_lib_)) { + Reset(); + } + + return IsValid(); + } + + bool IsValid() const { + return pdf_lib_.is_valid(); + } + + void Reset() { + pdf_lib_.Reset(NULL); + } + + bool RenderPDFPageToBitmap(const void* pdf_buffer, + int pdf_buffer_size, + int page_number, + void* bitmap_buffer, + int bitmap_width, + int bitmap_height, + int dpi_x, + int dpi_y, + bool autorotate) { + if (!render_pdf_to_bitmap_func_) + return false; + return render_pdf_to_bitmap_func_(pdf_buffer, pdf_buffer_size, page_number, + bitmap_buffer, bitmap_width, + bitmap_height, dpi_x, dpi_y, autorotate); + } + + bool GetPDFDocInfo(const void* pdf_buffer, + int buffer_size, + int* page_count, + double* max_page_width) { + if (!get_pdf_doc_info_func_) + return false; + return get_pdf_doc_info_func_(pdf_buffer, buffer_size, page_count, + max_page_width); + } + + protected: + virtual bool PlatformInit( + const base::FilePath& pdf_module_path, + const base::ScopedNativeLibrary& pdf_lib) { + return true; + } + + private: + // Exported by PDF plugin. + typedef bool (*RenderPDFPageToBitmapProc)(const void* pdf_buffer, + int pdf_buffer_size, + int page_number, + void* bitmap_buffer, + int bitmap_width, + int bitmap_height, + int dpi_x, + int dpi_y, + bool autorotate); + typedef bool (*GetPDFDocInfoProc)(const void* pdf_buffer, + int buffer_size, int* page_count, + double* max_page_width); + + RenderPDFPageToBitmapProc render_pdf_to_bitmap_func_; + GetPDFDocInfoProc get_pdf_doc_info_func_; + + base::ScopedNativeLibrary pdf_lib_; + DISALLOW_COPY_AND_ASSIGN(PdfFunctionsBase); +}; + +#if defined(OS_WIN) +// The 2 below IAT patch functions are almost identical to the code in +// render_process_impl.cc. This is needed to work around specific Windows APIs +// used by the Chrome PDF plugin that will fail in the sandbox. +static base::win::IATPatchFunction g_iat_patch_createdca; +HDC WINAPI UtilityProcess_CreateDCAPatch(LPCSTR driver_name, + LPCSTR device_name, + LPCSTR output, + const DEVMODEA* init_data) { + if (driver_name && (std::string("DISPLAY") == driver_name)) { + // CreateDC fails behind the sandbox, but not CreateCompatibleDC. + return CreateCompatibleDC(NULL); + } + + NOTREACHED(); + return CreateDCA(driver_name, device_name, output, init_data); +} + +static base::win::IATPatchFunction g_iat_patch_get_font_data; +DWORD WINAPI UtilityProcess_GetFontDataPatch( + HDC hdc, DWORD table, DWORD offset, LPVOID buffer, DWORD length) { + int rv = GetFontData(hdc, table, offset, buffer, length); + if (rv == GDI_ERROR && hdc) { + HFONT font = static_cast(GetCurrentObject(hdc, OBJ_FONT)); + + LOGFONT logfont; + if (GetObject(font, sizeof(LOGFONT), &logfont)) { + content::UtilityThread::Get()->PreCacheFont(logfont); + rv = GetFontData(hdc, table, offset, buffer, length); + content::UtilityThread::Get()->ReleaseCachedFonts(); + } + } + return rv; +} + +class PdfFunctionsWin : public PdfFunctionsBase { + public: + PdfFunctionsWin() : render_pdf_to_dc_func_(NULL) { + } + + bool PlatformInit( + const base::FilePath& pdf_module_path, + const base::ScopedNativeLibrary& pdf_lib) override { + // Patch the IAT for handling specific APIs known to fail in the sandbox. + if (!g_iat_patch_createdca.is_patched()) { + g_iat_patch_createdca.Patch(pdf_module_path.value().c_str(), + "gdi32.dll", "CreateDCA", + UtilityProcess_CreateDCAPatch); + } + + if (!g_iat_patch_get_font_data.is_patched()) { + g_iat_patch_get_font_data.Patch(pdf_module_path.value().c_str(), + "gdi32.dll", "GetFontData", + UtilityProcess_GetFontDataPatch); + } + render_pdf_to_dc_func_ = + reinterpret_cast( + pdf_lib.GetFunctionPointer("RenderPDFPageToDC")); + LOG_IF(WARNING, !render_pdf_to_dc_func_) << "Missing RenderPDFPageToDC"; + + return render_pdf_to_dc_func_ != NULL; + } + + bool RenderPDFPageToDC(const void* pdf_buffer, + int buffer_size, + int page_number, + HDC dc, + int dpi_x, + int dpi_y, + int bounds_origin_x, + int bounds_origin_y, + int bounds_width, + int bounds_height, + bool fit_to_bounds, + bool stretch_to_bounds, + bool keep_aspect_ratio, + bool center_in_bounds, + bool autorotate) { + if (!render_pdf_to_dc_func_) + return false; + return render_pdf_to_dc_func_(pdf_buffer, buffer_size, page_number, + dc, dpi_x, dpi_y, bounds_origin_x, + bounds_origin_y, bounds_width, bounds_height, + fit_to_bounds, stretch_to_bounds, + keep_aspect_ratio, center_in_bounds, + autorotate); + } + + private: + // Exported by PDF plugin. + typedef bool (*RenderPDFPageToDCProc)( + const void* pdf_buffer, int buffer_size, int page_number, HDC dc, + int dpi_x, int dpi_y, int bounds_origin_x, int bounds_origin_y, + int bounds_width, int bounds_height, bool fit_to_bounds, + bool stretch_to_bounds, bool keep_aspect_ratio, bool center_in_bounds, + bool autorotate); + RenderPDFPageToDCProc render_pdf_to_dc_func_; + + DISALLOW_COPY_AND_ASSIGN(PdfFunctionsWin); +}; + +typedef PdfFunctionsWin PdfFunctions; +#else // OS_WIN +typedef PdfFunctionsBase PdfFunctions; +#endif // OS_WIN + +base::LazyInstance g_pdf_lib = LAZY_INSTANCE_INITIALIZER; + +} // namespace + +PrintingHandler::PrintingHandler() {} + +PrintingHandler::~PrintingHandler() {} + +// static +void PrintingHandler::PreSandboxStartup() { + g_pdf_lib.Get().Init(); +} + +bool PrintingHandler::OnMessageReceived(const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(PrintingHandler, message) +#if defined(OS_WIN) + IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafiles, + OnRenderPDFPagesToMetafile) + IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafiles_GetPage, + OnRenderPDFPagesToMetafileGetPage) + IPC_MESSAGE_HANDLER(ChromeUtilityMsg_RenderPDFPagesToMetafiles_Stop, + OnRenderPDFPagesToMetafileStop) +#endif // OS_WIN + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +#if defined(OS_WIN) +void PrintingHandler::OnRenderPDFPagesToMetafile( + IPC::PlatformFileForTransit pdf_transit, + const printing::PdfRenderSettings& settings) { + pdf_rendering_settings_ = settings; + base::File pdf_file = IPC::PlatformFileForTransitToFile(pdf_transit); + int page_count = LoadPDF(pdf_file.Pass()); + Send( + new ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageCount(page_count)); +} + +void PrintingHandler::OnRenderPDFPagesToMetafileGetPage( + int page_number, + IPC::PlatformFileForTransit output_file) { + base::File emf_file = IPC::PlatformFileForTransitToFile(output_file); + double scale_factor = 1.0; + bool success = + RenderPdfPageToMetafile(page_number, emf_file.Pass(), &scale_factor); + Send(new ChromeUtilityHostMsg_RenderPDFPagesToMetafiles_PageDone( + success, scale_factor)); +} + +void PrintingHandler::OnRenderPDFPagesToMetafileStop() { + ReleaseProcessIfNeeded(); +} + +int PrintingHandler::LoadPDF(base::File pdf_file) { + if (!g_pdf_lib.Get().IsValid()) + return 0; + + int64 length = pdf_file.GetLength(); + if (length < 0) + return 0; + + pdf_data_.resize(length); + if (length != pdf_file.Read(0, pdf_data_.data(), pdf_data_.size())) + return 0; + + int total_page_count = 0; + if (!g_pdf_lib.Get().GetPDFDocInfo( + &pdf_data_.front(), pdf_data_.size(), &total_page_count, NULL)) { + return 0; + } + return total_page_count; +} + +bool PrintingHandler::RenderPdfPageToMetafile(int page_number, + base::File output_file, + double* scale_factor) { + printing::Emf metafile; + metafile.Init(); + + // We need to scale down DC to fit an entire page into DC available area. + // Current metafile is based on screen DC and have current screen size. + // Writing outside of those boundaries will result in the cut-off output. + // On metafiles (this is the case here), scaling down will still record + // original coordinates and we'll be able to print in full resolution. + // Before playback we'll need to counter the scaling up that will happen + // in the service (print_system_win.cc). + *scale_factor = + gfx::CalculatePageScale(metafile.context(), + pdf_rendering_settings_.area().right(), + pdf_rendering_settings_.area().bottom()); + gfx::ScaleDC(metafile.context(), *scale_factor); + + // The underlying metafile is of type Emf and ignores the arguments passed + // to StartPage. + metafile.StartPage(gfx::Size(), gfx::Rect(), 1); + if (!g_pdf_lib.Get().RenderPDFPageToDC( + &pdf_data_.front(), + pdf_data_.size(), + page_number, + metafile.context(), + pdf_rendering_settings_.dpi(), + pdf_rendering_settings_.dpi(), + pdf_rendering_settings_.area().x(), + pdf_rendering_settings_.area().y(), + pdf_rendering_settings_.area().width(), + pdf_rendering_settings_.area().height(), + true, + false, + true, + true, + pdf_rendering_settings_.autorotate())) { + return false; + } + metafile.FinishPage(); + metafile.FinishDocument(); + return metafile.SaveTo(&output_file); +} + +#endif // OS_WIN + diff --git a/libcef/utility/printing_handler.h b/libcef/utility/printing_handler.h new file mode 100644 index 000000000..41503fa5a --- /dev/null +++ b/libcef/utility/printing_handler.h @@ -0,0 +1,57 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef LIBCEF_UTILITY_PRINTING_HANDLER_H_ +#define LIBCEF_UTILITY_PRINTING_HANDLER_H_ + +#include "base/compiler_specific.h" +#include "base/macros.h" +#include "chrome/utility/utility_message_handler.h" +#include "ipc/ipc_platform_file.h" +#include "printing/pdf_render_settings.h" + +#if !defined(OS_WIN) +#error "Must be building on Windows." +#endif + +namespace printing { +class PdfRenderSettings; +struct PwgRasterSettings; +struct PageRange; +} + +// Dispatches IPCs for printing. +class PrintingHandler : public UtilityMessageHandler { + public: + PrintingHandler(); + ~PrintingHandler() override; + + static void PreSandboxStartup(); + + // IPC::Listener: + bool OnMessageReceived(const IPC::Message& message) override; + + private: + // IPC message handlers. +#if defined(OS_WIN) + void OnRenderPDFPagesToMetafile(IPC::PlatformFileForTransit pdf_transit, + const printing::PdfRenderSettings& settings); + void OnRenderPDFPagesToMetafileGetPage( + int page_number, + IPC::PlatformFileForTransit output_file); + void OnRenderPDFPagesToMetafileStop(); + + int LoadPDF(base::File pdf_file); + bool RenderPdfPageToMetafile(int page_number, + base::File output_file, + double* scale_factor); + + std::vector pdf_data_; + printing::PdfRenderSettings pdf_rendering_settings_; +#endif // defined(OS_WIN) + + DISALLOW_COPY_AND_ASSIGN(PrintingHandler); +}; + +#endif // LIBCEF_UTILITY_PRINTING_HANDLER_H_ diff --git a/libcef_dll/CMakeLists.txt.in b/libcef_dll/CMakeLists.txt.in new file mode 100644 index 000000000..d50ed8de1 --- /dev/null +++ b/libcef_dll/CMakeLists.txt.in @@ -0,0 +1,39 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +add_definitions(-DUSING_CEF_SHARED) + +# Append platform specific sources to a list of sources. +macro(LIBCEF_APPEND_PLATFORM_SOURCES name_of_list) + if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin" AND ${name_of_list}_MACOSX) + list(APPEND ${name_of_list} ${${name_of_list}_MACOSX}) + endif() + if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux" AND ${name_of_list}_LINUX) + list(APPEND ${name_of_list} ${${name_of_list}_LINUX}) + endif() + if("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows" AND ${name_of_list}_WINDOWS) + list(APPEND ${name_of_list} ${${name_of_list}_WINDOWS}) + endif() +endmacro() + +{{ + 'prefix': 'libcef', + 'library': 'libcef_dll_wrapper', + 'append_macro': 'LIBCEF_APPEND_PLATFORM_SOURCES', + 'includes': [ + 'includes_common', + 'autogen_cpp_includes', + 'includes_capi', + 'autogen_capi_includes', + 'includes_wrapper', + 'includes_win:WINDOWS', + 'includes_mac:MACOSX', + 'includes_linux:LINUX', + 'libcef_dll_wrapper_sources_common', + 'autogen_client_side', + ], +}} + +# Remove the default "lib" prefix from the resulting library. +set_target_properties(libcef_dll_wrapper PROPERTIES PREFIX "") diff --git a/libcef_dll/base/cef_atomicops_x86_gcc.cc b/libcef_dll/base/cef_atomicops_x86_gcc.cc new file mode 100644 index 000000000..4471eedaf --- /dev/null +++ b/libcef_dll/base/cef_atomicops_x86_gcc.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This module gets enough CPU information to optimize the +// atomicops module on x86. + +#include +#include + +#include "include/base/cef_atomicops.h" + +// This file only makes sense with atomicops_internals_x86_gcc.h -- it +// depends on structs that are defined in that file. If atomicops.h +// doesn't sub-include that file, then we aren't needed, and shouldn't +// try to do anything. +#ifdef CEF_INCLUDE_BASE_INTERNAL_CEF_ATOMICOPS_X86_GCC_H_ + +// Inline cpuid instruction. In PIC compilations, %ebx contains the address +// of the global offset table. To avoid breaking such executables, this code +// must preserve that register's value across cpuid instructions. +#if defined(__i386__) +#define cpuid(a, b, c, d, inp) \ + asm("mov %%ebx, %%edi\n" \ + "cpuid\n" \ + "xchg %%edi, %%ebx\n" \ + : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) +#elif defined(__x86_64__) +#define cpuid(a, b, c, d, inp) \ + asm("mov %%rbx, %%rdi\n" \ + "cpuid\n" \ + "xchg %%rdi, %%rbx\n" \ + : "=a" (a), "=D" (b), "=c" (c), "=d" (d) : "a" (inp)) +#endif + +#if defined(cpuid) // initialize the struct only on x86 + +// Set the flags so that code will run correctly and conservatively, so even +// if we haven't been initialized yet, we're probably single threaded, and our +// default values should hopefully be pretty safe. +struct AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures = { + false, // bug can't exist before process spawns multiple threads +}; + +namespace { + +// Initialize the AtomicOps_Internalx86CPUFeatures struct. +void AtomicOps_Internalx86CPUFeaturesInit() { + uint32_t eax; + uint32_t ebx; + uint32_t ecx; + uint32_t edx; + + // Get vendor string (issue CPUID with eax = 0) + cpuid(eax, ebx, ecx, edx, 0); + char vendor[13]; + memcpy(vendor, &ebx, 4); + memcpy(vendor + 4, &edx, 4); + memcpy(vendor + 8, &ecx, 4); + vendor[12] = 0; + + // get feature flags in ecx/edx, and family/model in eax + cpuid(eax, ebx, ecx, edx, 1); + + int family = (eax >> 8) & 0xf; // family and model fields + int model = (eax >> 4) & 0xf; + if (family == 0xf) { // use extended family and model fields + family += (eax >> 20) & 0xff; + model += ((eax >> 16) & 0xf) << 4; + } + + // Opteron Rev E has a bug in which on very rare occasions a locked + // instruction doesn't act as a read-acquire barrier if followed by a + // non-locked read-modify-write instruction. Rev F has this bug in + // pre-release versions, but not in versions released to customers, + // so we test only for Rev E, which is family 15, model 32..63 inclusive. + if (strcmp(vendor, "AuthenticAMD") == 0 && // AMD + family == 15 && + 32 <= model && model <= 63) { + AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = true; + } else { + AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug = false; + } +} + +class AtomicOpsx86Initializer { + public: + AtomicOpsx86Initializer() { + AtomicOps_Internalx86CPUFeaturesInit(); + } +}; + +// A global to get use initialized on startup via static initialization :/ +AtomicOpsx86Initializer g_initer; + +} // namespace + +#endif // if x86 + +#endif // ifdef CEF_INCLUDE_BASE_CEF_ATOMICOPS_INTERNALS_X86_GCC_H_ diff --git a/libcef_dll/base/cef_bind_helpers.cc b/libcef_dll/base/cef_bind_helpers.cc new file mode 100644 index 000000000..b65f5f31f --- /dev/null +++ b/libcef_dll/base/cef_bind_helpers.cc @@ -0,0 +1,14 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_bind_helpers.h" + +#include "include/base/cef_callback.h" + +namespace base { + +void DoNothing() { +} + +} // namespace base diff --git a/libcef_dll/base/cef_callback_helpers.cc b/libcef_dll/base/cef_callback_helpers.cc new file mode 100644 index 000000000..726104c7b --- /dev/null +++ b/libcef_dll/base/cef_callback_helpers.cc @@ -0,0 +1,42 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_callback_helpers.h" + +#include "include/base/cef_callback.h" + +namespace base { + +ScopedClosureRunner::ScopedClosureRunner() { +} + +ScopedClosureRunner::ScopedClosureRunner(const Closure& closure) + : closure_(closure) { +} + +ScopedClosureRunner::~ScopedClosureRunner() { + if (!closure_.is_null()) + closure_.Run(); +} + +void ScopedClosureRunner::Reset() { + Closure old_closure = Release(); + if (!old_closure.is_null()) + old_closure.Run(); +} + +void ScopedClosureRunner::Reset(const Closure& closure) { + Closure old_closure = Release(); + closure_ = closure; + if (!old_closure.is_null()) + old_closure.Run(); +} + +Closure ScopedClosureRunner::Release() { + Closure result = closure_; + closure_.Reset(); + return result; +} + +} // namespace base diff --git a/libcef_dll/base/cef_callback_internal.cc b/libcef_dll/base/cef_callback_internal.cc new file mode 100644 index 000000000..c521bc222 --- /dev/null +++ b/libcef_dll/base/cef_callback_internal.cc @@ -0,0 +1,34 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/internal/cef_callback_internal.h" + +#include "include/base/cef_logging.h" + +namespace base { +namespace cef_internal { + +void CallbackBase::Reset() { + polymorphic_invoke_ = NULL; + // NULL the bind_state_ last, since it may be holding the last ref to whatever + // object owns us, and we may be deleted after that. + bind_state_ = NULL; +} + +bool CallbackBase::Equals(const CallbackBase& other) const { + return bind_state_.get() == other.bind_state_.get() && + polymorphic_invoke_ == other.polymorphic_invoke_; +} + +CallbackBase::CallbackBase(BindStateBase* bind_state) + : bind_state_(bind_state), + polymorphic_invoke_(NULL) { + DCHECK(!bind_state_.get() || bind_state_->HasOneRef()); +} + +CallbackBase::~CallbackBase() { +} + +} // namespace cef_internal +} // namespace base diff --git a/libcef_dll/base/cef_lock.cc b/libcef_dll/base/cef_lock.cc new file mode 100644 index 000000000..f0a2cd44a --- /dev/null +++ b/libcef_dll/base/cef_lock.cc @@ -0,0 +1,44 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file is used for debugging assertion support. The Lock class +// is functionally a wrapper around the LockImpl class, so the only +// real intelligence in the class is in the debugging logic. + +#if !defined(NDEBUG) + +#include "include/base/cef_lock.h" +#include "include/base/cef_logging.h" + +namespace base { + +Lock::Lock() : lock_() { +} + +Lock::~Lock() { + DCHECK(owning_thread_ref_.is_null()); +} + +void Lock::AssertAcquired() const { + DCHECK(owning_thread_ref_ == PlatformThread::CurrentRef()); +} + +void Lock::CheckHeldAndUnmark() { + DCHECK(owning_thread_ref_ == PlatformThread::CurrentRef()); + owning_thread_ref_ = PlatformThreadRef(); +} + +void Lock::CheckUnheldAndMark() { + // Hitting this DCHECK means that your code is trying to re-enter a lock that + // is already held. The Chromium Lock implementation is not reentrant. + // See "Why can the holder of a Lock not reacquire it?" at + // http://www.chromium.org/developers/lock-and-condition-variable for more + // information. + DCHECK(owning_thread_ref_.is_null()); + owning_thread_ref_ = PlatformThread::CurrentRef(); +} + +} // namespace base + +#endif // NDEBUG diff --git a/libcef_dll/base/cef_lock_impl.cc b/libcef_dll/base/cef_lock_impl.cc new file mode 100644 index 000000000..fa772e1f7 --- /dev/null +++ b/libcef_dll/base/cef_lock_impl.cc @@ -0,0 +1,92 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/internal/cef_lock_impl.h" + +#if defined(OS_WIN) + +namespace base { +namespace cef_internal { + +LockImpl::LockImpl() { + // The second parameter is the spin count, for short-held locks it avoid the + // contending thread from going to sleep which helps performance greatly. + ::InitializeCriticalSectionAndSpinCount(&native_handle_, 2000); +} + +LockImpl::~LockImpl() { + ::DeleteCriticalSection(&native_handle_); +} + +bool LockImpl::Try() { + if (::TryEnterCriticalSection(&native_handle_) != FALSE) { + return true; + } + return false; +} + +void LockImpl::Lock() { + ::EnterCriticalSection(&native_handle_); +} + +void LockImpl::Unlock() { + ::LeaveCriticalSection(&native_handle_); +} + +} // namespace cef_internal +} // namespace base + +#elif defined(OS_POSIX) + +#include +#include + +#include "include/base/cef_logging.h" + +namespace base { +namespace cef_internal { + +LockImpl::LockImpl() { +#ifndef NDEBUG + // In debug, setup attributes for lock error checking. + pthread_mutexattr_t mta; + int rv = pthread_mutexattr_init(&mta); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); + rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); + rv = pthread_mutex_init(&native_handle_, &mta); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); + rv = pthread_mutexattr_destroy(&mta); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); +#else + // In release, go with the default lock attributes. + pthread_mutex_init(&native_handle_, NULL); +#endif +} + +LockImpl::~LockImpl() { + int rv = pthread_mutex_destroy(&native_handle_); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); +} + +bool LockImpl::Try() { + int rv = pthread_mutex_trylock(&native_handle_); + DCHECK(rv == 0 || rv == EBUSY) << ". " << strerror(rv); + return rv == 0; +} + +void LockImpl::Lock() { + int rv = pthread_mutex_lock(&native_handle_); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); +} + +void LockImpl::Unlock() { + int rv = pthread_mutex_unlock(&native_handle_); + DCHECK_EQ(rv, 0) << ". " << strerror(rv); +} + +} // namespace cef_internal +} // namespace base + +#endif // defined(OS_POSIX) diff --git a/libcef_dll/base/cef_logging.cc b/libcef_dll/base/cef_logging.cc new file mode 100644 index 000000000..a828b8fad --- /dev/null +++ b/libcef_dll/base/cef_logging.cc @@ -0,0 +1,259 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_logging.h" + +#if defined(OS_WIN) +#include +#include +#include +#elif defined(OS_POSIX) +#include +#include +#include +#endif + +#include "include/internal/cef_string_types.h" + +namespace cef { +namespace logging { + +namespace { + +#if defined(OS_POSIX) +// From base/safe_strerror_posix.cc. + +#define USE_HISTORICAL_STRERRO_R (defined(__GLIBC__) || defined(OS_NACL)) + +#if USE_HISTORICAL_STRERRO_R && defined(__GNUC__) +// GCC will complain about the unused second wrap function unless we tell it +// that we meant for them to be potentially unused, which is exactly what this +// attribute is for. +#define POSSIBLY_UNUSED __attribute__((unused)) +#else +#define POSSIBLY_UNUSED +#endif + +#if USE_HISTORICAL_STRERRO_R +// glibc has two strerror_r functions: a historical GNU-specific one that +// returns type char *, and a POSIX.1-2001 compliant one available since 2.3.4 +// that returns int. This wraps the GNU-specific one. +static void POSSIBLY_UNUSED wrap_posix_strerror_r( + char *(*strerror_r_ptr)(int, char *, size_t), + int err, + char *buf, + size_t len) { + // GNU version. + char *rc = (*strerror_r_ptr)(err, buf, len); + if (rc != buf) { + // glibc did not use buf and returned a static string instead. Copy it + // into buf. + buf[0] = '\0'; + strncat(buf, rc, len - 1); + } + // The GNU version never fails. Unknown errors get an "unknown error" message. + // The result is always null terminated. +} +#endif // USE_HISTORICAL_STRERRO_R + +// Wrapper for strerror_r functions that implement the POSIX interface. POSIX +// does not define the behaviour for some of the edge cases, so we wrap it to +// guarantee that they are handled. This is compiled on all POSIX platforms, but +// it will only be used on Linux if the POSIX strerror_r implementation is +// being used (see below). +static void POSSIBLY_UNUSED wrap_posix_strerror_r( + int (*strerror_r_ptr)(int, char *, size_t), + int err, + char *buf, + size_t len) { + int old_errno = errno; + // Have to cast since otherwise we get an error if this is the GNU version + // (but in such a scenario this function is never called). Sadly we can't use + // C++-style casts because the appropriate one is reinterpret_cast but it's + // considered illegal to reinterpret_cast a type to itself, so we get an + // error in the opposite case. + int result = (*strerror_r_ptr)(err, buf, len); + if (result == 0) { + // POSIX is vague about whether the string will be terminated, although + // it indirectly implies that typically ERANGE will be returned, instead + // of truncating the string. We play it safe by always terminating the + // string explicitly. + buf[len - 1] = '\0'; + } else { + // Error. POSIX is vague about whether the return value is itself a system + // error code or something else. On Linux currently it is -1 and errno is + // set. On BSD-derived systems it is a system error and errno is unchanged. + // We try and detect which case it is so as to put as much useful info as + // we can into our message. + int strerror_error; // The error encountered in strerror + int new_errno = errno; + if (new_errno != old_errno) { + // errno was changed, so probably the return value is just -1 or something + // else that doesn't provide any info, and errno is the error. + strerror_error = new_errno; + } else { + // Either the error from strerror_r was the same as the previous value, or + // errno wasn't used. Assume the latter. + strerror_error = result; + } + // snprintf truncates and always null-terminates. + snprintf(buf, + len, + "Error %d while retrieving error %d", + strerror_error, + err); + } + errno = old_errno; +} + +void safe_strerror_r(int err, char *buf, size_t len) { + if (buf == NULL || len <= 0) { + return; + } + // If using glibc (i.e., Linux), the compiler will automatically select the + // appropriate overloaded function based on the function type of strerror_r. + // The other one will be elided from the translation unit since both are + // static. + wrap_posix_strerror_r(&strerror_r, err, buf, len); +} + +std::string safe_strerror(int err) { + const int buffer_size = 256; + char buf[buffer_size]; + safe_strerror_r(err, buf, sizeof(buf)); + return std::string(buf); +} +#endif // defined(OS_POSIX) + +} // namespace + +// MSVC doesn't like complex extern templates and DLLs. +#if !defined(COMPILER_MSVC) +// Explicit instantiations for commonly used comparisons. +template std::string* MakeCheckOpString( + const int&, const int&, const char* names); +template std::string* MakeCheckOpString( + const unsigned long&, const unsigned long&, const char* names); +template std::string* MakeCheckOpString( + const unsigned long&, const unsigned int&, const char* names); +template std::string* MakeCheckOpString( + const unsigned int&, const unsigned long&, const char* names); +template std::string* MakeCheckOpString( + const std::string&, const std::string&, const char* name); +#endif + +#if defined(OS_WIN) +LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) { +} + +LogMessage::SaveLastError::~SaveLastError() { + ::SetLastError(last_error_); +} +#endif // defined(OS_WIN) + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity) + : severity_(severity), file_(file), line_(line) { +} + +LogMessage::LogMessage(const char* file, int line, std::string* result) + : severity_(LOG_FATAL), file_(file), line_(line) { + stream_ << "Check failed: " << *result; + delete result; +} + +LogMessage::LogMessage(const char* file, int line, LogSeverity severity, + std::string* result) + : severity_(severity), file_(file), line_(line) { + stream_ << "Check failed: " << *result; + delete result; +} + +LogMessage::~LogMessage() { + stream_ << std::endl; + std::string str_newline(stream_.str()); + cef_log(file_, line_, severity_, str_newline.c_str()); +} + +#if defined(OS_WIN) +// This has already been defined in the header, but defining it again as DWORD +// ensures that the type used in the header is equivalent to DWORD. If not, +// the redefinition is a compile error. +typedef DWORD SystemErrorCode; +#endif + +SystemErrorCode GetLastSystemErrorCode() { +#if defined(OS_WIN) + return ::GetLastError(); +#elif defined(OS_POSIX) + return errno; +#else +#error Not implemented +#endif +} + +#if defined(OS_WIN) +std::string SystemErrorCodeToString(SystemErrorCode error_code) { + const int error_message_buffer_size = 256; + char msgbuf[error_message_buffer_size]; + DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; + DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf, + arraysize(msgbuf), NULL); + std::stringstream ss; + if (len) { + std::string s(msgbuf); + // Messages returned by system end with line breaks. + s.erase(std::remove_if(s.begin(), s.end(), ::isspace), s.end()); + ss << s << " (0x" << std::hex << error_code << ")"; + } else { + ss << "Error (0x" << std::hex << GetLastError() << + ") while retrieving error. (0x" << error_code << ")"; + } + return ss.str(); +} +#elif defined(OS_POSIX) +std::string SystemErrorCodeToString(SystemErrorCode error_code) { + return safe_strerror(error_code); +} +#else +#error Not implemented +#endif + +#if defined(OS_WIN) +Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, + int line, + LogSeverity severity, + SystemErrorCode err) + : err_(err), + log_message_(file, line, severity) { +} + +Win32ErrorLogMessage::~Win32ErrorLogMessage() { + stream() << ": " << SystemErrorCodeToString(err_); +} +#elif defined(OS_POSIX) +ErrnoLogMessage::ErrnoLogMessage(const char* file, + int line, + LogSeverity severity, + SystemErrorCode err) + : err_(err), + log_message_(file, line, severity) { +} + +ErrnoLogMessage::~ErrnoLogMessage() { + stream() << ": " << SystemErrorCodeToString(err_); +} +#endif // OS_WIN + +std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) { + cef_string_utf8_t str = {0}; + std::wstring tmp_str(wstr); + cef_string_wide_to_utf8(wstr, tmp_str.size(), &str); + out << str.str; + cef_string_utf8_clear(&str); + return out; +} + +} // namespace logging +} // namespace cef diff --git a/libcef_dll/base/cef_ref_counted.cc b/libcef_dll/base/cef_ref_counted.cc new file mode 100644 index 000000000..76b44b5b3 --- /dev/null +++ b/libcef_dll/base/cef_ref_counted.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_ref_counted.h" +#include "include/base/cef_thread_collision_warner.h" + +namespace base { + +namespace subtle { + +bool RefCountedThreadSafeBase::HasOneRef() const { + return AtomicRefCountIsOne( + &const_cast(this)->ref_count_); +} + +RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(0) { +#ifndef NDEBUG + in_dtor_ = false; +#endif +} + +RefCountedThreadSafeBase::~RefCountedThreadSafeBase() { +#ifndef NDEBUG + DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without " + "calling Release()"; +#endif +} + +void RefCountedThreadSafeBase::AddRef() const { +#ifndef NDEBUG + DCHECK(!in_dtor_); +#endif + AtomicRefCountInc(&ref_count_); +} + +bool RefCountedThreadSafeBase::Release() const { +#ifndef NDEBUG + DCHECK(!in_dtor_); + DCHECK(!AtomicRefCountIsZero(&ref_count_)); +#endif + if (!AtomicRefCountDec(&ref_count_)) { +#ifndef NDEBUG + in_dtor_ = true; +#endif + return true; + } + return false; +} + +} // namespace subtle + +} // namespace base diff --git a/libcef_dll/base/cef_string16.cc b/libcef_dll/base/cef_string16.cc new file mode 100644 index 000000000..2e5f0b820 --- /dev/null +++ b/libcef_dll/base/cef_string16.cc @@ -0,0 +1,89 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_string16.h" + +#if defined(OS_POSIX) +#if defined(WCHAR_T_IS_UTF16) + +#error This file should not be used on 2-byte wchar_t systems +// If this winds up being needed on 2-byte wchar_t systems, either the +// definitions below can be used, or the host system's wide character +// functions like wmemcmp can be wrapped. + +#elif defined(WCHAR_T_IS_UTF32) + +#include +#include + +#include "include/internal/cef_string_types.h" + +namespace base { + +int c16memcmp(const char16* s1, const char16* s2, size_t n) { + // We cannot call memcmp because that changes the semantics. + while (n-- > 0) { + if (*s1 != *s2) { + // We cannot use (*s1 - *s2) because char16 is unsigned. + return ((*s1 < *s2) ? -1 : 1); + } + ++s1; + ++s2; + } + return 0; +} + +size_t c16len(const char16* s) { + const char16 *s_orig = s; + while (*s) { + ++s; + } + return s - s_orig; +} + +const char16* c16memchr(const char16* s, char16 c, size_t n) { + while (n-- > 0) { + if (*s == c) { + return s; + } + ++s; + } + return 0; +} + +char16* c16memmove(char16* s1, const char16* s2, size_t n) { + return static_cast(memmove(s1, s2, n * sizeof(char16))); +} + +char16* c16memcpy(char16* s1, const char16* s2, size_t n) { + return static_cast(memcpy(s1, s2, n * sizeof(char16))); +} + +char16* c16memset(char16* s, char16 c, size_t n) { + char16 *s_orig = s; + while (n-- > 0) { + *s = c; + ++s; + } + return s_orig; +} + +std::ostream& operator<<(std::ostream& out, const string16& str) { + cef_string_utf8_t cef_str = {0}; + cef_string_utf16_to_utf8(str.c_str(), str.size(), &cef_str); + out << cef_str.str; + cef_string_utf8_clear(&cef_str); + return out; +} + +void PrintTo(const string16& str, std::ostream* out) { + *out << str; +} + +} // namespace base + +template class std::basic_string; + +#endif // WCHAR_T_IS_UTF32 +#endif // OS_POSIX diff --git a/libcef_dll/base/cef_thread_checker_impl.cc b/libcef_dll/base/cef_thread_checker_impl.cc new file mode 100644 index 000000000..d3193a28d --- /dev/null +++ b/libcef_dll/base/cef_thread_checker_impl.cc @@ -0,0 +1,34 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/internal/cef_thread_checker_impl.h" + +namespace base { + +ThreadCheckerImpl::ThreadCheckerImpl() + : valid_thread_id_() { + EnsureThreadIdAssigned(); +} + +ThreadCheckerImpl::~ThreadCheckerImpl() {} + +bool ThreadCheckerImpl::CalledOnValidThread() const { + EnsureThreadIdAssigned(); + AutoLock auto_lock(lock_); + return valid_thread_id_ == PlatformThread::CurrentRef(); +} + +void ThreadCheckerImpl::DetachFromThread() { + AutoLock auto_lock(lock_); + valid_thread_id_ = PlatformThreadRef(); +} + +void ThreadCheckerImpl::EnsureThreadIdAssigned() const { + AutoLock auto_lock(lock_); + if (valid_thread_id_.is_null()) { + valid_thread_id_ = PlatformThread::CurrentRef(); + } +} + +} // namespace base diff --git a/libcef_dll/base/cef_thread_collision_warner.cc b/libcef_dll/base/cef_thread_collision_warner.cc new file mode 100644 index 000000000..794ab64a4 --- /dev/null +++ b/libcef_dll/base/cef_thread_collision_warner.cc @@ -0,0 +1,65 @@ +// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_thread_collision_warner.h" + +#include "include/base/cef_logging.h" +#include "include/internal/cef_thread_internal.h" + +namespace base { + +void DCheckAsserter::warn() { + NOTREACHED() << "Thread Collision"; +} + +static subtle::Atomic32 CurrentThread() { + const cef_platform_thread_id_t current_thread_id = + cef_get_current_platform_thread_id(); + // We need to get the thread id into an atomic data type. This might be a + // truncating conversion, but any loss-of-information just increases the + // chance of a fault negative, not a false positive. + const subtle::Atomic32 atomic_thread_id = + static_cast(current_thread_id); + + return atomic_thread_id; +} + +void ThreadCollisionWarner::EnterSelf() { + // If the active thread is 0 then I'll write the current thread ID + // if two or more threads arrive here only one will succeed to + // write on valid_thread_id_ the current thread ID. + subtle::Atomic32 current_thread_id = CurrentThread(); + + int previous_value = subtle::NoBarrier_CompareAndSwap(&valid_thread_id_, + 0, + current_thread_id); + if (previous_value != 0 && previous_value != current_thread_id) { + // gotcha! a thread is trying to use the same class and that is + // not current thread. + asserter_->warn(); + } + + subtle::NoBarrier_AtomicIncrement(&counter_, 1); +} + +void ThreadCollisionWarner::Enter() { + subtle::Atomic32 current_thread_id = CurrentThread(); + + if (subtle::NoBarrier_CompareAndSwap(&valid_thread_id_, + 0, + current_thread_id) != 0) { + // gotcha! another thread is trying to use the same class. + asserter_->warn(); + } + + subtle::NoBarrier_AtomicIncrement(&counter_, 1); +} + +void ThreadCollisionWarner::Leave() { + if (subtle::Barrier_AtomicIncrement(&counter_, -1) == 0) { + subtle::NoBarrier_Store(&valid_thread_id_, 0); + } +} + +} // namespace base diff --git a/libcef_dll/base/cef_weak_ptr.cc b/libcef_dll/base/cef_weak_ptr.cc new file mode 100644 index 000000000..3c83a490e --- /dev/null +++ b/libcef_dll/base/cef_weak_ptr.cc @@ -0,0 +1,77 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "include/base/cef_weak_ptr.h" + +namespace base { +namespace cef_internal { + +WeakReference::Flag::Flag() : is_valid_(true) { + // Flags only become bound when checked for validity, or invalidated, + // so that we can check that later validity/invalidation operations on + // the same Flag take place on the same thread. + thread_checker_.DetachFromThread(); +} + +void WeakReference::Flag::Invalidate() { + // The flag being invalidated with a single ref implies that there are no + // weak pointers in existence. Allow deletion on other thread in this case. + DCHECK(thread_checker_.CalledOnValidThread() || HasOneRef()) + << "WeakPtrs must be invalidated on the same thread."; + is_valid_ = false; +} + +bool WeakReference::Flag::IsValid() const { + DCHECK(thread_checker_.CalledOnValidThread()) + << "WeakPtrs must be checked on the same thread."; + return is_valid_; +} + +WeakReference::Flag::~Flag() { +} + +WeakReference::WeakReference() { +} + +WeakReference::WeakReference(const Flag* flag) : flag_(flag) { +} + +WeakReference::~WeakReference() { +} + +bool WeakReference::is_valid() const { return flag_.get() && flag_->IsValid(); } + +WeakReferenceOwner::WeakReferenceOwner() { +} + +WeakReferenceOwner::~WeakReferenceOwner() { + Invalidate(); +} + +WeakReference WeakReferenceOwner::GetRef() const { + // If we hold the last reference to the Flag then create a new one. + if (!HasRefs()) + flag_ = new WeakReference::Flag(); + + return WeakReference(flag_.get()); +} + +void WeakReferenceOwner::Invalidate() { + if (flag_.get()) { + flag_->Invalidate(); + flag_ = NULL; + } +} + +WeakPtrBase::WeakPtrBase() { +} + +WeakPtrBase::~WeakPtrBase() { +} + +WeakPtrBase::WeakPtrBase(const WeakReference& ref) : ref_(ref) { +} + +} // namespace cef_internal +} // namespace base diff --git a/libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.cc b/libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.cc new file mode 100644 index 000000000..a7899c0c3 --- /dev/null +++ b/libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.cc @@ -0,0 +1,47 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK allow_certificate_error_callback_cont( + struct _cef_allow_certificate_error_callback_t* self, int allow) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefAllowCertificateErrorCallbackCppToC::Get(self)->Continue( + allow?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefAllowCertificateErrorCallbackCppToC::CefAllowCertificateErrorCallbackCppToC( + CefAllowCertificateErrorCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = allow_certificate_error_callback_cont; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.h b/libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.h new file mode 100644 index 000000000..afb21832a --- /dev/null +++ b/libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.h @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_ALLOW_CERTIFICATE_ERROR_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_ALLOW_CERTIFICATE_ERROR_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request_handler.h" +#include "include/capi/cef_request_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefAllowCertificateErrorCallbackCppToC + : public CefCppToC { + public: + explicit CefAllowCertificateErrorCallbackCppToC( + CefAllowCertificateErrorCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_ALLOW_CERTIFICATE_ERROR_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/app_cpptoc.cc b/libcef_dll/cpptoc/app_cpptoc.cc new file mode 100644 index 000000000..f1e2c8a56 --- /dev/null +++ b/libcef_dll/cpptoc/app_cpptoc.cc @@ -0,0 +1,125 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/app_cpptoc.h" +#include "libcef_dll/cpptoc/browser_process_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_process_handler_cpptoc.h" +#include "libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h" +#include "libcef_dll/ctocpp/command_line_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_registrar_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK app_on_before_command_line_processing(struct _cef_app_t* self, + const cef_string_t* process_type, + struct _cef_command_line_t* command_line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: command_line; type: refptr_diff + DCHECK(command_line); + if (!command_line) + return; + // Unverified params: process_type + + // Execute + CefAppCppToC::Get(self)->OnBeforeCommandLineProcessing( + CefString(process_type), + CefCommandLineCToCpp::Wrap(command_line)); +} + +void CEF_CALLBACK app_on_register_custom_schemes(struct _cef_app_t* self, + struct _cef_scheme_registrar_t* registrar) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: registrar; type: refptr_diff + DCHECK(registrar); + if (!registrar) + return; + + // Execute + CefAppCppToC::Get(self)->OnRegisterCustomSchemes( + CefSchemeRegistrarCToCpp::Wrap(registrar)); +} + +struct _cef_resource_bundle_handler_t* CEF_CALLBACK app_get_resource_bundle_handler( + struct _cef_app_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefAppCppToC::Get( + self)->GetResourceBundleHandler(); + + // Return type: refptr_same + return CefResourceBundleHandlerCppToC::Wrap(_retval); +} + +struct _cef_browser_process_handler_t* CEF_CALLBACK app_get_browser_process_handler( + struct _cef_app_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefAppCppToC::Get( + self)->GetBrowserProcessHandler(); + + // Return type: refptr_same + return CefBrowserProcessHandlerCppToC::Wrap(_retval); +} + +struct _cef_render_process_handler_t* CEF_CALLBACK app_get_render_process_handler( + struct _cef_app_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefAppCppToC::Get( + self)->GetRenderProcessHandler(); + + // Return type: refptr_same + return CefRenderProcessHandlerCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefAppCppToC::CefAppCppToC(CefApp* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_command_line_processing = + app_on_before_command_line_processing; + struct_.struct_.on_register_custom_schemes = app_on_register_custom_schemes; + struct_.struct_.get_resource_bundle_handler = app_get_resource_bundle_handler; + struct_.struct_.get_browser_process_handler = app_get_browser_process_handler; + struct_.struct_.get_render_process_handler = app_get_render_process_handler; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/app_cpptoc.h b/libcef_dll/cpptoc/app_cpptoc.h new file mode 100644 index 000000000..9fc731c09 --- /dev/null +++ b/libcef_dll/cpptoc/app_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_APP_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_APP_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_app.h" +#include "include/capi/cef_app_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefAppCppToC + : public CefCppToC { + public: + explicit CefAppCppToC(CefApp* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_APP_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/auth_callback_cpptoc.cc b/libcef_dll/cpptoc/auth_callback_cpptoc.cc new file mode 100644 index 000000000..87c4ec2a0 --- /dev/null +++ b/libcef_dll/cpptoc/auth_callback_cpptoc.cc @@ -0,0 +1,65 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/auth_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK auth_callback_cont(struct _cef_auth_callback_t* self, + const cef_string_t* username, const cef_string_t* password) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: username; type: string_byref_const + DCHECK(username); + if (!username) + return; + // Verify param: password; type: string_byref_const + DCHECK(password); + if (!password) + return; + + // Execute + CefAuthCallbackCppToC::Get(self)->Continue( + CefString(username), + CefString(password)); +} + +void CEF_CALLBACK auth_callback_cancel(struct _cef_auth_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefAuthCallbackCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefAuthCallbackCppToC::CefAuthCallbackCppToC(CefAuthCallback* cls) + : CefCppToC( + cls) { + struct_.struct_.cont = auth_callback_cont; + struct_.struct_.cancel = auth_callback_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/auth_callback_cpptoc.h b/libcef_dll/cpptoc/auth_callback_cpptoc.h new file mode 100644 index 000000000..5dd75e20e --- /dev/null +++ b/libcef_dll/cpptoc/auth_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_AUTH_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_AUTH_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_auth_callback.h" +#include "include/capi/cef_auth_callback_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefAuthCallbackCppToC + : public CefCppToC { + public: + explicit CefAuthCallbackCppToC(CefAuthCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_AUTH_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/base_cpptoc.h b/libcef_dll/cpptoc/base_cpptoc.h new file mode 100644 index 000000000..fc20cb7ca --- /dev/null +++ b/libcef_dll/cpptoc/base_cpptoc.h @@ -0,0 +1,148 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DLL_CPPTOC_BASE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_BASE_CPPTOC_H_ +#pragma once + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_base.h" +#include "include/capi/cef_base_capi.h" + +// CefCppToC implementation for CefBase. +class CefBaseCppToC : public CefBase { + public: + // Use this method to retrieve the underlying class instance from our + // own structure when the structure is passed as the required first + // parameter of a C API function call. No explicit reference counting + // is done in this case. + static CefRefPtr Get(cef_base_t* s) { + DCHECK(s); + + // Cast our structure to the wrapper structure type. + CefBaseCppToC::Struct* wrapperStruct = + reinterpret_cast(s); + // Return the underlying object instance. + return wrapperStruct->class_->GetClass(); + } + + // Use this method to create a wrapper structure for passing our class + // instance to the other side. + static cef_base_t* Wrap(CefRefPtr c) { + if (!c.get()) + return NULL; + + // Wrap our object with the CefCppToC class. + CefBaseCppToC* wrapper = new CefBaseCppToC(c); + // Add a reference to our wrapper object that will be released once our + // structure arrives on the other side. + wrapper->AddRef(); + // Return the structure pointer that can now be passed to the other side. + return wrapper->GetStruct(); + } + + // Use this method to retrieve the underlying class instance when receiving + // our wrapper structure back from the other side. + static CefRefPtr Unwrap(cef_base_t* s) { + if (!s) + return NULL; + + // Cast our structure to the wrapper structure type. + CefBaseCppToC::Struct* wrapperStruct = + reinterpret_cast(s); + // Add the underlying object instance to a smart pointer. + CefRefPtr objectPtr(wrapperStruct->class_->GetClass()); + // Release the reference to our wrapper object that was added before the + // structure was passed back to us. + wrapperStruct->class_->Release(); + // Return the underlying object instance. + return objectPtr; + } + + // Structure representation with pointer to the C++ class. + struct Struct { + cef_base_t struct_; + CefBaseCppToC* class_; + }; + + explicit CefBaseCppToC(CefBase* cls) + : class_(cls) { + DCHECK(cls); + + struct_.class_ = this; + + // zero the underlying structure and set base members + memset(&struct_.struct_, 0, sizeof(cef_base_t)); + struct_.struct_.size = sizeof(cef_base_t); + struct_.struct_.add_ref = struct_add_ref; + struct_.struct_.release = struct_release; + struct_.struct_.has_one_ref = struct_has_one_ref; + } + virtual ~CefBaseCppToC() {} + + CefBase* GetClass() { return class_; } + + // If returning the structure across the DLL boundary you should call + // AddRef() on this CefCppToC object. On the other side of the DLL boundary, + // call UnderlyingRelease() on the wrapping CefCToCpp object. + cef_base_t* GetStruct() { return &struct_.struct_; } + + // CefBase methods increment/decrement reference counts on both this object + // and the underlying wrapper class. + void AddRef() const { + UnderlyingAddRef(); + ref_count_.AddRef(); + } + bool Release() const { + UnderlyingRelease(); + if (ref_count_.Release()) { + delete this; + return true; + } + return false; + } + bool HasOneRef() const { return ref_count_.HasOneRef(); } + + // Increment/decrement reference counts on only the underlying class. + void UnderlyingAddRef() const { class_->AddRef(); } + bool UnderlyingRelease() const { return class_->Release(); } + bool UnderlyingHasOneRef() const { return class_->HasOneRef(); } + + private: + static void CEF_CALLBACK struct_add_ref(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return; + + Struct* impl = reinterpret_cast(base); + impl->class_->AddRef(); + } + + static int CEF_CALLBACK struct_release(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return impl->class_->Release(); + } + + static int CEF_CALLBACK struct_has_one_ref(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return impl->class_->HasOneRef(); + } + + CefRefCount ref_count_; + Struct struct_; + CefBase* class_; + + DISALLOW_COPY_AND_ASSIGN(CefBaseCppToC); +}; + +#endif // CEF_LIBCEF_DLL_CPPTOC_BASE_CPPTOC_H_ diff --git a/libcef_dll/cpptoc/before_download_callback_cpptoc.cc b/libcef_dll/cpptoc/before_download_callback_cpptoc.cc new file mode 100644 index 000000000..85efc93fe --- /dev/null +++ b/libcef_dll/cpptoc/before_download_callback_cpptoc.cc @@ -0,0 +1,49 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/before_download_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK before_download_callback_cont( + struct _cef_before_download_callback_t* self, + const cef_string_t* download_path, int show_dialog) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: download_path + + // Execute + CefBeforeDownloadCallbackCppToC::Get(self)->Continue( + CefString(download_path), + show_dialog?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBeforeDownloadCallbackCppToC::CefBeforeDownloadCallbackCppToC( + CefBeforeDownloadCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = before_download_callback_cont; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/cpptoc/before_download_callback_cpptoc.h b/libcef_dll/cpptoc/before_download_callback_cpptoc.h new file mode 100644 index 000000000..9aada2e1d --- /dev/null +++ b/libcef_dll/cpptoc/before_download_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_BEFORE_DOWNLOAD_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_BEFORE_DOWNLOAD_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_download_handler.h" +#include "include/capi/cef_download_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefBeforeDownloadCallbackCppToC + : public CefCppToC { + public: + explicit CefBeforeDownloadCallbackCppToC(CefBeforeDownloadCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_BEFORE_DOWNLOAD_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/binary_value_cpptoc.cc b/libcef_dll/cpptoc/binary_value_cpptoc.cc new file mode 100644 index 000000000..6b397e8f7 --- /dev/null +++ b/libcef_dll/cpptoc/binary_value_cpptoc.cc @@ -0,0 +1,134 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/binary_value_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_binary_value_t* cef_binary_value_create(const void* data, + size_t data_size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return NULL; + + // Execute + CefRefPtr _retval = CefBinaryValue::Create( + data, + data_size); + + // Return type: refptr_same + return CefBinaryValueCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK binary_value_is_valid(struct _cef_binary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBinaryValueCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK binary_value_is_owned(struct _cef_binary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBinaryValueCppToC::Get(self)->IsOwned(); + + // Return type: bool + return _retval; +} + +struct _cef_binary_value_t* CEF_CALLBACK binary_value_copy( + struct _cef_binary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBinaryValueCppToC::Get(self)->Copy(); + + // Return type: refptr_same + return CefBinaryValueCppToC::Wrap(_retval); +} + +size_t CEF_CALLBACK binary_value_get_size(struct _cef_binary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefBinaryValueCppToC::Get(self)->GetSize(); + + // Return type: simple + return _retval; +} + +size_t CEF_CALLBACK binary_value_get_data(struct _cef_binary_value_t* self, + void* buffer, size_t buffer_size, size_t data_offset) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return 0; + + // Execute + size_t _retval = CefBinaryValueCppToC::Get(self)->GetData( + buffer, + buffer_size, + data_offset); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBinaryValueCppToC::CefBinaryValueCppToC(CefBinaryValue* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = binary_value_is_valid; + struct_.struct_.is_owned = binary_value_is_owned; + struct_.struct_.copy = binary_value_copy; + struct_.struct_.get_size = binary_value_get_size; + struct_.struct_.get_data = binary_value_get_data; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/binary_value_cpptoc.h b/libcef_dll/cpptoc/binary_value_cpptoc.h new file mode 100644 index 000000000..a4df9b293 --- /dev/null +++ b/libcef_dll/cpptoc/binary_value_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_BINARY_VALUE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_BINARY_VALUE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_values.h" +#include "include/capi/cef_values_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefBinaryValueCppToC + : public CefCppToC { + public: + explicit CefBinaryValueCppToC(CefBinaryValue* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_BINARY_VALUE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/browser_cpptoc.cc b/libcef_dll/cpptoc/browser_cpptoc.cc new file mode 100644 index 000000000..79ccc316c --- /dev/null +++ b/libcef_dll/cpptoc/browser_cpptoc.cc @@ -0,0 +1,387 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/browser_host_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/process_message_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +struct _cef_browser_host_t* CEF_CALLBACK browser_get_host( + struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserCppToC::Get(self)->GetHost(); + + // Return type: refptr_same + return CefBrowserHostCppToC::Wrap(_retval); +} + +int CEF_CALLBACK browser_can_go_back(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->CanGoBack(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_go_back(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->GoBack(); +} + +int CEF_CALLBACK browser_can_go_forward(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->CanGoForward(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_go_forward(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->GoForward(); +} + +int CEF_CALLBACK browser_is_loading(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->IsLoading(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_reload(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->Reload(); +} + +void CEF_CALLBACK browser_reload_ignore_cache(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->ReloadIgnoreCache(); +} + +void CEF_CALLBACK browser_stop_load(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->StopLoad(); +} + +int CEF_CALLBACK browser_get_identifier(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefBrowserCppToC::Get(self)->GetIdentifier(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK browser_is_same(struct _cef_browser_t* self, + struct _cef_browser_t* that) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: that; type: refptr_same + DCHECK(that); + if (!that) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->IsSame( + CefBrowserCppToC::Unwrap(that)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK browser_is_popup(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->IsPopup(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK browser_has_document(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->HasDocument(); + + // Return type: bool + return _retval; +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_main_frame( + struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserCppToC::Get(self)->GetMainFrame(); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_focused_frame( + struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserCppToC::Get(self)->GetFocusedFrame(); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_frame_byident( + struct _cef_browser_t* self, int64 identifier) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserCppToC::Get(self)->GetFrame( + identifier); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +struct _cef_frame_t* CEF_CALLBACK browser_get_frame(struct _cef_browser_t* self, + const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Unverified params: name + + // Execute + CefRefPtr _retval = CefBrowserCppToC::Get(self)->GetFrame( + CefString(name)); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +size_t CEF_CALLBACK browser_get_frame_count(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefBrowserCppToC::Get(self)->GetFrameCount(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK browser_get_frame_identifiers(struct _cef_browser_t* self, + size_t* identifiersCount, int64* identifiers) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: identifiers; type: simple_vec_byref + DCHECK(identifiersCount && (*identifiersCount == 0 || identifiers)); + if (!identifiersCount || (*identifiersCount > 0 && !identifiers)) + return; + + // Translate param: identifiers; type: simple_vec_byref + std::vector identifiersList; + if (identifiersCount && *identifiersCount > 0 && identifiers) { + for (size_t i = 0; i < *identifiersCount; ++i) { + identifiersList.push_back(identifiers[i]); + } + } + + // Execute + CefBrowserCppToC::Get(self)->GetFrameIdentifiers( + identifiersList); + + // Restore param: identifiers; type: simple_vec_byref + if (identifiersCount && identifiers) { + *identifiersCount = std::min(identifiersList.size(), *identifiersCount); + if (*identifiersCount > 0) { + for (size_t i = 0; i < *identifiersCount; ++i) { + identifiers[i] = identifiersList[i]; + } + } + } +} + +void CEF_CALLBACK browser_get_frame_names(struct _cef_browser_t* self, + cef_string_list_t names) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: names; type: string_vec_byref + DCHECK(names); + if (!names) + return; + + // Translate param: names; type: string_vec_byref + std::vector namesList; + transfer_string_list_contents(names, namesList); + + // Execute + CefBrowserCppToC::Get(self)->GetFrameNames( + namesList); + + // Restore param: names; type: string_vec_byref + cef_string_list_clear(names); + transfer_string_list_contents(namesList, names); +} + +int CEF_CALLBACK browser_send_process_message(struct _cef_browser_t* self, + cef_process_id_t target_process, struct _cef_process_message_t* message) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: message; type: refptr_same + DCHECK(message); + if (!message) + return 0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->SendProcessMessage( + target_process, + CefProcessMessageCppToC::Unwrap(message)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBrowserCppToC::CefBrowserCppToC(CefBrowser* cls) + : CefCppToC(cls) { + struct_.struct_.get_host = browser_get_host; + struct_.struct_.can_go_back = browser_can_go_back; + struct_.struct_.go_back = browser_go_back; + struct_.struct_.can_go_forward = browser_can_go_forward; + struct_.struct_.go_forward = browser_go_forward; + struct_.struct_.is_loading = browser_is_loading; + struct_.struct_.reload = browser_reload; + struct_.struct_.reload_ignore_cache = browser_reload_ignore_cache; + struct_.struct_.stop_load = browser_stop_load; + struct_.struct_.get_identifier = browser_get_identifier; + struct_.struct_.is_same = browser_is_same; + struct_.struct_.is_popup = browser_is_popup; + struct_.struct_.has_document = browser_has_document; + struct_.struct_.get_main_frame = browser_get_main_frame; + struct_.struct_.get_focused_frame = browser_get_focused_frame; + struct_.struct_.get_frame_byident = browser_get_frame_byident; + struct_.struct_.get_frame = browser_get_frame; + struct_.struct_.get_frame_count = browser_get_frame_count; + struct_.struct_.get_frame_identifiers = browser_get_frame_identifiers; + struct_.struct_.get_frame_names = browser_get_frame_names; + struct_.struct_.send_process_message = browser_send_process_message; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/browser_cpptoc.h b/libcef_dll/cpptoc/browser_cpptoc.h new file mode 100644 index 000000000..a3ee8a4dd --- /dev/null +++ b/libcef_dll/cpptoc/browser_cpptoc.h @@ -0,0 +1,37 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_BROWSER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_BROWSER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefBrowserCppToC + : public CefCppToC { + public: + explicit CefBrowserCppToC(CefBrowser* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_BROWSER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/browser_host_cpptoc.cc b/libcef_dll/cpptoc/browser_host_cpptoc.cc new file mode 100644 index 000000000..d49cf73a7 --- /dev/null +++ b/libcef_dll/cpptoc/browser_host_cpptoc.cc @@ -0,0 +1,900 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/browser_host_cpptoc.h" +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/cpptoc/request_context_cpptoc.h" +#include "libcef_dll/ctocpp/client_ctocpp.h" +#include "libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h" +#include "libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT int cef_browser_host_create_browser( + const cef_window_info_t* windowInfo, struct _cef_client_t* client, + const cef_string_t* url, const struct _cef_browser_settings_t* settings, + struct _cef_request_context_t* request_context) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: windowInfo; type: struct_byref_const + DCHECK(windowInfo); + if (!windowInfo) + return 0; + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return 0; + // Unverified params: client, url, request_context + + // Translate param: windowInfo; type: struct_byref_const + CefWindowInfo windowInfoObj; + if (windowInfo) + windowInfoObj.Set(*windowInfo, false); + // Translate param: settings; type: struct_byref_const + CefBrowserSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + + // Execute + bool _retval = CefBrowserHost::CreateBrowser( + windowInfoObj, + CefClientCToCpp::Wrap(client), + CefString(url), + settingsObj, + CefRequestContextCppToC::Unwrap(request_context)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT cef_browser_t* cef_browser_host_create_browser_sync( + const cef_window_info_t* windowInfo, struct _cef_client_t* client, + const cef_string_t* url, const struct _cef_browser_settings_t* settings, + struct _cef_request_context_t* request_context) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: windowInfo; type: struct_byref_const + DCHECK(windowInfo); + if (!windowInfo) + return NULL; + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return NULL; + // Unverified params: client, url, request_context + + // Translate param: windowInfo; type: struct_byref_const + CefWindowInfo windowInfoObj; + if (windowInfo) + windowInfoObj.Set(*windowInfo, false); + // Translate param: settings; type: struct_byref_const + CefBrowserSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + + // Execute + CefRefPtr _retval = CefBrowserHost::CreateBrowserSync( + windowInfoObj, + CefClientCToCpp::Wrap(client), + CefString(url), + settingsObj, + CefRequestContextCppToC::Unwrap(request_context)); + + // Return type: refptr_same + return CefBrowserCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_browser_t* CEF_CALLBACK browser_host_get_browser( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserHostCppToC::Get(self)->GetBrowser(); + + // Return type: refptr_same + return CefBrowserCppToC::Wrap(_retval); +} + +void CEF_CALLBACK browser_host_close_browser(struct _cef_browser_host_t* self, + int force_close) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->CloseBrowser( + force_close?true:false); +} + +void CEF_CALLBACK browser_host_set_focus(struct _cef_browser_host_t* self, + int focus) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->SetFocus( + focus?true:false); +} + +void CEF_CALLBACK browser_host_set_window_visibility( + struct _cef_browser_host_t* self, int visible) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->SetWindowVisibility( + visible?true:false); +} + +cef_window_handle_t CEF_CALLBACK browser_host_get_window_handle( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return kNullWindowHandle; + + // Execute + cef_window_handle_t _retval = CefBrowserHostCppToC::Get( + self)->GetWindowHandle(); + + // Return type: simple + return _retval; +} + +cef_window_handle_t CEF_CALLBACK browser_host_get_opener_window_handle( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return kNullWindowHandle; + + // Execute + cef_window_handle_t _retval = CefBrowserHostCppToC::Get( + self)->GetOpenerWindowHandle(); + + // Return type: simple + return _retval; +} + +struct _cef_client_t* CEF_CALLBACK browser_host_get_client( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserHostCppToC::Get(self)->GetClient(); + + // Return type: refptr_diff + return CefClientCToCpp::Unwrap(_retval); +} + +struct _cef_request_context_t* CEF_CALLBACK browser_host_get_request_context( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserHostCppToC::Get( + self)->GetRequestContext(); + + // Return type: refptr_same + return CefRequestContextCppToC::Wrap(_retval); +} + +double CEF_CALLBACK browser_host_get_zoom_level( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + double _retval = CefBrowserHostCppToC::Get(self)->GetZoomLevel(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK browser_host_set_zoom_level(struct _cef_browser_host_t* self, + double zoomLevel) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->SetZoomLevel( + zoomLevel); +} + +void CEF_CALLBACK browser_host_run_file_dialog(struct _cef_browser_host_t* self, + cef_file_dialog_mode_t mode, const cef_string_t* title, + const cef_string_t* default_file_path, cef_string_list_t accept_filters, + int selected_accept_filter, cef_run_file_dialog_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return; + // Unverified params: title, default_file_path, accept_filters + + // Translate param: accept_filters; type: string_vec_byref_const + std::vector accept_filtersList; + transfer_string_list_contents(accept_filters, accept_filtersList); + + // Execute + CefBrowserHostCppToC::Get(self)->RunFileDialog( + mode, + CefString(title), + CefString(default_file_path), + accept_filtersList, + selected_accept_filter, + CefRunFileDialogCallbackCToCpp::Wrap(callback)); +} + +void CEF_CALLBACK browser_host_start_download(struct _cef_browser_host_t* self, + const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->StartDownload( + CefString(url)); +} + +void CEF_CALLBACK browser_host_print(struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->Print(); +} + +void CEF_CALLBACK browser_host_find(struct _cef_browser_host_t* self, + int identifier, const cef_string_t* searchText, int forward, int matchCase, + int findNext) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: searchText; type: string_byref_const + DCHECK(searchText); + if (!searchText) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->Find( + identifier, + CefString(searchText), + forward?true:false, + matchCase?true:false, + findNext?true:false); +} + +void CEF_CALLBACK browser_host_stop_finding(struct _cef_browser_host_t* self, + int clearSelection) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->StopFinding( + clearSelection?true:false); +} + +void CEF_CALLBACK browser_host_show_dev_tools(struct _cef_browser_host_t* self, + const cef_window_info_t* windowInfo, struct _cef_client_t* client, + const struct _cef_browser_settings_t* settings, + const cef_point_t* inspect_element_at) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: windowInfo; type: struct_byref_const + DCHECK(windowInfo); + if (!windowInfo) + return; + // Verify param: client; type: refptr_diff + DCHECK(client); + if (!client) + return; + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return; + // Unverified params: inspect_element_at + + // Translate param: windowInfo; type: struct_byref_const + CefWindowInfo windowInfoObj; + if (windowInfo) + windowInfoObj.Set(*windowInfo, false); + // Translate param: settings; type: struct_byref_const + CefBrowserSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + // Translate param: inspect_element_at; type: simple_byref_const + CefPoint inspect_element_atVal = + inspect_element_at?*inspect_element_at:CefPoint(); + + // Execute + CefBrowserHostCppToC::Get(self)->ShowDevTools( + windowInfoObj, + CefClientCToCpp::Wrap(client), + settingsObj, + inspect_element_atVal); +} + +void CEF_CALLBACK browser_host_close_dev_tools( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->CloseDevTools(); +} + +void CEF_CALLBACK browser_host_get_navigation_entries( + struct _cef_browser_host_t* self, cef_navigation_entry_visitor_t* visitor, + int current_only) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->GetNavigationEntries( + CefNavigationEntryVisitorCToCpp::Wrap(visitor), + current_only?true:false); +} + +void CEF_CALLBACK browser_host_set_mouse_cursor_change_disabled( + struct _cef_browser_host_t* self, int disabled) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->SetMouseCursorChangeDisabled( + disabled?true:false); +} + +int CEF_CALLBACK browser_host_is_mouse_cursor_change_disabled( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserHostCppToC::Get(self)->IsMouseCursorChangeDisabled(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_host_replace_misspelling( + struct _cef_browser_host_t* self, const cef_string_t* word) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: word; type: string_byref_const + DCHECK(word); + if (!word) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->ReplaceMisspelling( + CefString(word)); +} + +void CEF_CALLBACK browser_host_add_word_to_dictionary( + struct _cef_browser_host_t* self, const cef_string_t* word) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: word; type: string_byref_const + DCHECK(word); + if (!word) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->AddWordToDictionary( + CefString(word)); +} + +int CEF_CALLBACK browser_host_is_window_rendering_disabled( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefBrowserHostCppToC::Get(self)->IsWindowRenderingDisabled(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_host_was_resized(struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->WasResized(); +} + +void CEF_CALLBACK browser_host_was_hidden(struct _cef_browser_host_t* self, + int hidden) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->WasHidden( + hidden?true:false); +} + +void CEF_CALLBACK browser_host_notify_screen_info_changed( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->NotifyScreenInfoChanged(); +} + +void CEF_CALLBACK browser_host_invalidate(struct _cef_browser_host_t* self, + cef_paint_element_type_t type) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->Invalidate( + type); +} + +void CEF_CALLBACK browser_host_send_key_event(struct _cef_browser_host_t* self, + const struct _cef_key_event_t* event) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefKeyEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->SendKeyEvent( + eventObj); +} + +void CEF_CALLBACK browser_host_send_mouse_click_event( + struct _cef_browser_host_t* self, const struct _cef_mouse_event_t* event, + cef_mouse_button_type_t type, int mouseUp, int clickCount) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefMouseEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->SendMouseClickEvent( + eventObj, + type, + mouseUp?true:false, + clickCount); +} + +void CEF_CALLBACK browser_host_send_mouse_move_event( + struct _cef_browser_host_t* self, const struct _cef_mouse_event_t* event, + int mouseLeave) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefMouseEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->SendMouseMoveEvent( + eventObj, + mouseLeave?true:false); +} + +void CEF_CALLBACK browser_host_send_mouse_wheel_event( + struct _cef_browser_host_t* self, const struct _cef_mouse_event_t* event, + int deltaX, int deltaY) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefMouseEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->SendMouseWheelEvent( + eventObj, + deltaX, + deltaY); +} + +void CEF_CALLBACK browser_host_send_focus_event( + struct _cef_browser_host_t* self, int setFocus) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->SendFocusEvent( + setFocus?true:false); +} + +void CEF_CALLBACK browser_host_send_capture_lost_event( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->SendCaptureLostEvent(); +} + +void CEF_CALLBACK browser_host_notify_move_or_resize_started( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->NotifyMoveOrResizeStarted(); +} + +cef_text_input_context_t CEF_CALLBACK browser_host_get_nstext_input_context( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + cef_text_input_context_t _retval = CefBrowserHostCppToC::Get( + self)->GetNSTextInputContext(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK browser_host_handle_key_event_before_text_input_client( + struct _cef_browser_host_t* self, cef_event_handle_t keyEvent) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->HandleKeyEventBeforeTextInputClient( + keyEvent); +} + +void CEF_CALLBACK browser_host_handle_key_event_after_text_input_client( + struct _cef_browser_host_t* self, cef_event_handle_t keyEvent) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->HandleKeyEventAfterTextInputClient( + keyEvent); +} + +void CEF_CALLBACK browser_host_drag_target_drag_enter( + struct _cef_browser_host_t* self, struct _cef_drag_data_t* drag_data, + const struct _cef_mouse_event_t* event, + cef_drag_operations_mask_t allowed_ops) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: drag_data; type: refptr_same + DCHECK(drag_data); + if (!drag_data) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefMouseEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->DragTargetDragEnter( + CefDragDataCppToC::Unwrap(drag_data), + eventObj, + allowed_ops); +} + +void CEF_CALLBACK browser_host_drag_target_drag_over( + struct _cef_browser_host_t* self, const struct _cef_mouse_event_t* event, + cef_drag_operations_mask_t allowed_ops) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefMouseEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->DragTargetDragOver( + eventObj, + allowed_ops); +} + +void CEF_CALLBACK browser_host_drag_target_drag_leave( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->DragTargetDragLeave(); +} + +void CEF_CALLBACK browser_host_drag_target_drop( + struct _cef_browser_host_t* self, const struct _cef_mouse_event_t* event) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return; + + // Translate param: event; type: struct_byref_const + CefMouseEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + CefBrowserHostCppToC::Get(self)->DragTargetDrop( + eventObj); +} + +void CEF_CALLBACK browser_host_drag_source_ended_at( + struct _cef_browser_host_t* self, int x, int y, + cef_drag_operations_mask_t op) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->DragSourceEndedAt( + x, + y, + op); +} + +void CEF_CALLBACK browser_host_drag_source_system_drag_ended( + struct _cef_browser_host_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserHostCppToC::Get(self)->DragSourceSystemDragEnded(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBrowserHostCppToC::CefBrowserHostCppToC(CefBrowserHost* cls) + : CefCppToC(cls) { + struct_.struct_.get_browser = browser_host_get_browser; + struct_.struct_.close_browser = browser_host_close_browser; + struct_.struct_.set_focus = browser_host_set_focus; + struct_.struct_.set_window_visibility = browser_host_set_window_visibility; + struct_.struct_.get_window_handle = browser_host_get_window_handle; + struct_.struct_.get_opener_window_handle = + browser_host_get_opener_window_handle; + struct_.struct_.get_client = browser_host_get_client; + struct_.struct_.get_request_context = browser_host_get_request_context; + struct_.struct_.get_zoom_level = browser_host_get_zoom_level; + struct_.struct_.set_zoom_level = browser_host_set_zoom_level; + struct_.struct_.run_file_dialog = browser_host_run_file_dialog; + struct_.struct_.start_download = browser_host_start_download; + struct_.struct_.print = browser_host_print; + struct_.struct_.find = browser_host_find; + struct_.struct_.stop_finding = browser_host_stop_finding; + struct_.struct_.show_dev_tools = browser_host_show_dev_tools; + struct_.struct_.close_dev_tools = browser_host_close_dev_tools; + struct_.struct_.get_navigation_entries = browser_host_get_navigation_entries; + struct_.struct_.set_mouse_cursor_change_disabled = + browser_host_set_mouse_cursor_change_disabled; + struct_.struct_.is_mouse_cursor_change_disabled = + browser_host_is_mouse_cursor_change_disabled; + struct_.struct_.replace_misspelling = browser_host_replace_misspelling; + struct_.struct_.add_word_to_dictionary = browser_host_add_word_to_dictionary; + struct_.struct_.is_window_rendering_disabled = + browser_host_is_window_rendering_disabled; + struct_.struct_.was_resized = browser_host_was_resized; + struct_.struct_.was_hidden = browser_host_was_hidden; + struct_.struct_.notify_screen_info_changed = + browser_host_notify_screen_info_changed; + struct_.struct_.invalidate = browser_host_invalidate; + struct_.struct_.send_key_event = browser_host_send_key_event; + struct_.struct_.send_mouse_click_event = browser_host_send_mouse_click_event; + struct_.struct_.send_mouse_move_event = browser_host_send_mouse_move_event; + struct_.struct_.send_mouse_wheel_event = browser_host_send_mouse_wheel_event; + struct_.struct_.send_focus_event = browser_host_send_focus_event; + struct_.struct_.send_capture_lost_event = + browser_host_send_capture_lost_event; + struct_.struct_.notify_move_or_resize_started = + browser_host_notify_move_or_resize_started; + struct_.struct_.get_nstext_input_context = + browser_host_get_nstext_input_context; + struct_.struct_.handle_key_event_before_text_input_client = + browser_host_handle_key_event_before_text_input_client; + struct_.struct_.handle_key_event_after_text_input_client = + browser_host_handle_key_event_after_text_input_client; + struct_.struct_.drag_target_drag_enter = browser_host_drag_target_drag_enter; + struct_.struct_.drag_target_drag_over = browser_host_drag_target_drag_over; + struct_.struct_.drag_target_drag_leave = browser_host_drag_target_drag_leave; + struct_.struct_.drag_target_drop = browser_host_drag_target_drop; + struct_.struct_.drag_source_ended_at = browser_host_drag_source_ended_at; + struct_.struct_.drag_source_system_drag_ended = + browser_host_drag_source_system_drag_ended; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/browser_host_cpptoc.h b/libcef_dll/cpptoc/browser_host_cpptoc.h new file mode 100644 index 000000000..e9a12860c --- /dev/null +++ b/libcef_dll/cpptoc/browser_host_cpptoc.h @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_BROWSER_HOST_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_BROWSER_HOST_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefBrowserHostCppToC + : public CefCppToC { + public: + explicit CefBrowserHostCppToC(CefBrowserHost* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_BROWSER_HOST_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/browser_process_handler_cpptoc.cc b/libcef_dll/cpptoc/browser_process_handler_cpptoc.cc new file mode 100644 index 000000000..dda5544d6 --- /dev/null +++ b/libcef_dll/cpptoc/browser_process_handler_cpptoc.cc @@ -0,0 +1,105 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_process_handler_cpptoc.h" +#include "libcef_dll/cpptoc/print_handler_cpptoc.h" +#include "libcef_dll/ctocpp/command_line_ctocpp.h" +#include "libcef_dll/ctocpp/list_value_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK browser_process_handler_on_context_initialized( + struct _cef_browser_process_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserProcessHandlerCppToC::Get(self)->OnContextInitialized(); +} + +void CEF_CALLBACK browser_process_handler_on_before_child_process_launch( + struct _cef_browser_process_handler_t* self, + struct _cef_command_line_t* command_line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: command_line; type: refptr_diff + DCHECK(command_line); + if (!command_line) + return; + + // Execute + CefBrowserProcessHandlerCppToC::Get(self)->OnBeforeChildProcessLaunch( + CefCommandLineCToCpp::Wrap(command_line)); +} + +void CEF_CALLBACK browser_process_handler_on_render_process_thread_created( + struct _cef_browser_process_handler_t* self, + struct _cef_list_value_t* extra_info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: extra_info; type: refptr_diff + DCHECK(extra_info); + if (!extra_info) + return; + + // Execute + CefBrowserProcessHandlerCppToC::Get(self)->OnRenderProcessThreadCreated( + CefListValueCToCpp::Wrap(extra_info)); +} + +struct _cef_print_handler_t* CEF_CALLBACK browser_process_handler_get_print_handler( + struct _cef_browser_process_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefBrowserProcessHandlerCppToC::Get( + self)->GetPrintHandler(); + + // Return type: refptr_same + return CefPrintHandlerCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBrowserProcessHandlerCppToC::CefBrowserProcessHandlerCppToC( + CefBrowserProcessHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_context_initialized = + browser_process_handler_on_context_initialized; + struct_.struct_.on_before_child_process_launch = + browser_process_handler_on_before_child_process_launch; + struct_.struct_.on_render_process_thread_created = + browser_process_handler_on_render_process_thread_created; + struct_.struct_.get_print_handler = browser_process_handler_get_print_handler; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/browser_process_handler_cpptoc.h b/libcef_dll/cpptoc/browser_process_handler_cpptoc.h new file mode 100644 index 000000000..fdc471b9b --- /dev/null +++ b/libcef_dll/cpptoc/browser_process_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_BROWSER_PROCESS_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_BROWSER_PROCESS_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_browser_process_handler.h" +#include "include/capi/cef_browser_process_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefBrowserProcessHandlerCppToC + : public CefCppToC { + public: + explicit CefBrowserProcessHandlerCppToC(CefBrowserProcessHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_BROWSER_PROCESS_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/callback_cpptoc.cc b/libcef_dll/cpptoc/callback_cpptoc.cc new file mode 100644 index 000000000..9fdad966a --- /dev/null +++ b/libcef_dll/cpptoc/callback_cpptoc.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK callback_cont(struct _cef_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefCallbackCppToC::Get(self)->Continue(); +} + +void CEF_CALLBACK callback_cancel(struct _cef_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefCallbackCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefCallbackCppToC::CefCallbackCppToC(CefCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = callback_cont; + struct_.struct_.cancel = callback_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/callback_cpptoc.h b/libcef_dll/cpptoc/callback_cpptoc.h new file mode 100644 index 000000000..375927b2a --- /dev/null +++ b/libcef_dll/cpptoc/callback_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_callback.h" +#include "include/capi/cef_callback_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefCallbackCppToC + : public CefCppToC { + public: + explicit CefCallbackCppToC(CefCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/client_cpptoc.cc b/libcef_dll/cpptoc/client_cpptoc.cc new file mode 100644 index 000000000..5d7d4820f --- /dev/null +++ b/libcef_dll/cpptoc/client_cpptoc.cc @@ -0,0 +1,312 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/client_cpptoc.h" +#include "libcef_dll/cpptoc/context_menu_handler_cpptoc.h" +#include "libcef_dll/cpptoc/dialog_handler_cpptoc.h" +#include "libcef_dll/cpptoc/display_handler_cpptoc.h" +#include "libcef_dll/cpptoc/download_handler_cpptoc.h" +#include "libcef_dll/cpptoc/drag_handler_cpptoc.h" +#include "libcef_dll/cpptoc/find_handler_cpptoc.h" +#include "libcef_dll/cpptoc/focus_handler_cpptoc.h" +#include "libcef_dll/cpptoc/geolocation_handler_cpptoc.h" +#include "libcef_dll/cpptoc/jsdialog_handler_cpptoc.h" +#include "libcef_dll/cpptoc/keyboard_handler_cpptoc.h" +#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h" +#include "libcef_dll/cpptoc/load_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_handler_cpptoc.h" +#include "libcef_dll/cpptoc/request_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/process_message_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +struct _cef_context_menu_handler_t* CEF_CALLBACK client_get_context_menu_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetContextMenuHandler(); + + // Return type: refptr_same + return CefContextMenuHandlerCppToC::Wrap(_retval); +} + +struct _cef_dialog_handler_t* CEF_CALLBACK client_get_dialog_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetDialogHandler(); + + // Return type: refptr_same + return CefDialogHandlerCppToC::Wrap(_retval); +} + +struct _cef_display_handler_t* CEF_CALLBACK client_get_display_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetDisplayHandler(); + + // Return type: refptr_same + return CefDisplayHandlerCppToC::Wrap(_retval); +} + +struct _cef_download_handler_t* CEF_CALLBACK client_get_download_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetDownloadHandler(); + + // Return type: refptr_same + return CefDownloadHandlerCppToC::Wrap(_retval); +} + +struct _cef_drag_handler_t* CEF_CALLBACK client_get_drag_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetDragHandler(); + + // Return type: refptr_same + return CefDragHandlerCppToC::Wrap(_retval); +} + +struct _cef_find_handler_t* CEF_CALLBACK client_get_find_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetFindHandler(); + + // Return type: refptr_same + return CefFindHandlerCppToC::Wrap(_retval); +} + +struct _cef_focus_handler_t* CEF_CALLBACK client_get_focus_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetFocusHandler(); + + // Return type: refptr_same + return CefFocusHandlerCppToC::Wrap(_retval); +} + +struct _cef_geolocation_handler_t* CEF_CALLBACK client_get_geolocation_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetGeolocationHandler(); + + // Return type: refptr_same + return CefGeolocationHandlerCppToC::Wrap(_retval); +} + +struct _cef_jsdialog_handler_t* CEF_CALLBACK client_get_jsdialog_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetJSDialogHandler(); + + // Return type: refptr_same + return CefJSDialogHandlerCppToC::Wrap(_retval); +} + +struct _cef_keyboard_handler_t* CEF_CALLBACK client_get_keyboard_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetKeyboardHandler(); + + // Return type: refptr_same + return CefKeyboardHandlerCppToC::Wrap(_retval); +} + +struct _cef_life_span_handler_t* CEF_CALLBACK client_get_life_span_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetLifeSpanHandler(); + + // Return type: refptr_same + return CefLifeSpanHandlerCppToC::Wrap(_retval); +} + +struct _cef_load_handler_t* CEF_CALLBACK client_get_load_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetLoadHandler(); + + // Return type: refptr_same + return CefLoadHandlerCppToC::Wrap(_retval); +} + +struct _cef_render_handler_t* CEF_CALLBACK client_get_render_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetRenderHandler(); + + // Return type: refptr_same + return CefRenderHandlerCppToC::Wrap(_retval); +} + +struct _cef_request_handler_t* CEF_CALLBACK client_get_request_handler( + struct _cef_client_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefClientCppToC::Get( + self)->GetRequestHandler(); + + // Return type: refptr_same + return CefRequestHandlerCppToC::Wrap(_retval); +} + +int CEF_CALLBACK client_on_process_message_received(struct _cef_client_t* self, + cef_browser_t* browser, cef_process_id_t source_process, + struct _cef_process_message_t* message) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: message; type: refptr_diff + DCHECK(message); + if (!message) + return 0; + + // Execute + bool _retval = CefClientCppToC::Get(self)->OnProcessMessageReceived( + CefBrowserCToCpp::Wrap(browser), + source_process, + CefProcessMessageCToCpp::Wrap(message)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefClientCppToC::CefClientCppToC(CefClient* cls) + : CefCppToC(cls) { + struct_.struct_.get_context_menu_handler = client_get_context_menu_handler; + struct_.struct_.get_dialog_handler = client_get_dialog_handler; + struct_.struct_.get_display_handler = client_get_display_handler; + struct_.struct_.get_download_handler = client_get_download_handler; + struct_.struct_.get_drag_handler = client_get_drag_handler; + struct_.struct_.get_find_handler = client_get_find_handler; + struct_.struct_.get_focus_handler = client_get_focus_handler; + struct_.struct_.get_geolocation_handler = client_get_geolocation_handler; + struct_.struct_.get_jsdialog_handler = client_get_jsdialog_handler; + struct_.struct_.get_keyboard_handler = client_get_keyboard_handler; + struct_.struct_.get_life_span_handler = client_get_life_span_handler; + struct_.struct_.get_load_handler = client_get_load_handler; + struct_.struct_.get_render_handler = client_get_render_handler; + struct_.struct_.get_request_handler = client_get_request_handler; + struct_.struct_.on_process_message_received = + client_on_process_message_received; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/client_cpptoc.h b/libcef_dll/cpptoc/client_cpptoc.h new file mode 100644 index 000000000..ae3135ec5 --- /dev/null +++ b/libcef_dll/cpptoc/client_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_CLIENT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_CLIENT_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefClientCppToC + : public CefCppToC { + public: + explicit CefClientCppToC(CefClient* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_CLIENT_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/command_line_cpptoc.cc b/libcef_dll/cpptoc/command_line_cpptoc.cc new file mode 100644 index 000000000..561c050b2 --- /dev/null +++ b/libcef_dll/cpptoc/command_line_cpptoc.cc @@ -0,0 +1,428 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/command_line_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_command_line_t* cef_command_line_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefCommandLine::CreateCommandLine(); + + // Return type: refptr_same + return CefCommandLineCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_command_line_t* cef_command_line_get_global() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefCommandLine::GetGlobalCommandLine(); + + // Return type: refptr_same + return CefCommandLineCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK command_line_is_valid(struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefCommandLineCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK command_line_is_read_only(struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefCommandLineCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +struct _cef_command_line_t* CEF_CALLBACK command_line_copy( + struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefCommandLineCppToC::Get(self)->Copy(); + + // Return type: refptr_same + return CefCommandLineCppToC::Wrap(_retval); +} + +void CEF_CALLBACK command_line_init_from_argv(struct _cef_command_line_t* self, + int argc, const char* const* argv) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: argv; type: simple_byaddr + DCHECK(argv); + if (!argv) + return; + + // Execute + CefCommandLineCppToC::Get(self)->InitFromArgv( + argc, + argv); +} + +void CEF_CALLBACK command_line_init_from_string( + struct _cef_command_line_t* self, const cef_string_t* command_line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: command_line; type: string_byref_const + DCHECK(command_line); + if (!command_line) + return; + + // Execute + CefCommandLineCppToC::Get(self)->InitFromString( + CefString(command_line)); +} + +void CEF_CALLBACK command_line_reset(struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefCommandLineCppToC::Get(self)->Reset(); +} + +void CEF_CALLBACK command_line_get_argv(struct _cef_command_line_t* self, + cef_string_list_t argv) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: argv; type: string_vec_byref + DCHECK(argv); + if (!argv) + return; + + // Translate param: argv; type: string_vec_byref + std::vector argvList; + transfer_string_list_contents(argv, argvList); + + // Execute + CefCommandLineCppToC::Get(self)->GetArgv( + argvList); + + // Restore param: argv; type: string_vec_byref + cef_string_list_clear(argv); + transfer_string_list_contents(argvList, argv); +} + +cef_string_userfree_t CEF_CALLBACK command_line_get_command_line_string( + struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefCommandLineCppToC::Get(self)->GetCommandLineString(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK command_line_get_program( + struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefCommandLineCppToC::Get(self)->GetProgram(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK command_line_set_program(struct _cef_command_line_t* self, + const cef_string_t* program) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: program; type: string_byref_const + DCHECK(program); + if (!program) + return; + + // Execute + CefCommandLineCppToC::Get(self)->SetProgram( + CefString(program)); +} + +int CEF_CALLBACK command_line_has_switches(struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefCommandLineCppToC::Get(self)->HasSwitches(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK command_line_has_switch(struct _cef_command_line_t* self, + const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return 0; + + // Execute + bool _retval = CefCommandLineCppToC::Get(self)->HasSwitch( + CefString(name)); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK command_line_get_switch_value( + struct _cef_command_line_t* self, const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return NULL; + + // Execute + CefString _retval = CefCommandLineCppToC::Get(self)->GetSwitchValue( + CefString(name)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK command_line_get_switches(struct _cef_command_line_t* self, + cef_string_map_t switches) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: switches; type: string_map_single_byref + DCHECK(switches); + if (!switches) + return; + + // Translate param: switches; type: string_map_single_byref + std::map switchesMap; + transfer_string_map_contents(switches, switchesMap); + + // Execute + CefCommandLineCppToC::Get(self)->GetSwitches( + switchesMap); + + // Restore param: switches; type: string_map_single_byref + cef_string_map_clear(switches); + transfer_string_map_contents(switchesMap, switches); +} + +void CEF_CALLBACK command_line_append_switch(struct _cef_command_line_t* self, + const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return; + + // Execute + CefCommandLineCppToC::Get(self)->AppendSwitch( + CefString(name)); +} + +void CEF_CALLBACK command_line_append_switch_with_value( + struct _cef_command_line_t* self, const cef_string_t* name, + const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return; + // Verify param: value; type: string_byref_const + DCHECK(value); + if (!value) + return; + + // Execute + CefCommandLineCppToC::Get(self)->AppendSwitchWithValue( + CefString(name), + CefString(value)); +} + +int CEF_CALLBACK command_line_has_arguments(struct _cef_command_line_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefCommandLineCppToC::Get(self)->HasArguments(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK command_line_get_arguments(struct _cef_command_line_t* self, + cef_string_list_t arguments) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: arguments; type: string_vec_byref + DCHECK(arguments); + if (!arguments) + return; + + // Translate param: arguments; type: string_vec_byref + std::vector argumentsList; + transfer_string_list_contents(arguments, argumentsList); + + // Execute + CefCommandLineCppToC::Get(self)->GetArguments( + argumentsList); + + // Restore param: arguments; type: string_vec_byref + cef_string_list_clear(arguments); + transfer_string_list_contents(argumentsList, arguments); +} + +void CEF_CALLBACK command_line_append_argument(struct _cef_command_line_t* self, + const cef_string_t* argument) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: argument; type: string_byref_const + DCHECK(argument); + if (!argument) + return; + + // Execute + CefCommandLineCppToC::Get(self)->AppendArgument( + CefString(argument)); +} + +void CEF_CALLBACK command_line_prepend_wrapper(struct _cef_command_line_t* self, + const cef_string_t* wrapper) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: wrapper; type: string_byref_const + DCHECK(wrapper); + if (!wrapper) + return; + + // Execute + CefCommandLineCppToC::Get(self)->PrependWrapper( + CefString(wrapper)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefCommandLineCppToC::CefCommandLineCppToC(CefCommandLine* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = command_line_is_valid; + struct_.struct_.is_read_only = command_line_is_read_only; + struct_.struct_.copy = command_line_copy; + struct_.struct_.init_from_argv = command_line_init_from_argv; + struct_.struct_.init_from_string = command_line_init_from_string; + struct_.struct_.reset = command_line_reset; + struct_.struct_.get_argv = command_line_get_argv; + struct_.struct_.get_command_line_string = + command_line_get_command_line_string; + struct_.struct_.get_program = command_line_get_program; + struct_.struct_.set_program = command_line_set_program; + struct_.struct_.has_switches = command_line_has_switches; + struct_.struct_.has_switch = command_line_has_switch; + struct_.struct_.get_switch_value = command_line_get_switch_value; + struct_.struct_.get_switches = command_line_get_switches; + struct_.struct_.append_switch = command_line_append_switch; + struct_.struct_.append_switch_with_value = + command_line_append_switch_with_value; + struct_.struct_.has_arguments = command_line_has_arguments; + struct_.struct_.get_arguments = command_line_get_arguments; + struct_.struct_.append_argument = command_line_append_argument; + struct_.struct_.prepend_wrapper = command_line_prepend_wrapper; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/command_line_cpptoc.h b/libcef_dll/cpptoc/command_line_cpptoc.h new file mode 100644 index 000000000..f7ae49f7c --- /dev/null +++ b/libcef_dll/cpptoc/command_line_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_COMMAND_LINE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_COMMAND_LINE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_command_line.h" +#include "include/capi/cef_command_line_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefCommandLineCppToC + : public CefCppToC { + public: + explicit CefCommandLineCppToC(CefCommandLine* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COMMAND_LINE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/completion_callback_cpptoc.cc b/libcef_dll/cpptoc/completion_callback_cpptoc.cc new file mode 100644 index 000000000..ff217b148 --- /dev/null +++ b/libcef_dll/cpptoc/completion_callback_cpptoc.cc @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/completion_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK completion_callback_on_complete( + struct _cef_completion_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefCompletionCallbackCppToC::Get(self)->OnComplete(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefCompletionCallbackCppToC::CefCompletionCallbackCppToC( + CefCompletionCallback* cls) + : CefCppToC(cls) { + struct_.struct_.on_complete = completion_callback_on_complete; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/completion_callback_cpptoc.h b/libcef_dll/cpptoc/completion_callback_cpptoc.h new file mode 100644 index 000000000..cc5acfecd --- /dev/null +++ b/libcef_dll/cpptoc/completion_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_COMPLETION_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_COMPLETION_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_callback.h" +#include "include/capi/cef_callback_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefCompletionCallbackCppToC + : public CefCppToC { + public: + explicit CefCompletionCallbackCppToC(CefCompletionCallback* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COMPLETION_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/context_menu_handler_cpptoc.cc b/libcef_dll/cpptoc/context_menu_handler_cpptoc.cc new file mode 100644 index 000000000..5cf6447b8 --- /dev/null +++ b/libcef_dll/cpptoc/context_menu_handler_cpptoc.cc @@ -0,0 +1,132 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/context_menu_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/context_menu_params_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/menu_model_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK context_menu_handler_on_before_context_menu( + struct _cef_context_menu_handler_t* self, cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_context_menu_params_t* params, + struct _cef_menu_model_t* model) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: params; type: refptr_diff + DCHECK(params); + if (!params) + return; + // Verify param: model; type: refptr_diff + DCHECK(model); + if (!model) + return; + + // Execute + CefContextMenuHandlerCppToC::Get(self)->OnBeforeContextMenu( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefContextMenuParamsCToCpp::Wrap(params), + CefMenuModelCToCpp::Wrap(model)); +} + +int CEF_CALLBACK context_menu_handler_on_context_menu_command( + struct _cef_context_menu_handler_t* self, cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_context_menu_params_t* params, + int command_id, cef_event_flags_t event_flags) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: params; type: refptr_diff + DCHECK(params); + if (!params) + return 0; + + // Execute + bool _retval = CefContextMenuHandlerCppToC::Get(self)->OnContextMenuCommand( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefContextMenuParamsCToCpp::Wrap(params), + command_id, + event_flags); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK context_menu_handler_on_context_menu_dismissed( + struct _cef_context_menu_handler_t* self, cef_browser_t* browser, + struct _cef_frame_t* frame) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + + // Execute + CefContextMenuHandlerCppToC::Get(self)->OnContextMenuDismissed( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefContextMenuHandlerCppToC::CefContextMenuHandlerCppToC( + CefContextMenuHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_context_menu = + context_menu_handler_on_before_context_menu; + struct_.struct_.on_context_menu_command = + context_menu_handler_on_context_menu_command; + struct_.struct_.on_context_menu_dismissed = + context_menu_handler_on_context_menu_dismissed; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/context_menu_handler_cpptoc.h b/libcef_dll/cpptoc/context_menu_handler_cpptoc.h new file mode 100644 index 000000000..6931f39c6 --- /dev/null +++ b/libcef_dll/cpptoc/context_menu_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_CONTEXT_MENU_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_CONTEXT_MENU_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_context_menu_handler.h" +#include "include/capi/cef_context_menu_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefContextMenuHandlerCppToC + : public CefCppToC { + public: + explicit CefContextMenuHandlerCppToC(CefContextMenuHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_CONTEXT_MENU_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/context_menu_params_cpptoc.cc b/libcef_dll/cpptoc/context_menu_params_cpptoc.cc new file mode 100644 index 000000000..650d8bf3f --- /dev/null +++ b/libcef_dll/cpptoc/context_menu_params_cpptoc.cc @@ -0,0 +1,362 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/context_menu_params_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK context_menu_params_get_xcoord( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefContextMenuParamsCppToC::Get(self)->GetXCoord(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK context_menu_params_get_ycoord( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefContextMenuParamsCppToC::Get(self)->GetYCoord(); + + // Return type: simple + return _retval; +} + +cef_context_menu_type_flags_t CEF_CALLBACK context_menu_params_get_type_flags( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CM_TYPEFLAG_NONE; + + // Execute + cef_context_menu_type_flags_t _retval = CefContextMenuParamsCppToC::Get( + self)->GetTypeFlags(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_link_url( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetLinkUrl(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_unfiltered_link_url( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get( + self)->GetUnfilteredLinkUrl(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_source_url( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetSourceUrl(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK context_menu_params_has_image_contents( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefContextMenuParamsCppToC::Get(self)->HasImageContents(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_page_url( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetPageUrl(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_frame_url( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetFrameUrl(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_frame_charset( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetFrameCharset(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_context_menu_media_type_t CEF_CALLBACK context_menu_params_get_media_type( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CM_MEDIATYPE_NONE; + + // Execute + cef_context_menu_media_type_t _retval = CefContextMenuParamsCppToC::Get( + self)->GetMediaType(); + + // Return type: simple + return _retval; +} + +cef_context_menu_media_state_flags_t CEF_CALLBACK context_menu_params_get_media_state_flags( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CM_MEDIAFLAG_NONE; + + // Execute + cef_context_menu_media_state_flags_t _retval = + CefContextMenuParamsCppToC::Get(self)->GetMediaStateFlags(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_selection_text( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetSelectionText(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK context_menu_params_get_misspelled_word( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefContextMenuParamsCppToC::Get(self)->GetMisspelledWord( + ); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK context_menu_params_get_misspelling_hash( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefContextMenuParamsCppToC::Get(self)->GetMisspellingHash(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK context_menu_params_get_dictionary_suggestions( + struct _cef_context_menu_params_t* self, cef_string_list_t suggestions) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: suggestions; type: string_vec_byref + DCHECK(suggestions); + if (!suggestions) + return 0; + + // Translate param: suggestions; type: string_vec_byref + std::vector suggestionsList; + transfer_string_list_contents(suggestions, suggestionsList); + + // Execute + bool _retval = CefContextMenuParamsCppToC::Get( + self)->GetDictionarySuggestions( + suggestionsList); + + // Restore param: suggestions; type: string_vec_byref + cef_string_list_clear(suggestions); + transfer_string_list_contents(suggestionsList, suggestions); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK context_menu_params_is_editable( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefContextMenuParamsCppToC::Get(self)->IsEditable(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK context_menu_params_is_spell_check_enabled( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefContextMenuParamsCppToC::Get(self)->IsSpellCheckEnabled(); + + // Return type: bool + return _retval; +} + +cef_context_menu_edit_state_flags_t CEF_CALLBACK context_menu_params_get_edit_state_flags( + struct _cef_context_menu_params_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CM_EDITFLAG_NONE; + + // Execute + cef_context_menu_edit_state_flags_t _retval = CefContextMenuParamsCppToC::Get( + self)->GetEditStateFlags(); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefContextMenuParamsCppToC::CefContextMenuParamsCppToC( + CefContextMenuParams* cls) + : CefCppToC(cls) { + struct_.struct_.get_xcoord = context_menu_params_get_xcoord; + struct_.struct_.get_ycoord = context_menu_params_get_ycoord; + struct_.struct_.get_type_flags = context_menu_params_get_type_flags; + struct_.struct_.get_link_url = context_menu_params_get_link_url; + struct_.struct_.get_unfiltered_link_url = + context_menu_params_get_unfiltered_link_url; + struct_.struct_.get_source_url = context_menu_params_get_source_url; + struct_.struct_.has_image_contents = context_menu_params_has_image_contents; + struct_.struct_.get_page_url = context_menu_params_get_page_url; + struct_.struct_.get_frame_url = context_menu_params_get_frame_url; + struct_.struct_.get_frame_charset = context_menu_params_get_frame_charset; + struct_.struct_.get_media_type = context_menu_params_get_media_type; + struct_.struct_.get_media_state_flags = + context_menu_params_get_media_state_flags; + struct_.struct_.get_selection_text = context_menu_params_get_selection_text; + struct_.struct_.get_misspelled_word = context_menu_params_get_misspelled_word; + struct_.struct_.get_misspelling_hash = + context_menu_params_get_misspelling_hash; + struct_.struct_.get_dictionary_suggestions = + context_menu_params_get_dictionary_suggestions; + struct_.struct_.is_editable = context_menu_params_is_editable; + struct_.struct_.is_spell_check_enabled = + context_menu_params_is_spell_check_enabled; + struct_.struct_.get_edit_state_flags = + context_menu_params_get_edit_state_flags; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/context_menu_params_cpptoc.h b/libcef_dll/cpptoc/context_menu_params_cpptoc.h new file mode 100644 index 000000000..9420c46c1 --- /dev/null +++ b/libcef_dll/cpptoc/context_menu_params_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_CONTEXT_MENU_PARAMS_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_CONTEXT_MENU_PARAMS_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_context_menu_handler.h" +#include "include/capi/cef_context_menu_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefContextMenuParamsCppToC + : public CefCppToC { + public: + explicit CefContextMenuParamsCppToC(CefContextMenuParams* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_CONTEXT_MENU_PARAMS_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/cookie_manager_cpptoc.cc b/libcef_dll/cpptoc/cookie_manager_cpptoc.cc new file mode 100644 index 000000000..38e0be3c4 --- /dev/null +++ b/libcef_dll/cpptoc/cookie_manager_cpptoc.cc @@ -0,0 +1,225 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h" +#include "libcef_dll/ctocpp/completion_callback_ctocpp.h" +#include "libcef_dll/ctocpp/cookie_visitor_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_get_global_manager() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefCookieManager::GetGlobalManager(); + + // Return type: refptr_same + return CefCookieManagerCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager( + const cef_string_t* path, int persist_session_cookies) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: path + + // Execute + CefRefPtr _retval = CefCookieManager::CreateManager( + CefString(path), + persist_session_cookies?true:false); + + // Return type: refptr_same + return CefCookieManagerCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK cookie_manager_set_supported_schemes( + struct _cef_cookie_manager_t* self, cef_string_list_t schemes) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: schemes; type: string_vec_byref_const + DCHECK(schemes); + if (!schemes) + return; + + // Translate param: schemes; type: string_vec_byref_const + std::vector schemesList; + transfer_string_list_contents(schemes, schemesList); + + // Execute + CefCookieManagerCppToC::Get(self)->SetSupportedSchemes( + schemesList); +} + +int CEF_CALLBACK cookie_manager_visit_all_cookies( + struct _cef_cookie_manager_t* self, + struct _cef_cookie_visitor_t* visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return 0; + + // Execute + bool _retval = CefCookieManagerCppToC::Get(self)->VisitAllCookies( + CefCookieVisitorCToCpp::Wrap(visitor)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK cookie_manager_visit_url_cookies( + struct _cef_cookie_manager_t* self, const cef_string_t* url, + int includeHttpOnly, struct _cef_cookie_visitor_t* visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return 0; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return 0; + + // Execute + bool _retval = CefCookieManagerCppToC::Get(self)->VisitUrlCookies( + CefString(url), + includeHttpOnly?true:false, + CefCookieVisitorCToCpp::Wrap(visitor)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK cookie_manager_set_cookie(struct _cef_cookie_manager_t* self, + const cef_string_t* url, const struct _cef_cookie_t* cookie) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return 0; + // Verify param: cookie; type: struct_byref_const + DCHECK(cookie); + if (!cookie) + return 0; + + // Translate param: cookie; type: struct_byref_const + CefCookie cookieObj; + if (cookie) + cookieObj.Set(*cookie, false); + + // Execute + bool _retval = CefCookieManagerCppToC::Get(self)->SetCookie( + CefString(url), + cookieObj); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK cookie_manager_delete_cookies( + struct _cef_cookie_manager_t* self, const cef_string_t* url, + const cef_string_t* cookie_name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: url, cookie_name + + // Execute + bool _retval = CefCookieManagerCppToC::Get(self)->DeleteCookies( + CefString(url), + CefString(cookie_name)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK cookie_manager_set_storage_path( + struct _cef_cookie_manager_t* self, const cef_string_t* path, + int persist_session_cookies) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: path + + // Execute + bool _retval = CefCookieManagerCppToC::Get(self)->SetStoragePath( + CefString(path), + persist_session_cookies?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK cookie_manager_flush_store(struct _cef_cookie_manager_t* self, + cef_completion_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefCookieManagerCppToC::Get(self)->FlushStore( + CefCompletionCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefCookieManagerCppToC::CefCookieManagerCppToC(CefCookieManager* cls) + : CefCppToC( + cls) { + struct_.struct_.set_supported_schemes = cookie_manager_set_supported_schemes; + struct_.struct_.visit_all_cookies = cookie_manager_visit_all_cookies; + struct_.struct_.visit_url_cookies = cookie_manager_visit_url_cookies; + struct_.struct_.set_cookie = cookie_manager_set_cookie; + struct_.struct_.delete_cookies = cookie_manager_delete_cookies; + struct_.struct_.set_storage_path = cookie_manager_set_storage_path; + struct_.struct_.flush_store = cookie_manager_flush_store; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/cookie_manager_cpptoc.h b/libcef_dll/cpptoc/cookie_manager_cpptoc.h new file mode 100644 index 000000000..440bb9fd3 --- /dev/null +++ b/libcef_dll/cpptoc/cookie_manager_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_COOKIE_MANAGER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_COOKIE_MANAGER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_cookie.h" +#include "include/capi/cef_cookie_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefCookieManagerCppToC + : public CefCppToC { + public: + explicit CefCookieManagerCppToC(CefCookieManager* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COOKIE_MANAGER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/cookie_visitor_cpptoc.cc b/libcef_dll/cpptoc/cookie_visitor_cpptoc.cc new file mode 100644 index 000000000..a67434411 --- /dev/null +++ b/libcef_dll/cpptoc/cookie_visitor_cpptoc.cc @@ -0,0 +1,70 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/cookie_visitor_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK cookie_visitor_visit(struct _cef_cookie_visitor_t* self, + const struct _cef_cookie_t* cookie, int count, int total, + int* deleteCookie) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: cookie; type: struct_byref_const + DCHECK(cookie); + if (!cookie) + return 0; + // Verify param: deleteCookie; type: bool_byref + DCHECK(deleteCookie); + if (!deleteCookie) + return 0; + + // Translate param: cookie; type: struct_byref_const + CefCookie cookieObj; + if (cookie) + cookieObj.Set(*cookie, false); + // Translate param: deleteCookie; type: bool_byref + bool deleteCookieBool = (deleteCookie && *deleteCookie)?true:false; + + // Execute + bool _retval = CefCookieVisitorCppToC::Get(self)->Visit( + cookieObj, + count, + total, + deleteCookieBool); + + // Restore param: deleteCookie; type: bool_byref + if (deleteCookie) + *deleteCookie = deleteCookieBool?true:false; + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefCookieVisitorCppToC::CefCookieVisitorCppToC(CefCookieVisitor* cls) + : CefCppToC( + cls) { + struct_.struct_.visit = cookie_visitor_visit; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/cookie_visitor_cpptoc.h b/libcef_dll/cpptoc/cookie_visitor_cpptoc.h new file mode 100644 index 000000000..af6729efd --- /dev/null +++ b/libcef_dll/cpptoc/cookie_visitor_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_COOKIE_VISITOR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_COOKIE_VISITOR_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_cookie.h" +#include "include/capi/cef_cookie_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefCookieVisitorCppToC + : public CefCppToC { + public: + explicit CefCookieVisitorCppToC(CefCookieVisitor* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COOKIE_VISITOR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/cpptoc.h b/libcef_dll/cpptoc/cpptoc.h new file mode 100644 index 000000000..a1b37d99e --- /dev/null +++ b/libcef_dll/cpptoc/cpptoc.h @@ -0,0 +1,165 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DLL_CPPTOC_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_CPPTOC_H_ +#pragma once + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_base.h" +#include "include/capi/cef_base_capi.h" + + +// Wrap a C++ class with a C structure. This is used when the class +// implementation exists on this side of the DLL boundary but will have methods +// called from the other side of the DLL boundary. +template +class CefCppToC : public CefBase { + public: + // Structure representation with pointer to the C++ class. + struct Struct { + StructName struct_; + CefCppToC* class_; + }; + + // Use this method to retrieve the underlying class instance from our + // own structure when the structure is passed as the required first + // parameter of a C API function call. No explicit reference counting + // is done in this case. + static CefRefPtr Get(StructName* s) { + DCHECK(s); + + // Cast our structure to the wrapper structure type. + Struct* wrapperStruct = reinterpret_cast(s); + // Return the underlying object instance. + return wrapperStruct->class_->GetClass(); + } + + // Use this method to create a wrapper structure for passing our class + // instance to the other side. + static StructName* Wrap(CefRefPtr c) { + if (!c.get()) + return NULL; + + // Wrap our object with the CefCppToC class. + ClassName* wrapper = new ClassName(c.get()); + // Add a reference to our wrapper object that will be released once our + // structure arrives on the other side. + wrapper->AddRef(); + // Return the structure pointer that can now be passed to the other side. + return wrapper->GetStruct(); + } + + // Use this method to retrieve the underlying class instance when receiving + // our wrapper structure back from the other side. + static CefRefPtr Unwrap(StructName* s) { + if (!s) + return NULL; + + // Cast our structure to the wrapper structure type. + Struct* wrapperStruct = reinterpret_cast(s); + // Add the underlying object instance to a smart pointer. + CefRefPtr objectPtr(wrapperStruct->class_->GetClass()); + // Release the reference to our wrapper object that was added before the + // structure was passed back to us. + wrapperStruct->class_->Release(); + // Return the underlying object instance. + return objectPtr; + } + + explicit CefCppToC(BaseName* cls) + : class_(cls) { + DCHECK(cls); + + struct_.class_ = this; + + // zero the underlying structure and set base members + memset(&struct_.struct_, 0, sizeof(StructName)); + struct_.struct_.base.size = sizeof(StructName); + struct_.struct_.base.add_ref = struct_add_ref; + struct_.struct_.base.release = struct_release; + struct_.struct_.base.has_one_ref = struct_has_one_ref; + +#ifndef NDEBUG + base::AtomicRefCountInc(&DebugObjCt); +#endif + } + virtual ~CefCppToC() { +#ifndef NDEBUG + base::AtomicRefCountDec(&DebugObjCt); +#endif + } + + BaseName* GetClass() { return class_; } + + // If returning the structure across the DLL boundary you should call + // AddRef() on this CefCppToC object. On the other side of the DLL boundary, + // call UnderlyingRelease() on the wrapping CefCToCpp object. + StructName* GetStruct() { return &struct_.struct_; } + + // CefBase methods increment/decrement reference counts on both this object + // and the underlying wrapper class. + void AddRef() const { + UnderlyingAddRef(); + ref_count_.AddRef(); + } + bool Release() const { + UnderlyingRelease(); + if (ref_count_.Release()) { + delete this; + return true; + } + return false; + } + bool HasOneRef() const { return ref_count_.HasOneRef(); } + + // Increment/decrement reference counts on only the underlying class. + void UnderlyingAddRef() const { class_->AddRef(); } + bool UnderlyingRelease() const { return class_->Release(); } + bool UnderlyingHasOneRef() const { return class_->HasOneRef(); } + +#ifndef NDEBUG + // Simple tracking of allocated objects. + static base::AtomicRefCount DebugObjCt; // NOLINT(runtime/int) +#endif + + protected: + Struct struct_; + BaseName* class_; + + private: + static void CEF_CALLBACK struct_add_ref(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return; + + Struct* impl = reinterpret_cast(base); + impl->class_->AddRef(); + } + + static int CEF_CALLBACK struct_release(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return impl->class_->Release(); + } + + static int CEF_CALLBACK struct_has_one_ref(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return impl->class_->HasOneRef(); + } + + CefRefCount ref_count_; + + DISALLOW_COPY_AND_ASSIGN(CefCppToC); +}; + +#endif // CEF_LIBCEF_DLL_CPPTOC_CPPTOC_H_ diff --git a/libcef_dll/cpptoc/dialog_handler_cpptoc.cc b/libcef_dll/cpptoc/dialog_handler_cpptoc.cc new file mode 100644 index 000000000..f5b2aa374 --- /dev/null +++ b/libcef_dll/cpptoc/dialog_handler_cpptoc.cc @@ -0,0 +1,76 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/dialog_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/file_dialog_callback_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK dialog_handler_on_file_dialog( + struct _cef_dialog_handler_t* self, cef_browser_t* browser, + cef_file_dialog_mode_t mode, const cef_string_t* title, + const cef_string_t* default_file_path, cef_string_list_t accept_filters, + int selected_accept_filter, cef_file_dialog_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + // Unverified params: title, default_file_path, accept_filters + + // Translate param: accept_filters; type: string_vec_byref_const + std::vector accept_filtersList; + transfer_string_list_contents(accept_filters, accept_filtersList); + + // Execute + bool _retval = CefDialogHandlerCppToC::Get(self)->OnFileDialog( + CefBrowserCToCpp::Wrap(browser), + mode, + CefString(title), + CefString(default_file_path), + accept_filtersList, + selected_accept_filter, + CefFileDialogCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDialogHandlerCppToC::CefDialogHandlerCppToC(CefDialogHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.on_file_dialog = dialog_handler_on_file_dialog; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/dialog_handler_cpptoc.h b/libcef_dll/cpptoc/dialog_handler_cpptoc.h new file mode 100644 index 000000000..235997380 --- /dev/null +++ b/libcef_dll/cpptoc/dialog_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DIALOG_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DIALOG_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_dialog_handler.h" +#include "include/capi/cef_dialog_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefDialogHandlerCppToC + : public CefCppToC { + public: + explicit CefDialogHandlerCppToC(CefDialogHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DIALOG_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/dictionary_value_cpptoc.cc b/libcef_dll/cpptoc/dictionary_value_cpptoc.cc new file mode 100644 index 000000000..ce7999ee2 --- /dev/null +++ b/libcef_dll/cpptoc/dictionary_value_cpptoc.cc @@ -0,0 +1,577 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/binary_value_cpptoc.h" +#include "libcef_dll/cpptoc/dictionary_value_cpptoc.h" +#include "libcef_dll/cpptoc/list_value_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_dictionary_value_t* cef_dictionary_value_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefDictionaryValue::Create(); + + // Return type: refptr_same + return CefDictionaryValueCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK dictionary_value_is_valid( + struct _cef_dictionary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_is_owned( + struct _cef_dictionary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->IsOwned(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_is_read_only( + struct _cef_dictionary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +struct _cef_dictionary_value_t* CEF_CALLBACK dictionary_value_copy( + struct _cef_dictionary_value_t* self, int exclude_empty_children) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDictionaryValueCppToC::Get( + self)->Copy( + exclude_empty_children?true:false); + + // Return type: refptr_same + return CefDictionaryValueCppToC::Wrap(_retval); +} + +size_t CEF_CALLBACK dictionary_value_get_size( + struct _cef_dictionary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefDictionaryValueCppToC::Get(self)->GetSize(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK dictionary_value_clear(struct _cef_dictionary_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->Clear(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_has_key(struct _cef_dictionary_value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->HasKey( + CefString(key)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_get_keys(struct _cef_dictionary_value_t* self, + cef_string_list_t keys) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: keys; type: string_vec_byref + DCHECK(keys); + if (!keys) + return 0; + + // Translate param: keys; type: string_vec_byref + std::vector keysList; + transfer_string_list_contents(keys, keysList); + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->GetKeys( + keysList); + + // Restore param: keys; type: string_vec_byref + cef_string_list_clear(keys); + transfer_string_list_contents(keysList, keys); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_remove(struct _cef_dictionary_value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->Remove( + CefString(key)); + + // Return type: bool + return _retval; +} + +cef_value_type_t CEF_CALLBACK dictionary_value_get_type( + struct _cef_dictionary_value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return VTYPE_INVALID; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return VTYPE_INVALID; + + // Execute + cef_value_type_t _retval = CefDictionaryValueCppToC::Get(self)->GetType( + CefString(key)); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK dictionary_value_get_bool(struct _cef_dictionary_value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->GetBool( + CefString(key)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_get_int(struct _cef_dictionary_value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + int _retval = CefDictionaryValueCppToC::Get(self)->GetInt( + CefString(key)); + + // Return type: simple + return _retval; +} + +double CEF_CALLBACK dictionary_value_get_double( + struct _cef_dictionary_value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + double _retval = CefDictionaryValueCppToC::Get(self)->GetDouble( + CefString(key)); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK dictionary_value_get_string( + struct _cef_dictionary_value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return NULL; + + // Execute + CefString _retval = CefDictionaryValueCppToC::Get(self)->GetString( + CefString(key)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_binary_value_t* CEF_CALLBACK dictionary_value_get_binary( + struct _cef_dictionary_value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return NULL; + + // Execute + CefRefPtr _retval = CefDictionaryValueCppToC::Get( + self)->GetBinary( + CefString(key)); + + // Return type: refptr_same + return CefBinaryValueCppToC::Wrap(_retval); +} + +struct _cef_dictionary_value_t* CEF_CALLBACK dictionary_value_get_dictionary( + struct _cef_dictionary_value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return NULL; + + // Execute + CefRefPtr _retval = CefDictionaryValueCppToC::Get( + self)->GetDictionary( + CefString(key)); + + // Return type: refptr_same + return CefDictionaryValueCppToC::Wrap(_retval); +} + +struct _cef_list_value_t* CEF_CALLBACK dictionary_value_get_list( + struct _cef_dictionary_value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return NULL; + + // Execute + CefRefPtr _retval = CefDictionaryValueCppToC::Get( + self)->GetList( + CefString(key)); + + // Return type: refptr_same + return CefListValueCppToC::Wrap(_retval); +} + +int CEF_CALLBACK dictionary_value_set_null(struct _cef_dictionary_value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetNull( + CefString(key)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_bool(struct _cef_dictionary_value_t* self, + const cef_string_t* key, int value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetBool( + CefString(key), + value?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_int(struct _cef_dictionary_value_t* self, + const cef_string_t* key, int value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetInt( + CefString(key), + value); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_double( + struct _cef_dictionary_value_t* self, const cef_string_t* key, + double value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetDouble( + CefString(key), + value); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_string( + struct _cef_dictionary_value_t* self, const cef_string_t* key, + const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + // Unverified params: value + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetString( + CefString(key), + CefString(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_binary( + struct _cef_dictionary_value_t* self, const cef_string_t* key, + cef_binary_value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetBinary( + CefString(key), + CefBinaryValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_dictionary( + struct _cef_dictionary_value_t* self, const cef_string_t* key, + struct _cef_dictionary_value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetDictionary( + CefString(key), + CefDictionaryValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK dictionary_value_set_list(struct _cef_dictionary_value_t* self, + const cef_string_t* key, struct _cef_list_value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefDictionaryValueCppToC::Get(self)->SetList( + CefString(key), + CefListValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDictionaryValueCppToC::CefDictionaryValueCppToC(CefDictionaryValue* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = dictionary_value_is_valid; + struct_.struct_.is_owned = dictionary_value_is_owned; + struct_.struct_.is_read_only = dictionary_value_is_read_only; + struct_.struct_.copy = dictionary_value_copy; + struct_.struct_.get_size = dictionary_value_get_size; + struct_.struct_.clear = dictionary_value_clear; + struct_.struct_.has_key = dictionary_value_has_key; + struct_.struct_.get_keys = dictionary_value_get_keys; + struct_.struct_.remove = dictionary_value_remove; + struct_.struct_.get_type = dictionary_value_get_type; + struct_.struct_.get_bool = dictionary_value_get_bool; + struct_.struct_.get_int = dictionary_value_get_int; + struct_.struct_.get_double = dictionary_value_get_double; + struct_.struct_.get_string = dictionary_value_get_string; + struct_.struct_.get_binary = dictionary_value_get_binary; + struct_.struct_.get_dictionary = dictionary_value_get_dictionary; + struct_.struct_.get_list = dictionary_value_get_list; + struct_.struct_.set_null = dictionary_value_set_null; + struct_.struct_.set_bool = dictionary_value_set_bool; + struct_.struct_.set_int = dictionary_value_set_int; + struct_.struct_.set_double = dictionary_value_set_double; + struct_.struct_.set_string = dictionary_value_set_string; + struct_.struct_.set_binary = dictionary_value_set_binary; + struct_.struct_.set_dictionary = dictionary_value_set_dictionary; + struct_.struct_.set_list = dictionary_value_set_list; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/dictionary_value_cpptoc.h b/libcef_dll/cpptoc/dictionary_value_cpptoc.h new file mode 100644 index 000000000..86ba43f1b --- /dev/null +++ b/libcef_dll/cpptoc/dictionary_value_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DICTIONARY_VALUE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DICTIONARY_VALUE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_values.h" +#include "include/capi/cef_values_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefDictionaryValueCppToC + : public CefCppToC { + public: + explicit CefDictionaryValueCppToC(CefDictionaryValue* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DICTIONARY_VALUE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/display_handler_cpptoc.cc b/libcef_dll/cpptoc/display_handler_cpptoc.cc new file mode 100644 index 000000000..0a64e2f0a --- /dev/null +++ b/libcef_dll/cpptoc/display_handler_cpptoc.cc @@ -0,0 +1,181 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/display_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK display_handler_on_address_change( + struct _cef_display_handler_t* self, cef_browser_t* browser, + struct _cef_frame_t* frame, const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefDisplayHandlerCppToC::Get(self)->OnAddressChange( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(url)); +} + +void CEF_CALLBACK display_handler_on_title_change( + struct _cef_display_handler_t* self, cef_browser_t* browser, + const cef_string_t* title) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Unverified params: title + + // Execute + CefDisplayHandlerCppToC::Get(self)->OnTitleChange( + CefBrowserCToCpp::Wrap(browser), + CefString(title)); +} + +void CEF_CALLBACK display_handler_on_favicon_urlchange( + struct _cef_display_handler_t* self, cef_browser_t* browser, + cef_string_list_t icon_urls) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Unverified params: icon_urls + + // Translate param: icon_urls; type: string_vec_byref_const + std::vector icon_urlsList; + transfer_string_list_contents(icon_urls, icon_urlsList); + + // Execute + CefDisplayHandlerCppToC::Get(self)->OnFaviconURLChange( + CefBrowserCToCpp::Wrap(browser), + icon_urlsList); +} + +int CEF_CALLBACK display_handler_on_tooltip(struct _cef_display_handler_t* self, + cef_browser_t* browser, cef_string_t* text) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Unverified params: text + + // Translate param: text; type: string_byref + CefString textStr(text); + + // Execute + bool _retval = CefDisplayHandlerCppToC::Get(self)->OnTooltip( + CefBrowserCToCpp::Wrap(browser), + textStr); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK display_handler_on_status_message( + struct _cef_display_handler_t* self, cef_browser_t* browser, + const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Unverified params: value + + // Execute + CefDisplayHandlerCppToC::Get(self)->OnStatusMessage( + CefBrowserCToCpp::Wrap(browser), + CefString(value)); +} + +int CEF_CALLBACK display_handler_on_console_message( + struct _cef_display_handler_t* self, cef_browser_t* browser, + const cef_string_t* message, const cef_string_t* source, int line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Unverified params: message, source + + // Execute + bool _retval = CefDisplayHandlerCppToC::Get(self)->OnConsoleMessage( + CefBrowserCToCpp::Wrap(browser), + CefString(message), + CefString(source), + line); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDisplayHandlerCppToC::CefDisplayHandlerCppToC(CefDisplayHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_address_change = display_handler_on_address_change; + struct_.struct_.on_title_change = display_handler_on_title_change; + struct_.struct_.on_favicon_urlchange = display_handler_on_favicon_urlchange; + struct_.struct_.on_tooltip = display_handler_on_tooltip; + struct_.struct_.on_status_message = display_handler_on_status_message; + struct_.struct_.on_console_message = display_handler_on_console_message; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/display_handler_cpptoc.h b/libcef_dll/cpptoc/display_handler_cpptoc.h new file mode 100644 index 000000000..c80b2427c --- /dev/null +++ b/libcef_dll/cpptoc/display_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DISPLAY_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DISPLAY_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_display_handler.h" +#include "include/capi/cef_display_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefDisplayHandlerCppToC + : public CefCppToC { + public: + explicit CefDisplayHandlerCppToC(CefDisplayHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DISPLAY_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/domdocument_cpptoc.cc b/libcef_dll/cpptoc/domdocument_cpptoc.cc new file mode 100644 index 000000000..a665eb557 --- /dev/null +++ b/libcef_dll/cpptoc/domdocument_cpptoc.cc @@ -0,0 +1,268 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/domdocument_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_dom_document_type_t CEF_CALLBACK domdocument_get_type( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return DOM_DOCUMENT_TYPE_UNKNOWN; + + // Execute + cef_dom_document_type_t _retval = CefDOMDocumentCppToC::Get(self)->GetType(); + + // Return type: simple + return _retval; +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_document( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMDocumentCppToC::Get(self)->GetDocument( + ); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_body( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMDocumentCppToC::Get(self)->GetBody(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_head( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMDocumentCppToC::Get(self)->GetHead(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +cef_string_userfree_t CEF_CALLBACK domdocument_get_title( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMDocumentCppToC::Get(self)->GetTitle(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_element_by_id( + struct _cef_domdocument_t* self, const cef_string_t* id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: id; type: string_byref_const + DCHECK(id); + if (!id) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMDocumentCppToC::Get( + self)->GetElementById( + CefString(id)); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_focused_node( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMDocumentCppToC::Get( + self)->GetFocusedNode(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +int CEF_CALLBACK domdocument_has_selection(struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMDocumentCppToC::Get(self)->HasSelection(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK domdocument_get_selection_start_offset( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefDOMDocumentCppToC::Get(self)->GetSelectionStartOffset(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK domdocument_get_selection_end_offset( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefDOMDocumentCppToC::Get(self)->GetSelectionEndOffset(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK domdocument_get_selection_as_markup( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMDocumentCppToC::Get(self)->GetSelectionAsMarkup(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK domdocument_get_selection_as_text( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMDocumentCppToC::Get(self)->GetSelectionAsText(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK domdocument_get_base_url( + struct _cef_domdocument_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMDocumentCppToC::Get(self)->GetBaseURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK domdocument_get_complete_url( + struct _cef_domdocument_t* self, const cef_string_t* partialURL) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: partialURL; type: string_byref_const + DCHECK(partialURL); + if (!partialURL) + return NULL; + + // Execute + CefString _retval = CefDOMDocumentCppToC::Get(self)->GetCompleteURL( + CefString(partialURL)); + + // Return type: string + return _retval.DetachToUserFree(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDOMDocumentCppToC::CefDOMDocumentCppToC(CefDOMDocument* cls) + : CefCppToC(cls) { + struct_.struct_.get_type = domdocument_get_type; + struct_.struct_.get_document = domdocument_get_document; + struct_.struct_.get_body = domdocument_get_body; + struct_.struct_.get_head = domdocument_get_head; + struct_.struct_.get_title = domdocument_get_title; + struct_.struct_.get_element_by_id = domdocument_get_element_by_id; + struct_.struct_.get_focused_node = domdocument_get_focused_node; + struct_.struct_.has_selection = domdocument_has_selection; + struct_.struct_.get_selection_start_offset = + domdocument_get_selection_start_offset; + struct_.struct_.get_selection_end_offset = + domdocument_get_selection_end_offset; + struct_.struct_.get_selection_as_markup = domdocument_get_selection_as_markup; + struct_.struct_.get_selection_as_text = domdocument_get_selection_as_text; + struct_.struct_.get_base_url = domdocument_get_base_url; + struct_.struct_.get_complete_url = domdocument_get_complete_url; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/domdocument_cpptoc.h b/libcef_dll/cpptoc/domdocument_cpptoc.h new file mode 100644 index 000000000..695de554c --- /dev/null +++ b/libcef_dll/cpptoc/domdocument_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DOMDOCUMENT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOMDOCUMENT_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_dom.h" +#include "include/capi/cef_dom_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefDOMDocumentCppToC + : public CefCppToC { + public: + explicit CefDOMDocumentCppToC(CefDOMDocument* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMDOCUMENT_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/domnode_cpptoc.cc b/libcef_dll/cpptoc/domnode_cpptoc.cc new file mode 100644 index 000000000..fb128c956 --- /dev/null +++ b/libcef_dll/cpptoc/domnode_cpptoc.cc @@ -0,0 +1,467 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/domdocument_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_dom_node_type_t CEF_CALLBACK domnode_get_type(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return DOM_NODE_TYPE_UNSUPPORTED; + + // Execute + cef_dom_node_type_t _retval = CefDOMNodeCppToC::Get(self)->GetType(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK domnode_is_text(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->IsText(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK domnode_is_element(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->IsElement(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK domnode_is_editable(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->IsEditable(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK domnode_is_form_control_element(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->IsFormControlElement(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_form_control_element_type( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetFormControlElementType(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK domnode_is_same(struct _cef_domnode_t* self, + struct _cef_domnode_t* that) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: that; type: refptr_same + DCHECK(that); + if (!that) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->IsSame( + CefDOMNodeCppToC::Unwrap(that)); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_name( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_value( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetValue(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK domnode_set_value(struct _cef_domnode_t* self, + const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: value; type: string_byref_const + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->SetValue( + CefString(value)); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_as_markup( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetAsMarkup(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_domdocument_t* CEF_CALLBACK domnode_get_document( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMNodeCppToC::Get(self)->GetDocument( + ); + + // Return type: refptr_same + return CefDOMDocumentCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domnode_get_parent( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMNodeCppToC::Get(self)->GetParent(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domnode_get_previous_sibling( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMNodeCppToC::Get( + self)->GetPreviousSibling(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domnode_get_next_sibling( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMNodeCppToC::Get(self)->GetNextSibling(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +int CEF_CALLBACK domnode_has_children(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->HasChildren(); + + // Return type: bool + return _retval; +} + +struct _cef_domnode_t* CEF_CALLBACK domnode_get_first_child( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMNodeCppToC::Get(self)->GetFirstChild(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +struct _cef_domnode_t* CEF_CALLBACK domnode_get_last_child( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMNodeCppToC::Get(self)->GetLastChild(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_element_tag_name( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetElementTagName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK domnode_has_element_attributes(struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->HasElementAttributes(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK domnode_has_element_attribute(struct _cef_domnode_t* self, + const cef_string_t* attrName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: attrName; type: string_byref_const + DCHECK(attrName); + if (!attrName) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->HasElementAttribute( + CefString(attrName)); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_element_attribute( + struct _cef_domnode_t* self, const cef_string_t* attrName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: attrName; type: string_byref_const + DCHECK(attrName); + if (!attrName) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetElementAttribute( + CefString(attrName)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK domnode_get_element_attributes(struct _cef_domnode_t* self, + cef_string_map_t attrMap) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: attrMap; type: string_map_single_byref + DCHECK(attrMap); + if (!attrMap) + return; + + // Translate param: attrMap; type: string_map_single_byref + std::map attrMapMap; + transfer_string_map_contents(attrMap, attrMapMap); + + // Execute + CefDOMNodeCppToC::Get(self)->GetElementAttributes( + attrMapMap); + + // Restore param: attrMap; type: string_map_single_byref + cef_string_map_clear(attrMap); + transfer_string_map_contents(attrMapMap, attrMap); +} + +int CEF_CALLBACK domnode_set_element_attribute(struct _cef_domnode_t* self, + const cef_string_t* attrName, const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: attrName; type: string_byref_const + DCHECK(attrName); + if (!attrName) + return 0; + // Verify param: value; type: string_byref_const + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefDOMNodeCppToC::Get(self)->SetElementAttribute( + CefString(attrName), + CefString(value)); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK domnode_get_element_inner_text( + struct _cef_domnode_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMNodeCppToC::Get(self)->GetElementInnerText(); + + // Return type: string + return _retval.DetachToUserFree(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDOMNodeCppToC::CefDOMNodeCppToC(CefDOMNode* cls) + : CefCppToC(cls) { + struct_.struct_.get_type = domnode_get_type; + struct_.struct_.is_text = domnode_is_text; + struct_.struct_.is_element = domnode_is_element; + struct_.struct_.is_editable = domnode_is_editable; + struct_.struct_.is_form_control_element = domnode_is_form_control_element; + struct_.struct_.get_form_control_element_type = + domnode_get_form_control_element_type; + struct_.struct_.is_same = domnode_is_same; + struct_.struct_.get_name = domnode_get_name; + struct_.struct_.get_value = domnode_get_value; + struct_.struct_.set_value = domnode_set_value; + struct_.struct_.get_as_markup = domnode_get_as_markup; + struct_.struct_.get_document = domnode_get_document; + struct_.struct_.get_parent = domnode_get_parent; + struct_.struct_.get_previous_sibling = domnode_get_previous_sibling; + struct_.struct_.get_next_sibling = domnode_get_next_sibling; + struct_.struct_.has_children = domnode_has_children; + struct_.struct_.get_first_child = domnode_get_first_child; + struct_.struct_.get_last_child = domnode_get_last_child; + struct_.struct_.get_element_tag_name = domnode_get_element_tag_name; + struct_.struct_.has_element_attributes = domnode_has_element_attributes; + struct_.struct_.has_element_attribute = domnode_has_element_attribute; + struct_.struct_.get_element_attribute = domnode_get_element_attribute; + struct_.struct_.get_element_attributes = domnode_get_element_attributes; + struct_.struct_.set_element_attribute = domnode_set_element_attribute; + struct_.struct_.get_element_inner_text = domnode_get_element_inner_text; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/domnode_cpptoc.h b/libcef_dll/cpptoc/domnode_cpptoc.h new file mode 100644 index 000000000..780f7cc16 --- /dev/null +++ b/libcef_dll/cpptoc/domnode_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DOMNODE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOMNODE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_dom.h" +#include "include/capi/cef_dom_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefDOMNodeCppToC + : public CefCppToC { + public: + explicit CefDOMNodeCppToC(CefDOMNode* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMNODE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/domvisitor_cpptoc.cc b/libcef_dll/cpptoc/domvisitor_cpptoc.cc new file mode 100644 index 000000000..fdf60cdd0 --- /dev/null +++ b/libcef_dll/cpptoc/domvisitor_cpptoc.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/domvisitor_cpptoc.h" +#include "libcef_dll/ctocpp/domdocument_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK domvisitor_visit(struct _cef_domvisitor_t* self, + struct _cef_domdocument_t* document) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: document; type: refptr_diff + DCHECK(document); + if (!document) + return; + + // Execute + CefDOMVisitorCppToC::Get(self)->Visit( + CefDOMDocumentCToCpp::Wrap(document)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDOMVisitorCppToC::CefDOMVisitorCppToC(CefDOMVisitor* cls) + : CefCppToC(cls) { + struct_.struct_.visit = domvisitor_visit; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/domvisitor_cpptoc.h b/libcef_dll/cpptoc/domvisitor_cpptoc.h new file mode 100644 index 000000000..3bdbe7168 --- /dev/null +++ b/libcef_dll/cpptoc/domvisitor_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DOMVISITOR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOMVISITOR_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_dom.h" +#include "include/capi/cef_dom_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefDOMVisitorCppToC + : public CefCppToC { + public: + explicit CefDOMVisitorCppToC(CefDOMVisitor* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMVISITOR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/download_handler_cpptoc.cc b/libcef_dll/cpptoc/download_handler_cpptoc.cc new file mode 100644 index 000000000..572bf7e02 --- /dev/null +++ b/libcef_dll/cpptoc/download_handler_cpptoc.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/download_handler_cpptoc.h" +#include "libcef_dll/ctocpp/before_download_callback_ctocpp.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/download_item_ctocpp.h" +#include "libcef_dll/ctocpp/download_item_callback_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK download_handler_on_before_download( + struct _cef_download_handler_t* self, cef_browser_t* browser, + struct _cef_download_item_t* download_item, + const cef_string_t* suggested_name, + cef_before_download_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: download_item; type: refptr_diff + DCHECK(download_item); + if (!download_item) + return; + // Verify param: suggested_name; type: string_byref_const + DCHECK(suggested_name); + if (!suggested_name) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return; + + // Execute + CefDownloadHandlerCppToC::Get(self)->OnBeforeDownload( + CefBrowserCToCpp::Wrap(browser), + CefDownloadItemCToCpp::Wrap(download_item), + CefString(suggested_name), + CefBeforeDownloadCallbackCToCpp::Wrap(callback)); +} + +void CEF_CALLBACK download_handler_on_download_updated( + struct _cef_download_handler_t* self, cef_browser_t* browser, + struct _cef_download_item_t* download_item, + cef_download_item_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: download_item; type: refptr_diff + DCHECK(download_item); + if (!download_item) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return; + + // Execute + CefDownloadHandlerCppToC::Get(self)->OnDownloadUpdated( + CefBrowserCToCpp::Wrap(browser), + CefDownloadItemCToCpp::Wrap(download_item), + CefDownloadItemCallbackCToCpp::Wrap(callback)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDownloadHandlerCppToC::CefDownloadHandlerCppToC(CefDownloadHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_download = download_handler_on_before_download; + struct_.struct_.on_download_updated = download_handler_on_download_updated; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/download_handler_cpptoc.h b/libcef_dll/cpptoc/download_handler_cpptoc.h new file mode 100644 index 000000000..b3acda7c8 --- /dev/null +++ b/libcef_dll/cpptoc/download_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_download_handler.h" +#include "include/capi/cef_download_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefDownloadHandlerCppToC + : public CefCppToC { + public: + explicit CefDownloadHandlerCppToC(CefDownloadHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/download_item_callback_cpptoc.cc b/libcef_dll/cpptoc/download_item_callback_cpptoc.cc new file mode 100644 index 000000000..b62d476a5 --- /dev/null +++ b/libcef_dll/cpptoc/download_item_callback_cpptoc.cc @@ -0,0 +1,70 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/download_item_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK download_item_callback_cancel( + struct _cef_download_item_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefDownloadItemCallbackCppToC::Get(self)->Cancel(); +} + +void CEF_CALLBACK download_item_callback_pause( + struct _cef_download_item_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefDownloadItemCallbackCppToC::Get(self)->Pause(); +} + +void CEF_CALLBACK download_item_callback_resume( + struct _cef_download_item_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefDownloadItemCallbackCppToC::Get(self)->Resume(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDownloadItemCallbackCppToC::CefDownloadItemCallbackCppToC( + CefDownloadItemCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cancel = download_item_callback_cancel; + struct_.struct_.pause = download_item_callback_pause; + struct_.struct_.resume = download_item_callback_resume; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/download_item_callback_cpptoc.h b/libcef_dll/cpptoc/download_item_callback_cpptoc.h new file mode 100644 index 000000000..4c5a0a064 --- /dev/null +++ b/libcef_dll/cpptoc/download_item_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_ITEM_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_ITEM_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_download_handler.h" +#include "include/capi/cef_download_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefDownloadItemCallbackCppToC + : public CefCppToC { + public: + explicit CefDownloadItemCallbackCppToC(CefDownloadItemCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_ITEM_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/download_item_cpptoc.cc b/libcef_dll/cpptoc/download_item_cpptoc.cc new file mode 100644 index 000000000..d060e81bc --- /dev/null +++ b/libcef_dll/cpptoc/download_item_cpptoc.cc @@ -0,0 +1,300 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/download_item_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK download_item_is_valid(struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDownloadItemCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK download_item_is_in_progress( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDownloadItemCppToC::Get(self)->IsInProgress(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK download_item_is_complete(struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDownloadItemCppToC::Get(self)->IsComplete(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK download_item_is_canceled(struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDownloadItemCppToC::Get(self)->IsCanceled(); + + // Return type: bool + return _retval; +} + +int64 CEF_CALLBACK download_item_get_current_speed( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefDownloadItemCppToC::Get(self)->GetCurrentSpeed(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK download_item_get_percent_complete( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefDownloadItemCppToC::Get(self)->GetPercentComplete(); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK download_item_get_total_bytes( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefDownloadItemCppToC::Get(self)->GetTotalBytes(); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK download_item_get_received_bytes( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefDownloadItemCppToC::Get(self)->GetReceivedBytes(); + + // Return type: simple + return _retval; +} + +cef_time_t CEF_CALLBACK download_item_get_start_time( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CefTime(); + + // Execute + cef_time_t _retval = CefDownloadItemCppToC::Get(self)->GetStartTime(); + + // Return type: simple + return _retval; +} + +cef_time_t CEF_CALLBACK download_item_get_end_time( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CefTime(); + + // Execute + cef_time_t _retval = CefDownloadItemCppToC::Get(self)->GetEndTime(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK download_item_get_full_path( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDownloadItemCppToC::Get(self)->GetFullPath(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +uint32 CEF_CALLBACK download_item_get_id(struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + uint32 _retval = CefDownloadItemCppToC::Get(self)->GetId(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK download_item_get_url( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDownloadItemCppToC::Get(self)->GetURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK download_item_get_original_url( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDownloadItemCppToC::Get(self)->GetOriginalUrl(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK download_item_get_suggested_file_name( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDownloadItemCppToC::Get(self)->GetSuggestedFileName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK download_item_get_content_disposition( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDownloadItemCppToC::Get(self)->GetContentDisposition(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK download_item_get_mime_type( + struct _cef_download_item_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDownloadItemCppToC::Get(self)->GetMimeType(); + + // Return type: string + return _retval.DetachToUserFree(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDownloadItemCppToC::CefDownloadItemCppToC(CefDownloadItem* cls) + : CefCppToC( + cls) { + struct_.struct_.is_valid = download_item_is_valid; + struct_.struct_.is_in_progress = download_item_is_in_progress; + struct_.struct_.is_complete = download_item_is_complete; + struct_.struct_.is_canceled = download_item_is_canceled; + struct_.struct_.get_current_speed = download_item_get_current_speed; + struct_.struct_.get_percent_complete = download_item_get_percent_complete; + struct_.struct_.get_total_bytes = download_item_get_total_bytes; + struct_.struct_.get_received_bytes = download_item_get_received_bytes; + struct_.struct_.get_start_time = download_item_get_start_time; + struct_.struct_.get_end_time = download_item_get_end_time; + struct_.struct_.get_full_path = download_item_get_full_path; + struct_.struct_.get_id = download_item_get_id; + struct_.struct_.get_url = download_item_get_url; + struct_.struct_.get_original_url = download_item_get_original_url; + struct_.struct_.get_suggested_file_name = + download_item_get_suggested_file_name; + struct_.struct_.get_content_disposition = + download_item_get_content_disposition; + struct_.struct_.get_mime_type = download_item_get_mime_type; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/download_item_cpptoc.h b/libcef_dll/cpptoc/download_item_cpptoc.h new file mode 100644 index 000000000..1560928aa --- /dev/null +++ b/libcef_dll/cpptoc/download_item_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_ITEM_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_ITEM_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_download_item.h" +#include "include/capi/cef_download_item_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefDownloadItemCppToC + : public CefCppToC { + public: + explicit CefDownloadItemCppToC(CefDownloadItem* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_ITEM_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/drag_data_cpptoc.cc b/libcef_dll/cpptoc/drag_data_cpptoc.cc new file mode 100644 index 000000000..f53b0f53b --- /dev/null +++ b/libcef_dll/cpptoc/drag_data_cpptoc.cc @@ -0,0 +1,401 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/cpptoc/stream_writer_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_drag_data_t* cef_drag_data_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefDragData::Create(); + + // Return type: refptr_same + return CefDragDataCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +struct _cef_drag_data_t* CEF_CALLBACK drag_data_clone( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDragDataCppToC::Get(self)->Clone(); + + // Return type: refptr_same + return CefDragDataCppToC::Wrap(_retval); +} + +int CEF_CALLBACK drag_data_is_read_only(struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDragDataCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK drag_data_is_link(struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDragDataCppToC::Get(self)->IsLink(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK drag_data_is_fragment(struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDragDataCppToC::Get(self)->IsFragment(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK drag_data_is_file(struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDragDataCppToC::Get(self)->IsFile(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_link_url( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetLinkURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_link_title( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetLinkTitle(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_link_metadata( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetLinkMetadata(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_fragment_text( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetFragmentText(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_fragment_html( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetFragmentHtml(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_fragment_base_url( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetFragmentBaseURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK drag_data_get_file_name( + struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDragDataCppToC::Get(self)->GetFileName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +size_t CEF_CALLBACK drag_data_get_file_contents(struct _cef_drag_data_t* self, + struct _cef_stream_writer_t* writer) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: writer + + // Execute + size_t _retval = CefDragDataCppToC::Get(self)->GetFileContents( + CefStreamWriterCppToC::Unwrap(writer)); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK drag_data_get_file_names(struct _cef_drag_data_t* self, + cef_string_list_t names) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: names; type: string_vec_byref + DCHECK(names); + if (!names) + return 0; + + // Translate param: names; type: string_vec_byref + std::vector namesList; + transfer_string_list_contents(names, namesList); + + // Execute + bool _retval = CefDragDataCppToC::Get(self)->GetFileNames( + namesList); + + // Restore param: names; type: string_vec_byref + cef_string_list_clear(names); + transfer_string_list_contents(namesList, names); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK drag_data_set_link_url(struct _cef_drag_data_t* self, + const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: url + + // Execute + CefDragDataCppToC::Get(self)->SetLinkURL( + CefString(url)); +} + +void CEF_CALLBACK drag_data_set_link_title(struct _cef_drag_data_t* self, + const cef_string_t* title) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: title + + // Execute + CefDragDataCppToC::Get(self)->SetLinkTitle( + CefString(title)); +} + +void CEF_CALLBACK drag_data_set_link_metadata(struct _cef_drag_data_t* self, + const cef_string_t* data) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: data + + // Execute + CefDragDataCppToC::Get(self)->SetLinkMetadata( + CefString(data)); +} + +void CEF_CALLBACK drag_data_set_fragment_text(struct _cef_drag_data_t* self, + const cef_string_t* text) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: text + + // Execute + CefDragDataCppToC::Get(self)->SetFragmentText( + CefString(text)); +} + +void CEF_CALLBACK drag_data_set_fragment_html(struct _cef_drag_data_t* self, + const cef_string_t* html) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: html + + // Execute + CefDragDataCppToC::Get(self)->SetFragmentHtml( + CefString(html)); +} + +void CEF_CALLBACK drag_data_set_fragment_base_url(struct _cef_drag_data_t* self, + const cef_string_t* base_url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: base_url + + // Execute + CefDragDataCppToC::Get(self)->SetFragmentBaseURL( + CefString(base_url)); +} + +void CEF_CALLBACK drag_data_reset_file_contents(struct _cef_drag_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefDragDataCppToC::Get(self)->ResetFileContents(); +} + +void CEF_CALLBACK drag_data_add_file(struct _cef_drag_data_t* self, + const cef_string_t* path, const cef_string_t* display_name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + // Unverified params: display_name + + // Execute + CefDragDataCppToC::Get(self)->AddFile( + CefString(path), + CefString(display_name)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDragDataCppToC::CefDragDataCppToC(CefDragData* cls) + : CefCppToC(cls) { + struct_.struct_.clone = drag_data_clone; + struct_.struct_.is_read_only = drag_data_is_read_only; + struct_.struct_.is_link = drag_data_is_link; + struct_.struct_.is_fragment = drag_data_is_fragment; + struct_.struct_.is_file = drag_data_is_file; + struct_.struct_.get_link_url = drag_data_get_link_url; + struct_.struct_.get_link_title = drag_data_get_link_title; + struct_.struct_.get_link_metadata = drag_data_get_link_metadata; + struct_.struct_.get_fragment_text = drag_data_get_fragment_text; + struct_.struct_.get_fragment_html = drag_data_get_fragment_html; + struct_.struct_.get_fragment_base_url = drag_data_get_fragment_base_url; + struct_.struct_.get_file_name = drag_data_get_file_name; + struct_.struct_.get_file_contents = drag_data_get_file_contents; + struct_.struct_.get_file_names = drag_data_get_file_names; + struct_.struct_.set_link_url = drag_data_set_link_url; + struct_.struct_.set_link_title = drag_data_set_link_title; + struct_.struct_.set_link_metadata = drag_data_set_link_metadata; + struct_.struct_.set_fragment_text = drag_data_set_fragment_text; + struct_.struct_.set_fragment_html = drag_data_set_fragment_html; + struct_.struct_.set_fragment_base_url = drag_data_set_fragment_base_url; + struct_.struct_.reset_file_contents = drag_data_reset_file_contents; + struct_.struct_.add_file = drag_data_add_file; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/drag_data_cpptoc.h b/libcef_dll/cpptoc/drag_data_cpptoc.h new file mode 100644 index 000000000..2bc9b84e9 --- /dev/null +++ b/libcef_dll/cpptoc/drag_data_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DRAG_DATA_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DRAG_DATA_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_drag_data.h" +#include "include/capi/cef_drag_data_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefDragDataCppToC + : public CefCppToC { + public: + explicit CefDragDataCppToC(CefDragData* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DRAG_DATA_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/drag_handler_cpptoc.cc b/libcef_dll/cpptoc/drag_handler_cpptoc.cc new file mode 100644 index 000000000..bd217f0d7 --- /dev/null +++ b/libcef_dll/cpptoc/drag_handler_cpptoc.cc @@ -0,0 +1,59 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/drag_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/drag_data_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK drag_handler_on_drag_enter(struct _cef_drag_handler_t* self, + cef_browser_t* browser, cef_drag_data_t* dragData, + cef_drag_operations_mask_t mask) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: dragData; type: refptr_diff + DCHECK(dragData); + if (!dragData) + return 0; + + // Execute + bool _retval = CefDragHandlerCppToC::Get(self)->OnDragEnter( + CefBrowserCToCpp::Wrap(browser), + CefDragDataCToCpp::Wrap(dragData), + mask); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDragHandlerCppToC::CefDragHandlerCppToC(CefDragHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_drag_enter = drag_handler_on_drag_enter; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/drag_handler_cpptoc.h b/libcef_dll/cpptoc/drag_handler_cpptoc.h new file mode 100644 index 000000000..9af149902 --- /dev/null +++ b/libcef_dll/cpptoc/drag_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_DRAG_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DRAG_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_drag_handler.h" +#include "include/capi/cef_drag_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefDragHandlerCppToC + : public CefCppToC { + public: + explicit CefDragHandlerCppToC(CefDragHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DRAG_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/end_tracing_callback_cpptoc.cc b/libcef_dll/cpptoc/end_tracing_callback_cpptoc.cc new file mode 100644 index 000000000..a4379a7ee --- /dev/null +++ b/libcef_dll/cpptoc/end_tracing_callback_cpptoc.cc @@ -0,0 +1,51 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/end_tracing_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK end_tracing_callback_on_end_tracing_complete( + struct _cef_end_tracing_callback_t* self, + const cef_string_t* tracing_file) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: tracing_file; type: string_byref_const + DCHECK(tracing_file); + if (!tracing_file) + return; + + // Execute + CefEndTracingCallbackCppToC::Get(self)->OnEndTracingComplete( + CefString(tracing_file)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefEndTracingCallbackCppToC::CefEndTracingCallbackCppToC( + CefEndTracingCallback* cls) + : CefCppToC(cls) { + struct_.struct_.on_end_tracing_complete = + end_tracing_callback_on_end_tracing_complete; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/end_tracing_callback_cpptoc.h b/libcef_dll/cpptoc/end_tracing_callback_cpptoc.h new file mode 100644 index 000000000..b05e16d9c --- /dev/null +++ b/libcef_dll/cpptoc/end_tracing_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_END_TRACING_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_END_TRACING_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_trace.h" +#include "include/capi/cef_trace_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefEndTracingCallbackCppToC + : public CefCppToC { + public: + explicit CefEndTracingCallbackCppToC(CefEndTracingCallback* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_END_TRACING_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/file_dialog_callback_cpptoc.cc b/libcef_dll/cpptoc/file_dialog_callback_cpptoc.cc new file mode 100644 index 000000000..40f7b1562 --- /dev/null +++ b/libcef_dll/cpptoc/file_dialog_callback_cpptoc.cc @@ -0,0 +1,70 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/file_dialog_callback_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK file_dialog_callback_cont( + struct _cef_file_dialog_callback_t* self, int selected_accept_filter, + cef_string_list_t file_paths) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return; + // Unverified params: file_paths + + // Translate param: file_paths; type: string_vec_byref_const + std::vector file_pathsList; + transfer_string_list_contents(file_paths, file_pathsList); + + // Execute + CefFileDialogCallbackCppToC::Get(self)->Continue( + selected_accept_filter, + file_pathsList); +} + +void CEF_CALLBACK file_dialog_callback_cancel( + struct _cef_file_dialog_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFileDialogCallbackCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefFileDialogCallbackCppToC::CefFileDialogCallbackCppToC( + CefFileDialogCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = file_dialog_callback_cont; + struct_.struct_.cancel = file_dialog_callback_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/file_dialog_callback_cpptoc.h b/libcef_dll/cpptoc/file_dialog_callback_cpptoc.h new file mode 100644 index 000000000..2883a501d --- /dev/null +++ b/libcef_dll/cpptoc/file_dialog_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_FILE_DIALOG_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_FILE_DIALOG_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_dialog_handler.h" +#include "include/capi/cef_dialog_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefFileDialogCallbackCppToC + : public CefCppToC { + public: + explicit CefFileDialogCallbackCppToC(CefFileDialogCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FILE_DIALOG_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/find_handler_cpptoc.cc b/libcef_dll/cpptoc/find_handler_cpptoc.cc new file mode 100644 index 000000000..1645c8b47 --- /dev/null +++ b/libcef_dll/cpptoc/find_handler_cpptoc.cc @@ -0,0 +1,62 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/find_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK find_handler_on_find_result(struct _cef_find_handler_t* self, + cef_browser_t* browser, int identifier, int count, + const cef_rect_t* selectionRect, int activeMatchOrdinal, + int finalUpdate) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: selectionRect; type: simple_byref_const + DCHECK(selectionRect); + if (!selectionRect) + return; + + // Translate param: selectionRect; type: simple_byref_const + CefRect selectionRectVal = selectionRect?*selectionRect:CefRect(); + + // Execute + CefFindHandlerCppToC::Get(self)->OnFindResult( + CefBrowserCToCpp::Wrap(browser), + identifier, + count, + selectionRectVal, + activeMatchOrdinal, + finalUpdate?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefFindHandlerCppToC::CefFindHandlerCppToC(CefFindHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_find_result = find_handler_on_find_result; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/find_handler_cpptoc.h b/libcef_dll/cpptoc/find_handler_cpptoc.h new file mode 100644 index 000000000..aff1edc46 --- /dev/null +++ b/libcef_dll/cpptoc/find_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_FIND_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_FIND_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_find_handler.h" +#include "include/capi/cef_find_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefFindHandlerCppToC + : public CefCppToC { + public: + explicit CefFindHandlerCppToC(CefFindHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FIND_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/focus_handler_cpptoc.cc b/libcef_dll/cpptoc/focus_handler_cpptoc.cc new file mode 100644 index 000000000..fa5cfb88b --- /dev/null +++ b/libcef_dll/cpptoc/focus_handler_cpptoc.cc @@ -0,0 +1,90 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/focus_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK focus_handler_on_take_focus(struct _cef_focus_handler_t* self, + cef_browser_t* browser, int next) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefFocusHandlerCppToC::Get(self)->OnTakeFocus( + CefBrowserCToCpp::Wrap(browser), + next?true:false); +} + +int CEF_CALLBACK focus_handler_on_set_focus(struct _cef_focus_handler_t* self, + cef_browser_t* browser, cef_focus_source_t source) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + + // Execute + bool _retval = CefFocusHandlerCppToC::Get(self)->OnSetFocus( + CefBrowserCToCpp::Wrap(browser), + source); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK focus_handler_on_got_focus(struct _cef_focus_handler_t* self, + cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefFocusHandlerCppToC::Get(self)->OnGotFocus( + CefBrowserCToCpp::Wrap(browser)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefFocusHandlerCppToC::CefFocusHandlerCppToC(CefFocusHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.on_take_focus = focus_handler_on_take_focus; + struct_.struct_.on_set_focus = focus_handler_on_set_focus; + struct_.struct_.on_got_focus = focus_handler_on_got_focus; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/focus_handler_cpptoc.h b/libcef_dll/cpptoc/focus_handler_cpptoc.h new file mode 100644 index 000000000..e0c98564e --- /dev/null +++ b/libcef_dll/cpptoc/focus_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_FOCUS_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_FOCUS_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_focus_handler.h" +#include "include/capi/cef_focus_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefFocusHandlerCppToC + : public CefCppToC { + public: + explicit CefFocusHandlerCppToC(CefFocusHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FOCUS_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/frame_cpptoc.cc b/libcef_dll/cpptoc/frame_cpptoc.cc new file mode 100644 index 000000000..9b9d54a13 --- /dev/null +++ b/libcef_dll/cpptoc/frame_cpptoc.cc @@ -0,0 +1,401 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/ctocpp/domvisitor_ctocpp.h" +#include "libcef_dll/ctocpp/string_visitor_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK frame_is_valid(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefFrameCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK frame_undo(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Undo(); +} + +void CEF_CALLBACK frame_redo(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Redo(); +} + +void CEF_CALLBACK frame_cut(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Cut(); +} + +void CEF_CALLBACK frame_copy(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Copy(); +} + +void CEF_CALLBACK frame_paste(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Paste(); +} + +void CEF_CALLBACK frame_del(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Delete(); +} + +void CEF_CALLBACK frame_select_all(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->SelectAll(); +} + +void CEF_CALLBACK frame_view_source(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->ViewSource(); +} + +void CEF_CALLBACK frame_get_source(struct _cef_frame_t* self, + struct _cef_string_visitor_t* visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return; + + // Execute + CefFrameCppToC::Get(self)->GetSource( + CefStringVisitorCToCpp::Wrap(visitor)); +} + +void CEF_CALLBACK frame_get_text(struct _cef_frame_t* self, + struct _cef_string_visitor_t* visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return; + + // Execute + CefFrameCppToC::Get(self)->GetText( + CefStringVisitorCToCpp::Wrap(visitor)); +} + +void CEF_CALLBACK frame_load_request(struct _cef_frame_t* self, + struct _cef_request_t* request) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: request; type: refptr_same + DCHECK(request); + if (!request) + return; + + // Execute + CefFrameCppToC::Get(self)->LoadRequest( + CefRequestCppToC::Unwrap(request)); +} + +void CEF_CALLBACK frame_load_url(struct _cef_frame_t* self, + const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefFrameCppToC::Get(self)->LoadURL( + CefString(url)); +} + +void CEF_CALLBACK frame_load_string(struct _cef_frame_t* self, + const cef_string_t* string_val, const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: string_val; type: string_byref_const + DCHECK(string_val); + if (!string_val) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefFrameCppToC::Get(self)->LoadString( + CefString(string_val), + CefString(url)); +} + +void CEF_CALLBACK frame_execute_java_script(struct _cef_frame_t* self, + const cef_string_t* code, const cef_string_t* script_url, + int start_line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: code; type: string_byref_const + DCHECK(code); + if (!code) + return; + // Unverified params: script_url + + // Execute + CefFrameCppToC::Get(self)->ExecuteJavaScript( + CefString(code), + CefString(script_url), + start_line); +} + +int CEF_CALLBACK frame_is_main(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefFrameCppToC::Get(self)->IsMain(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK frame_is_focused(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefFrameCppToC::Get(self)->IsFocused(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK frame_get_name(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefFrameCppToC::Get(self)->GetName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int64 CEF_CALLBACK frame_get_identifier(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefFrameCppToC::Get(self)->GetIdentifier(); + + // Return type: simple + return _retval; +} + +struct _cef_frame_t* CEF_CALLBACK frame_get_parent(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefFrameCppToC::Get(self)->GetParent(); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +cef_string_userfree_t CEF_CALLBACK frame_get_url(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefFrameCppToC::Get(self)->GetURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_browser_t* CEF_CALLBACK frame_get_browser(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefFrameCppToC::Get(self)->GetBrowser(); + + // Return type: refptr_same + return CefBrowserCppToC::Wrap(_retval); +} + +struct _cef_v8context_t* CEF_CALLBACK frame_get_v8context( + struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefFrameCppToC::Get(self)->GetV8Context(); + + // Return type: refptr_same + return CefV8ContextCppToC::Wrap(_retval); +} + +void CEF_CALLBACK frame_visit_dom(struct _cef_frame_t* self, + cef_domvisitor_t* visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return; + + // Execute + CefFrameCppToC::Get(self)->VisitDOM( + CefDOMVisitorCToCpp::Wrap(visitor)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefFrameCppToC::CefFrameCppToC(CefFrame* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = frame_is_valid; + struct_.struct_.undo = frame_undo; + struct_.struct_.redo = frame_redo; + struct_.struct_.cut = frame_cut; + struct_.struct_.copy = frame_copy; + struct_.struct_.paste = frame_paste; + struct_.struct_.del = frame_del; + struct_.struct_.select_all = frame_select_all; + struct_.struct_.view_source = frame_view_source; + struct_.struct_.get_source = frame_get_source; + struct_.struct_.get_text = frame_get_text; + struct_.struct_.load_request = frame_load_request; + struct_.struct_.load_url = frame_load_url; + struct_.struct_.load_string = frame_load_string; + struct_.struct_.execute_java_script = frame_execute_java_script; + struct_.struct_.is_main = frame_is_main; + struct_.struct_.is_focused = frame_is_focused; + struct_.struct_.get_name = frame_get_name; + struct_.struct_.get_identifier = frame_get_identifier; + struct_.struct_.get_parent = frame_get_parent; + struct_.struct_.get_url = frame_get_url; + struct_.struct_.get_browser = frame_get_browser; + struct_.struct_.get_v8context = frame_get_v8context; + struct_.struct_.visit_dom = frame_visit_dom; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/frame_cpptoc.h b/libcef_dll/cpptoc/frame_cpptoc.h new file mode 100644 index 000000000..d6821297d --- /dev/null +++ b/libcef_dll/cpptoc/frame_cpptoc.h @@ -0,0 +1,39 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_FRAME_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_FRAME_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_frame.h" +#include "include/capi/cef_frame_capi.h" +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefFrameCppToC + : public CefCppToC { + public: + explicit CefFrameCppToC(CefFrame* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FRAME_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/geolocation_callback_cpptoc.cc b/libcef_dll/cpptoc/geolocation_callback_cpptoc.cc new file mode 100644 index 000000000..5865e8754 --- /dev/null +++ b/libcef_dll/cpptoc/geolocation_callback_cpptoc.cc @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/geolocation_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK geolocation_callback_cont( + struct _cef_geolocation_callback_t* self, int allow) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefGeolocationCallbackCppToC::Get(self)->Continue( + allow?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefGeolocationCallbackCppToC::CefGeolocationCallbackCppToC( + CefGeolocationCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = geolocation_callback_cont; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/geolocation_callback_cpptoc.h b/libcef_dll/cpptoc/geolocation_callback_cpptoc.h new file mode 100644 index 000000000..251b2a1c2 --- /dev/null +++ b/libcef_dll/cpptoc/geolocation_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_GEOLOCATION_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_GEOLOCATION_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_geolocation_handler.h" +#include "include/capi/cef_geolocation_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefGeolocationCallbackCppToC + : public CefCppToC { + public: + explicit CefGeolocationCallbackCppToC(CefGeolocationCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_GEOLOCATION_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/geolocation_handler_cpptoc.cc b/libcef_dll/cpptoc/geolocation_handler_cpptoc.cc new file mode 100644 index 000000000..3116df65a --- /dev/null +++ b/libcef_dll/cpptoc/geolocation_handler_cpptoc.cc @@ -0,0 +1,95 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/geolocation_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/geolocation_callback_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK geolocation_handler_on_request_geolocation_permission( + struct _cef_geolocation_handler_t* self, cef_browser_t* browser, + const cef_string_t* requesting_url, int request_id, + cef_geolocation_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: requesting_url; type: string_byref_const + DCHECK(requesting_url); + if (!requesting_url) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefGeolocationHandlerCppToC::Get( + self)->OnRequestGeolocationPermission( + CefBrowserCToCpp::Wrap(browser), + CefString(requesting_url), + request_id, + CefGeolocationCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK geolocation_handler_on_cancel_geolocation_permission( + struct _cef_geolocation_handler_t* self, cef_browser_t* browser, + const cef_string_t* requesting_url, int request_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: requesting_url; type: string_byref_const + DCHECK(requesting_url); + if (!requesting_url) + return; + + // Execute + CefGeolocationHandlerCppToC::Get(self)->OnCancelGeolocationPermission( + CefBrowserCToCpp::Wrap(browser), + CefString(requesting_url), + request_id); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefGeolocationHandlerCppToC::CefGeolocationHandlerCppToC( + CefGeolocationHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_request_geolocation_permission = + geolocation_handler_on_request_geolocation_permission; + struct_.struct_.on_cancel_geolocation_permission = + geolocation_handler_on_cancel_geolocation_permission; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/geolocation_handler_cpptoc.h b/libcef_dll/cpptoc/geolocation_handler_cpptoc.h new file mode 100644 index 000000000..21fc13281 --- /dev/null +++ b/libcef_dll/cpptoc/geolocation_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_GEOLOCATION_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_GEOLOCATION_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_geolocation_handler.h" +#include "include/capi/cef_geolocation_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefGeolocationHandlerCppToC + : public CefCppToC { + public: + explicit CefGeolocationHandlerCppToC(CefGeolocationHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_GEOLOCATION_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/get_geolocation_callback_cpptoc.cc b/libcef_dll/cpptoc/get_geolocation_callback_cpptoc.cc new file mode 100644 index 000000000..bb4a265d5 --- /dev/null +++ b/libcef_dll/cpptoc/get_geolocation_callback_cpptoc.cc @@ -0,0 +1,57 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/get_geolocation_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK get_geolocation_callback_on_location_update( + struct _cef_get_geolocation_callback_t* self, + const struct _cef_geoposition_t* position) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: position; type: struct_byref_const + DCHECK(position); + if (!position) + return; + + // Translate param: position; type: struct_byref_const + CefGeoposition positionObj; + if (position) + positionObj.Set(*position, false); + + // Execute + CefGetGeolocationCallbackCppToC::Get(self)->OnLocationUpdate( + positionObj); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefGetGeolocationCallbackCppToC::CefGetGeolocationCallbackCppToC( + CefGetGeolocationCallback* cls) + : CefCppToC(cls) { + struct_.struct_.on_location_update = + get_geolocation_callback_on_location_update; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/cpptoc/get_geolocation_callback_cpptoc.h b/libcef_dll/cpptoc/get_geolocation_callback_cpptoc.h new file mode 100644 index 000000000..72c2264d3 --- /dev/null +++ b/libcef_dll/cpptoc/get_geolocation_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_GET_GEOLOCATION_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_GET_GEOLOCATION_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_geolocation.h" +#include "include/capi/cef_geolocation_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefGetGeolocationCallbackCppToC + : public CefCppToC { + public: + explicit CefGetGeolocationCallbackCppToC(CefGetGeolocationCallback* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_GET_GEOLOCATION_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/jsdialog_callback_cpptoc.cc b/libcef_dll/cpptoc/jsdialog_callback_cpptoc.cc new file mode 100644 index 000000000..5a53232f1 --- /dev/null +++ b/libcef_dll/cpptoc/jsdialog_callback_cpptoc.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/jsdialog_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK jsdialog_callback_cont(struct _cef_jsdialog_callback_t* self, + int success, const cef_string_t* user_input) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: user_input + + // Execute + CefJSDialogCallbackCppToC::Get(self)->Continue( + success?true:false, + CefString(user_input)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefJSDialogCallbackCppToC::CefJSDialogCallbackCppToC(CefJSDialogCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = jsdialog_callback_cont; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/jsdialog_callback_cpptoc.h b/libcef_dll/cpptoc/jsdialog_callback_cpptoc.h new file mode 100644 index 000000000..0528e59e8 --- /dev/null +++ b/libcef_dll/cpptoc/jsdialog_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_jsdialog_handler.h" +#include "include/capi/cef_jsdialog_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefJSDialogCallbackCppToC + : public CefCppToC { + public: + explicit CefJSDialogCallbackCppToC(CefJSDialogCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc b/libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc new file mode 100644 index 000000000..ff8b523c6 --- /dev/null +++ b/libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc @@ -0,0 +1,151 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/jsdialog_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/jsdialog_callback_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK jsdialog_handler_on_jsdialog( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser, + const cef_string_t* origin_url, const cef_string_t* accept_lang, + cef_jsdialog_type_t dialog_type, const cef_string_t* message_text, + const cef_string_t* default_prompt_text, cef_jsdialog_callback_t* callback, + int* suppress_message) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + // Verify param: suppress_message; type: bool_byref + DCHECK(suppress_message); + if (!suppress_message) + return 0; + // Unverified params: origin_url, accept_lang, message_text, + // default_prompt_text + + // Translate param: suppress_message; type: bool_byref + bool suppress_messageBool = ( + suppress_message && *suppress_message)?true:false; + + // Execute + bool _retval = CefJSDialogHandlerCppToC::Get(self)->OnJSDialog( + CefBrowserCToCpp::Wrap(browser), + CefString(origin_url), + CefString(accept_lang), + dialog_type, + CefString(message_text), + CefString(default_prompt_text), + CefJSDialogCallbackCToCpp::Wrap(callback), + suppress_messageBool); + + // Restore param: suppress_message; type: bool_byref + if (suppress_message) + *suppress_message = suppress_messageBool?true:false; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK jsdialog_handler_on_before_unload_dialog( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser, + const cef_string_t* message_text, int is_reload, + cef_jsdialog_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + // Unverified params: message_text + + // Execute + bool _retval = CefJSDialogHandlerCppToC::Get(self)->OnBeforeUnloadDialog( + CefBrowserCToCpp::Wrap(browser), + CefString(message_text), + is_reload?true:false, + CefJSDialogCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK jsdialog_handler_on_reset_dialog_state( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefJSDialogHandlerCppToC::Get(self)->OnResetDialogState( + CefBrowserCToCpp::Wrap(browser)); +} + +void CEF_CALLBACK jsdialog_handler_on_dialog_closed( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefJSDialogHandlerCppToC::Get(self)->OnDialogClosed( + CefBrowserCToCpp::Wrap(browser)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefJSDialogHandlerCppToC::CefJSDialogHandlerCppToC(CefJSDialogHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_jsdialog = jsdialog_handler_on_jsdialog; + struct_.struct_.on_before_unload_dialog = + jsdialog_handler_on_before_unload_dialog; + struct_.struct_.on_reset_dialog_state = + jsdialog_handler_on_reset_dialog_state; + struct_.struct_.on_dialog_closed = jsdialog_handler_on_dialog_closed; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/jsdialog_handler_cpptoc.h b/libcef_dll/cpptoc/jsdialog_handler_cpptoc.h new file mode 100644 index 000000000..f4dae2033 --- /dev/null +++ b/libcef_dll/cpptoc/jsdialog_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_jsdialog_handler.h" +#include "include/capi/cef_jsdialog_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefJSDialogHandlerCppToC + : public CefCppToC { + public: + explicit CefJSDialogHandlerCppToC(CefJSDialogHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/keyboard_handler_cpptoc.cc b/libcef_dll/cpptoc/keyboard_handler_cpptoc.cc new file mode 100644 index 000000000..9b4e07f30 --- /dev/null +++ b/libcef_dll/cpptoc/keyboard_handler_cpptoc.cc @@ -0,0 +1,110 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/keyboard_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK keyboard_handler_on_pre_key_event( + struct _cef_keyboard_handler_t* self, cef_browser_t* browser, + const struct _cef_key_event_t* event, cef_event_handle_t os_event, + int* is_keyboard_shortcut) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return 0; + // Verify param: is_keyboard_shortcut; type: bool_byaddr + DCHECK(is_keyboard_shortcut); + if (!is_keyboard_shortcut) + return 0; + + // Translate param: event; type: struct_byref_const + CefKeyEvent eventObj; + if (event) + eventObj.Set(*event, false); + // Translate param: is_keyboard_shortcut; type: bool_byaddr + bool is_keyboard_shortcutBool = ( + is_keyboard_shortcut && *is_keyboard_shortcut)?true:false; + + // Execute + bool _retval = CefKeyboardHandlerCppToC::Get(self)->OnPreKeyEvent( + CefBrowserCToCpp::Wrap(browser), + eventObj, + os_event, + &is_keyboard_shortcutBool); + + // Restore param: is_keyboard_shortcut; type: bool_byaddr + if (is_keyboard_shortcut) + *is_keyboard_shortcut = is_keyboard_shortcutBool?true:false; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK keyboard_handler_on_key_event( + struct _cef_keyboard_handler_t* self, cef_browser_t* browser, + const struct _cef_key_event_t* event, cef_event_handle_t os_event) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: event; type: struct_byref_const + DCHECK(event); + if (!event) + return 0; + + // Translate param: event; type: struct_byref_const + CefKeyEvent eventObj; + if (event) + eventObj.Set(*event, false); + + // Execute + bool _retval = CefKeyboardHandlerCppToC::Get(self)->OnKeyEvent( + CefBrowserCToCpp::Wrap(browser), + eventObj, + os_event); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefKeyboardHandlerCppToC::CefKeyboardHandlerCppToC(CefKeyboardHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_pre_key_event = keyboard_handler_on_pre_key_event; + struct_.struct_.on_key_event = keyboard_handler_on_key_event; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/keyboard_handler_cpptoc.h b/libcef_dll/cpptoc/keyboard_handler_cpptoc.h new file mode 100644 index 000000000..1ead2dd56 --- /dev/null +++ b/libcef_dll/cpptoc/keyboard_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_KEYBOARD_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_KEYBOARD_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_keyboard_handler.h" +#include "include/capi/cef_keyboard_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefKeyboardHandlerCppToC + : public CefCppToC { + public: + explicit CefKeyboardHandlerCppToC(CefKeyboardHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_KEYBOARD_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/life_span_handler_cpptoc.cc b/libcef_dll/cpptoc/life_span_handler_cpptoc.cc new file mode 100644 index 000000000..343b4400d --- /dev/null +++ b/libcef_dll/cpptoc/life_span_handler_cpptoc.cc @@ -0,0 +1,211 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/client_cpptoc.h" +#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK life_span_handler_on_before_popup( + struct _cef_life_span_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_t* target_url, + const cef_string_t* target_frame_name, + const struct _cef_popup_features_t* popupFeatures, + cef_window_info_t* windowInfo, cef_client_t** client, + struct _cef_browser_settings_t* settings, int* no_javascript_access) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: popupFeatures; type: struct_byref_const + DCHECK(popupFeatures); + if (!popupFeatures) + return 0; + // Verify param: windowInfo; type: struct_byref + DCHECK(windowInfo); + if (!windowInfo) + return 0; + // Verify param: client; type: refptr_same_byref + DCHECK(client); + if (!client) + return 0; + // Verify param: settings; type: struct_byref + DCHECK(settings); + if (!settings) + return 0; + // Verify param: no_javascript_access; type: bool_byaddr + DCHECK(no_javascript_access); + if (!no_javascript_access) + return 0; + // Unverified params: target_url, target_frame_name + + // Translate param: popupFeatures; type: struct_byref_const + CefPopupFeatures popupFeaturesObj; + if (popupFeatures) + popupFeaturesObj.Set(*popupFeatures, false); + // Translate param: windowInfo; type: struct_byref + CefWindowInfo windowInfoObj; + if (windowInfo) + windowInfoObj.AttachTo(*windowInfo); + // Translate param: client; type: refptr_same_byref + CefRefPtr clientPtr; + if (client && *client) + clientPtr = CefClientCppToC::Unwrap(*client); + CefClient* clientOrig = clientPtr.get(); + // Translate param: settings; type: struct_byref + CefBrowserSettings settingsObj; + if (settings) + settingsObj.AttachTo(*settings); + // Translate param: no_javascript_access; type: bool_byaddr + bool no_javascript_accessBool = ( + no_javascript_access && *no_javascript_access)?true:false; + + // Execute + bool _retval = CefLifeSpanHandlerCppToC::Get(self)->OnBeforePopup( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(target_url), + CefString(target_frame_name), + popupFeaturesObj, + windowInfoObj, + clientPtr, + settingsObj, + &no_javascript_accessBool); + + // Restore param: windowInfo; type: struct_byref + if (windowInfo) + windowInfoObj.DetachTo(*windowInfo); + // Restore param: client; type: refptr_same_byref + if (client) { + if (clientPtr.get()) { + if (clientPtr.get() != clientOrig) { + *client = CefClientCppToC::Wrap(clientPtr); + } + } else { + *client = NULL; + } + } + // Restore param: settings; type: struct_byref + if (settings) + settingsObj.DetachTo(*settings); + // Restore param: no_javascript_access; type: bool_byaddr + if (no_javascript_access) + *no_javascript_access = no_javascript_accessBool?true:false; + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK life_span_handler_on_after_created( + struct _cef_life_span_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefLifeSpanHandlerCppToC::Get(self)->OnAfterCreated( + CefBrowserCToCpp::Wrap(browser)); +} + +int CEF_CALLBACK life_span_handler_run_modal( + struct _cef_life_span_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + + // Execute + bool _retval = CefLifeSpanHandlerCppToC::Get(self)->RunModal( + CefBrowserCToCpp::Wrap(browser)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK life_span_handler_do_close( + struct _cef_life_span_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + + // Execute + bool _retval = CefLifeSpanHandlerCppToC::Get(self)->DoClose( + CefBrowserCToCpp::Wrap(browser)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK life_span_handler_on_before_close( + struct _cef_life_span_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefLifeSpanHandlerCppToC::Get(self)->OnBeforeClose( + CefBrowserCToCpp::Wrap(browser)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefLifeSpanHandlerCppToC::CefLifeSpanHandlerCppToC(CefLifeSpanHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_popup = life_span_handler_on_before_popup; + struct_.struct_.on_after_created = life_span_handler_on_after_created; + struct_.struct_.run_modal = life_span_handler_run_modal; + struct_.struct_.do_close = life_span_handler_do_close; + struct_.struct_.on_before_close = life_span_handler_on_before_close; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/life_span_handler_cpptoc.h b/libcef_dll/cpptoc/life_span_handler_cpptoc.h new file mode 100644 index 000000000..7c37562d6 --- /dev/null +++ b/libcef_dll/cpptoc/life_span_handler_cpptoc.h @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_LIFE_SPAN_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_LIFE_SPAN_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_life_span_handler.h" +#include "include/capi/cef_life_span_handler_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefLifeSpanHandlerCppToC + : public CefCppToC { + public: + explicit CefLifeSpanHandlerCppToC(CefLifeSpanHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_LIFE_SPAN_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/list_value_cpptoc.cc b/libcef_dll/cpptoc/list_value_cpptoc.cc new file mode 100644 index 000000000..bd0c4f985 --- /dev/null +++ b/libcef_dll/cpptoc/list_value_cpptoc.cc @@ -0,0 +1,528 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/binary_value_cpptoc.h" +#include "libcef_dll/cpptoc/dictionary_value_cpptoc.h" +#include "libcef_dll/cpptoc/list_value_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_list_value_t* cef_list_value_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefListValue::Create(); + + // Return type: refptr_same + return CefListValueCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK list_value_is_valid(struct _cef_list_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_is_owned(struct _cef_list_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->IsOwned(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_is_read_only(struct _cef_list_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +struct _cef_list_value_t* CEF_CALLBACK list_value_copy( + struct _cef_list_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefListValueCppToC::Get(self)->Copy(); + + // Return type: refptr_same + return CefListValueCppToC::Wrap(_retval); +} + +int CEF_CALLBACK list_value_set_size(struct _cef_list_value_t* self, + size_t size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetSize( + size); + + // Return type: bool + return _retval; +} + +size_t CEF_CALLBACK list_value_get_size(struct _cef_list_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefListValueCppToC::Get(self)->GetSize(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK list_value_clear(struct _cef_list_value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->Clear(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_remove(struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->Remove( + index); + + // Return type: bool + return _retval; +} + +cef_value_type_t CEF_CALLBACK list_value_get_type( + struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return VTYPE_INVALID; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return VTYPE_INVALID; + + // Execute + cef_value_type_t _retval = CefListValueCppToC::Get(self)->GetType( + index); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK list_value_get_bool(struct _cef_list_value_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->GetBool( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_get_int(struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + int _retval = CefListValueCppToC::Get(self)->GetInt( + index); + + // Return type: simple + return _retval; +} + +double CEF_CALLBACK list_value_get_double(struct _cef_list_value_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + double _retval = CefListValueCppToC::Get(self)->GetDouble( + index); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK list_value_get_string( + struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + CefString _retval = CefListValueCppToC::Get(self)->GetString( + index); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_binary_value_t* CEF_CALLBACK list_value_get_binary( + struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + CefRefPtr _retval = CefListValueCppToC::Get(self)->GetBinary( + index); + + // Return type: refptr_same + return CefBinaryValueCppToC::Wrap(_retval); +} + +cef_dictionary_value_t* CEF_CALLBACK list_value_get_dictionary( + struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + CefRefPtr _retval = CefListValueCppToC::Get( + self)->GetDictionary( + index); + + // Return type: refptr_same + return CefDictionaryValueCppToC::Wrap(_retval); +} + +struct _cef_list_value_t* CEF_CALLBACK list_value_get_list( + struct _cef_list_value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + CefRefPtr _retval = CefListValueCppToC::Get(self)->GetList( + index); + + // Return type: refptr_same + return CefListValueCppToC::Wrap(_retval); +} + +int CEF_CALLBACK list_value_set_null(struct _cef_list_value_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetNull( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_bool(struct _cef_list_value_t* self, int index, + int value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetBool( + index, + value?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_int(struct _cef_list_value_t* self, int index, + int value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetInt( + index, + value); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_double(struct _cef_list_value_t* self, + int index, double value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetDouble( + index, + value); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_string(struct _cef_list_value_t* self, + int index, const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + // Unverified params: value + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetString( + index, + CefString(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_binary(struct _cef_list_value_t* self, + int index, cef_binary_value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetBinary( + index, + CefBinaryValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_dictionary(struct _cef_list_value_t* self, + int index, cef_dictionary_value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetDictionary( + index, + CefDictionaryValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK list_value_set_list(struct _cef_list_value_t* self, int index, + struct _cef_list_value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefListValueCppToC::Get(self)->SetList( + index, + CefListValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefListValueCppToC::CefListValueCppToC(CefListValue* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = list_value_is_valid; + struct_.struct_.is_owned = list_value_is_owned; + struct_.struct_.is_read_only = list_value_is_read_only; + struct_.struct_.copy = list_value_copy; + struct_.struct_.set_size = list_value_set_size; + struct_.struct_.get_size = list_value_get_size; + struct_.struct_.clear = list_value_clear; + struct_.struct_.remove = list_value_remove; + struct_.struct_.get_type = list_value_get_type; + struct_.struct_.get_bool = list_value_get_bool; + struct_.struct_.get_int = list_value_get_int; + struct_.struct_.get_double = list_value_get_double; + struct_.struct_.get_string = list_value_get_string; + struct_.struct_.get_binary = list_value_get_binary; + struct_.struct_.get_dictionary = list_value_get_dictionary; + struct_.struct_.get_list = list_value_get_list; + struct_.struct_.set_null = list_value_set_null; + struct_.struct_.set_bool = list_value_set_bool; + struct_.struct_.set_int = list_value_set_int; + struct_.struct_.set_double = list_value_set_double; + struct_.struct_.set_string = list_value_set_string; + struct_.struct_.set_binary = list_value_set_binary; + struct_.struct_.set_dictionary = list_value_set_dictionary; + struct_.struct_.set_list = list_value_set_list; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/list_value_cpptoc.h b/libcef_dll/cpptoc/list_value_cpptoc.h new file mode 100644 index 000000000..a6dd5705f --- /dev/null +++ b/libcef_dll/cpptoc/list_value_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_LIST_VALUE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_LIST_VALUE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_values.h" +#include "include/capi/cef_values_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefListValueCppToC + : public CefCppToC { + public: + explicit CefListValueCppToC(CefListValue* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_LIST_VALUE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/load_handler_cpptoc.cc b/libcef_dll/cpptoc/load_handler_cpptoc.cc new file mode 100644 index 000000000..791cd19e1 --- /dev/null +++ b/libcef_dll/cpptoc/load_handler_cpptoc.cc @@ -0,0 +1,133 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/load_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK load_handler_on_loading_state_change( + struct _cef_load_handler_t* self, cef_browser_t* browser, int isLoading, + int canGoBack, int canGoForward) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefLoadHandlerCppToC::Get(self)->OnLoadingStateChange( + CefBrowserCToCpp::Wrap(browser), + isLoading?true:false, + canGoBack?true:false, + canGoForward?true:false); +} + +void CEF_CALLBACK load_handler_on_load_start(struct _cef_load_handler_t* self, + cef_browser_t* browser, cef_frame_t* frame) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + + // Execute + CefLoadHandlerCppToC::Get(self)->OnLoadStart( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame)); +} + +void CEF_CALLBACK load_handler_on_load_end(struct _cef_load_handler_t* self, + cef_browser_t* browser, cef_frame_t* frame, int httpStatusCode) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + + // Execute + CefLoadHandlerCppToC::Get(self)->OnLoadEnd( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + httpStatusCode); +} + +void CEF_CALLBACK load_handler_on_load_error(struct _cef_load_handler_t* self, + cef_browser_t* browser, cef_frame_t* frame, cef_errorcode_t errorCode, + const cef_string_t* errorText, const cef_string_t* failedUrl) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: failedUrl; type: string_byref_const + DCHECK(failedUrl); + if (!failedUrl) + return; + // Unverified params: errorText + + // Execute + CefLoadHandlerCppToC::Get(self)->OnLoadError( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + errorCode, + CefString(errorText), + CefString(failedUrl)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefLoadHandlerCppToC::CefLoadHandlerCppToC(CefLoadHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_loading_state_change = + load_handler_on_loading_state_change; + struct_.struct_.on_load_start = load_handler_on_load_start; + struct_.struct_.on_load_end = load_handler_on_load_end; + struct_.struct_.on_load_error = load_handler_on_load_error; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/load_handler_cpptoc.h b/libcef_dll/cpptoc/load_handler_cpptoc.h new file mode 100644 index 000000000..171468dde --- /dev/null +++ b/libcef_dll/cpptoc/load_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_LOAD_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_LOAD_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_load_handler.h" +#include "include/capi/cef_load_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefLoadHandlerCppToC + : public CefCppToC { + public: + explicit CefLoadHandlerCppToC(CefLoadHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_LOAD_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/menu_model_cpptoc.cc b/libcef_dll/cpptoc/menu_model_cpptoc.cc new file mode 100644 index 000000000..6507f7a06 --- /dev/null +++ b/libcef_dll/cpptoc/menu_model_cpptoc.cc @@ -0,0 +1,1020 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/menu_model_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK menu_model_clear(struct _cef_menu_model_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->Clear(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_get_count(struct _cef_menu_model_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefMenuModelCppToC::Get(self)->GetCount(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK menu_model_add_separator(struct _cef_menu_model_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->AddSeparator(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_add_item(struct _cef_menu_model_t* self, + int command_id, const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->AddItem( + command_id, + CefString(label)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_add_check_item(struct _cef_menu_model_t* self, + int command_id, const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->AddCheckItem( + command_id, + CefString(label)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_add_radio_item(struct _cef_menu_model_t* self, + int command_id, const cef_string_t* label, int group_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->AddRadioItem( + command_id, + CefString(label), + group_id); + + // Return type: bool + return _retval; +} + +struct _cef_menu_model_t* CEF_CALLBACK menu_model_add_sub_menu( + struct _cef_menu_model_t* self, int command_id, + const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return NULL; + + // Execute + CefRefPtr _retval = CefMenuModelCppToC::Get(self)->AddSubMenu( + command_id, + CefString(label)); + + // Return type: refptr_same + return CefMenuModelCppToC::Wrap(_retval); +} + +int CEF_CALLBACK menu_model_insert_separator_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->InsertSeparatorAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_insert_item_at(struct _cef_menu_model_t* self, + int index, int command_id, const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->InsertItemAt( + index, + command_id, + CefString(label)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_insert_check_item_at(struct _cef_menu_model_t* self, + int index, int command_id, const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->InsertCheckItemAt( + index, + command_id, + CefString(label)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_insert_radio_item_at(struct _cef_menu_model_t* self, + int index, int command_id, const cef_string_t* label, int group_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->InsertRadioItemAt( + index, + command_id, + CefString(label), + group_id); + + // Return type: bool + return _retval; +} + +struct _cef_menu_model_t* CEF_CALLBACK menu_model_insert_sub_menu_at( + struct _cef_menu_model_t* self, int index, int command_id, + const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return NULL; + + // Execute + CefRefPtr _retval = CefMenuModelCppToC::Get( + self)->InsertSubMenuAt( + index, + command_id, + CefString(label)); + + // Return type: refptr_same + return CefMenuModelCppToC::Wrap(_retval); +} + +int CEF_CALLBACK menu_model_remove(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->Remove( + command_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_remove_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->RemoveAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_get_index_of(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefMenuModelCppToC::Get(self)->GetIndexOf( + command_id); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK menu_model_get_command_id_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefMenuModelCppToC::Get(self)->GetCommandIdAt( + index); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK menu_model_set_command_id_at(struct _cef_menu_model_t* self, + int index, int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetCommandIdAt( + index, + command_id); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK menu_model_get_label( + struct _cef_menu_model_t* self, int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefMenuModelCppToC::Get(self)->GetLabel( + command_id); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK menu_model_get_label_at( + struct _cef_menu_model_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefMenuModelCppToC::Get(self)->GetLabelAt( + index); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK menu_model_set_label(struct _cef_menu_model_t* self, + int command_id, const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetLabel( + command_id, + CefString(label)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_label_at(struct _cef_menu_model_t* self, + int index, const cef_string_t* label) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: label; type: string_byref_const + DCHECK(label); + if (!label) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetLabelAt( + index, + CefString(label)); + + // Return type: bool + return _retval; +} + +cef_menu_item_type_t CEF_CALLBACK menu_model_get_type( + struct _cef_menu_model_t* self, int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return MENUITEMTYPE_NONE; + + // Execute + cef_menu_item_type_t _retval = CefMenuModelCppToC::Get(self)->GetType( + command_id); + + // Return type: simple + return _retval; +} + +cef_menu_item_type_t CEF_CALLBACK menu_model_get_type_at( + struct _cef_menu_model_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return MENUITEMTYPE_NONE; + + // Execute + cef_menu_item_type_t _retval = CefMenuModelCppToC::Get(self)->GetTypeAt( + index); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK menu_model_get_group_id(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefMenuModelCppToC::Get(self)->GetGroupId( + command_id); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK menu_model_get_group_id_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefMenuModelCppToC::Get(self)->GetGroupIdAt( + index); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK menu_model_set_group_id(struct _cef_menu_model_t* self, + int command_id, int group_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetGroupId( + command_id, + group_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_group_id_at(struct _cef_menu_model_t* self, + int index, int group_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetGroupIdAt( + index, + group_id); + + // Return type: bool + return _retval; +} + +struct _cef_menu_model_t* CEF_CALLBACK menu_model_get_sub_menu( + struct _cef_menu_model_t* self, int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefMenuModelCppToC::Get(self)->GetSubMenu( + command_id); + + // Return type: refptr_same + return CefMenuModelCppToC::Wrap(_retval); +} + +struct _cef_menu_model_t* CEF_CALLBACK menu_model_get_sub_menu_at( + struct _cef_menu_model_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefMenuModelCppToC::Get(self)->GetSubMenuAt( + index); + + // Return type: refptr_same + return CefMenuModelCppToC::Wrap(_retval); +} + +int CEF_CALLBACK menu_model_is_visible(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->IsVisible( + command_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_is_visible_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->IsVisibleAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_visible(struct _cef_menu_model_t* self, + int command_id, int visible) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetVisible( + command_id, + visible?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_visible_at(struct _cef_menu_model_t* self, + int index, int visible) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetVisibleAt( + index, + visible?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_is_enabled(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->IsEnabled( + command_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_is_enabled_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->IsEnabledAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_enabled(struct _cef_menu_model_t* self, + int command_id, int enabled) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetEnabled( + command_id, + enabled?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_enabled_at(struct _cef_menu_model_t* self, + int index, int enabled) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetEnabledAt( + index, + enabled?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_is_checked(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->IsChecked( + command_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_is_checked_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->IsCheckedAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_checked(struct _cef_menu_model_t* self, + int command_id, int checked) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetChecked( + command_id, + checked?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_checked_at(struct _cef_menu_model_t* self, + int index, int checked) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetCheckedAt( + index, + checked?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_has_accelerator(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->HasAccelerator( + command_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_has_accelerator_at(struct _cef_menu_model_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->HasAcceleratorAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_accelerator(struct _cef_menu_model_t* self, + int command_id, int key_code, int shift_pressed, int ctrl_pressed, + int alt_pressed) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetAccelerator( + command_id, + key_code, + shift_pressed?true:false, + ctrl_pressed?true:false, + alt_pressed?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_set_accelerator_at(struct _cef_menu_model_t* self, + int index, int key_code, int shift_pressed, int ctrl_pressed, + int alt_pressed) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->SetAcceleratorAt( + index, + key_code, + shift_pressed?true:false, + ctrl_pressed?true:false, + alt_pressed?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_remove_accelerator(struct _cef_menu_model_t* self, + int command_id) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->RemoveAccelerator( + command_id); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_remove_accelerator_at( + struct _cef_menu_model_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->RemoveAcceleratorAt( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_get_accelerator(struct _cef_menu_model_t* self, + int command_id, int* key_code, int* shift_pressed, int* ctrl_pressed, + int* alt_pressed) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key_code; type: simple_byref + DCHECK(key_code); + if (!key_code) + return 0; + // Verify param: shift_pressed; type: bool_byref + DCHECK(shift_pressed); + if (!shift_pressed) + return 0; + // Verify param: ctrl_pressed; type: bool_byref + DCHECK(ctrl_pressed); + if (!ctrl_pressed) + return 0; + // Verify param: alt_pressed; type: bool_byref + DCHECK(alt_pressed); + if (!alt_pressed) + return 0; + + // Translate param: key_code; type: simple_byref + int key_codeVal = key_code?*key_code:0; + // Translate param: shift_pressed; type: bool_byref + bool shift_pressedBool = (shift_pressed && *shift_pressed)?true:false; + // Translate param: ctrl_pressed; type: bool_byref + bool ctrl_pressedBool = (ctrl_pressed && *ctrl_pressed)?true:false; + // Translate param: alt_pressed; type: bool_byref + bool alt_pressedBool = (alt_pressed && *alt_pressed)?true:false; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->GetAccelerator( + command_id, + key_codeVal, + shift_pressedBool, + ctrl_pressedBool, + alt_pressedBool); + + // Restore param: key_code; type: simple_byref + if (key_code) + *key_code = key_codeVal; + // Restore param: shift_pressed; type: bool_byref + if (shift_pressed) + *shift_pressed = shift_pressedBool?true:false; + // Restore param: ctrl_pressed; type: bool_byref + if (ctrl_pressed) + *ctrl_pressed = ctrl_pressedBool?true:false; + // Restore param: alt_pressed; type: bool_byref + if (alt_pressed) + *alt_pressed = alt_pressedBool?true:false; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK menu_model_get_accelerator_at(struct _cef_menu_model_t* self, + int index, int* key_code, int* shift_pressed, int* ctrl_pressed, + int* alt_pressed) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: key_code; type: simple_byref + DCHECK(key_code); + if (!key_code) + return 0; + // Verify param: shift_pressed; type: bool_byref + DCHECK(shift_pressed); + if (!shift_pressed) + return 0; + // Verify param: ctrl_pressed; type: bool_byref + DCHECK(ctrl_pressed); + if (!ctrl_pressed) + return 0; + // Verify param: alt_pressed; type: bool_byref + DCHECK(alt_pressed); + if (!alt_pressed) + return 0; + + // Translate param: key_code; type: simple_byref + int key_codeVal = key_code?*key_code:0; + // Translate param: shift_pressed; type: bool_byref + bool shift_pressedBool = (shift_pressed && *shift_pressed)?true:false; + // Translate param: ctrl_pressed; type: bool_byref + bool ctrl_pressedBool = (ctrl_pressed && *ctrl_pressed)?true:false; + // Translate param: alt_pressed; type: bool_byref + bool alt_pressedBool = (alt_pressed && *alt_pressed)?true:false; + + // Execute + bool _retval = CefMenuModelCppToC::Get(self)->GetAcceleratorAt( + index, + key_codeVal, + shift_pressedBool, + ctrl_pressedBool, + alt_pressedBool); + + // Restore param: key_code; type: simple_byref + if (key_code) + *key_code = key_codeVal; + // Restore param: shift_pressed; type: bool_byref + if (shift_pressed) + *shift_pressed = shift_pressedBool?true:false; + // Restore param: ctrl_pressed; type: bool_byref + if (ctrl_pressed) + *ctrl_pressed = ctrl_pressedBool?true:false; + // Restore param: alt_pressed; type: bool_byref + if (alt_pressed) + *alt_pressed = alt_pressedBool?true:false; + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefMenuModelCppToC::CefMenuModelCppToC(CefMenuModel* cls) + : CefCppToC(cls) { + struct_.struct_.clear = menu_model_clear; + struct_.struct_.get_count = menu_model_get_count; + struct_.struct_.add_separator = menu_model_add_separator; + struct_.struct_.add_item = menu_model_add_item; + struct_.struct_.add_check_item = menu_model_add_check_item; + struct_.struct_.add_radio_item = menu_model_add_radio_item; + struct_.struct_.add_sub_menu = menu_model_add_sub_menu; + struct_.struct_.insert_separator_at = menu_model_insert_separator_at; + struct_.struct_.insert_item_at = menu_model_insert_item_at; + struct_.struct_.insert_check_item_at = menu_model_insert_check_item_at; + struct_.struct_.insert_radio_item_at = menu_model_insert_radio_item_at; + struct_.struct_.insert_sub_menu_at = menu_model_insert_sub_menu_at; + struct_.struct_.remove = menu_model_remove; + struct_.struct_.remove_at = menu_model_remove_at; + struct_.struct_.get_index_of = menu_model_get_index_of; + struct_.struct_.get_command_id_at = menu_model_get_command_id_at; + struct_.struct_.set_command_id_at = menu_model_set_command_id_at; + struct_.struct_.get_label = menu_model_get_label; + struct_.struct_.get_label_at = menu_model_get_label_at; + struct_.struct_.set_label = menu_model_set_label; + struct_.struct_.set_label_at = menu_model_set_label_at; + struct_.struct_.get_type = menu_model_get_type; + struct_.struct_.get_type_at = menu_model_get_type_at; + struct_.struct_.get_group_id = menu_model_get_group_id; + struct_.struct_.get_group_id_at = menu_model_get_group_id_at; + struct_.struct_.set_group_id = menu_model_set_group_id; + struct_.struct_.set_group_id_at = menu_model_set_group_id_at; + struct_.struct_.get_sub_menu = menu_model_get_sub_menu; + struct_.struct_.get_sub_menu_at = menu_model_get_sub_menu_at; + struct_.struct_.is_visible = menu_model_is_visible; + struct_.struct_.is_visible_at = menu_model_is_visible_at; + struct_.struct_.set_visible = menu_model_set_visible; + struct_.struct_.set_visible_at = menu_model_set_visible_at; + struct_.struct_.is_enabled = menu_model_is_enabled; + struct_.struct_.is_enabled_at = menu_model_is_enabled_at; + struct_.struct_.set_enabled = menu_model_set_enabled; + struct_.struct_.set_enabled_at = menu_model_set_enabled_at; + struct_.struct_.is_checked = menu_model_is_checked; + struct_.struct_.is_checked_at = menu_model_is_checked_at; + struct_.struct_.set_checked = menu_model_set_checked; + struct_.struct_.set_checked_at = menu_model_set_checked_at; + struct_.struct_.has_accelerator = menu_model_has_accelerator; + struct_.struct_.has_accelerator_at = menu_model_has_accelerator_at; + struct_.struct_.set_accelerator = menu_model_set_accelerator; + struct_.struct_.set_accelerator_at = menu_model_set_accelerator_at; + struct_.struct_.remove_accelerator = menu_model_remove_accelerator; + struct_.struct_.remove_accelerator_at = menu_model_remove_accelerator_at; + struct_.struct_.get_accelerator = menu_model_get_accelerator; + struct_.struct_.get_accelerator_at = menu_model_get_accelerator_at; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/menu_model_cpptoc.h b/libcef_dll/cpptoc/menu_model_cpptoc.h new file mode 100644 index 000000000..d4684935d --- /dev/null +++ b/libcef_dll/cpptoc/menu_model_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_MENU_MODEL_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_MENU_MODEL_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_menu_model.h" +#include "include/capi/cef_menu_model_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefMenuModelCppToC + : public CefCppToC { + public: + explicit CefMenuModelCppToC(CefMenuModel* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_MENU_MODEL_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/navigation_entry_cpptoc.cc b/libcef_dll/cpptoc/navigation_entry_cpptoc.cc new file mode 100644 index 000000000..beb1d9224 --- /dev/null +++ b/libcef_dll/cpptoc/navigation_entry_cpptoc.cc @@ -0,0 +1,191 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/navigation_entry_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK navigation_entry_is_valid( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefNavigationEntryCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK navigation_entry_get_url( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefNavigationEntryCppToC::Get(self)->GetURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK navigation_entry_get_display_url( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefNavigationEntryCppToC::Get(self)->GetDisplayURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK navigation_entry_get_original_url( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefNavigationEntryCppToC::Get(self)->GetOriginalURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK navigation_entry_get_title( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefNavigationEntryCppToC::Get(self)->GetTitle(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_transition_type_t CEF_CALLBACK navigation_entry_get_transition_type( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return TT_EXPLICIT; + + // Execute + cef_transition_type_t _retval = CefNavigationEntryCppToC::Get( + self)->GetTransitionType(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK navigation_entry_has_post_data( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefNavigationEntryCppToC::Get(self)->HasPostData(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK navigation_entry_get_frame_name( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefNavigationEntryCppToC::Get(self)->GetFrameName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_time_t CEF_CALLBACK navigation_entry_get_completion_time( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CefTime(); + + // Execute + cef_time_t _retval = CefNavigationEntryCppToC::Get(self)->GetCompletionTime(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK navigation_entry_get_http_status_code( + struct _cef_navigation_entry_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefNavigationEntryCppToC::Get(self)->GetHttpStatusCode(); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefNavigationEntryCppToC::CefNavigationEntryCppToC(CefNavigationEntry* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = navigation_entry_is_valid; + struct_.struct_.get_url = navigation_entry_get_url; + struct_.struct_.get_display_url = navigation_entry_get_display_url; + struct_.struct_.get_original_url = navigation_entry_get_original_url; + struct_.struct_.get_title = navigation_entry_get_title; + struct_.struct_.get_transition_type = navigation_entry_get_transition_type; + struct_.struct_.has_post_data = navigation_entry_has_post_data; + struct_.struct_.get_frame_name = navigation_entry_get_frame_name; + struct_.struct_.get_completion_time = navigation_entry_get_completion_time; + struct_.struct_.get_http_status_code = navigation_entry_get_http_status_code; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/navigation_entry_cpptoc.h b/libcef_dll/cpptoc/navigation_entry_cpptoc.h new file mode 100644 index 000000000..e6fae6775 --- /dev/null +++ b/libcef_dll/cpptoc/navigation_entry_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_NAVIGATION_ENTRY_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_NAVIGATION_ENTRY_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_navigation_entry.h" +#include "include/capi/cef_navigation_entry_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefNavigationEntryCppToC + : public CefCppToC { + public: + explicit CefNavigationEntryCppToC(CefNavigationEntry* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_NAVIGATION_ENTRY_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.cc b/libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.cc new file mode 100644 index 000000000..ae2d0c78e --- /dev/null +++ b/libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.cc @@ -0,0 +1,59 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h" +#include "libcef_dll/ctocpp/navigation_entry_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK navigation_entry_visitor_visit( + struct _cef_navigation_entry_visitor_t* self, + struct _cef_navigation_entry_t* entry, int current, int index, + int total) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: entry; type: refptr_diff + DCHECK(entry); + if (!entry) + return 0; + + // Execute + bool _retval = CefNavigationEntryVisitorCppToC::Get(self)->Visit( + CefNavigationEntryCToCpp::Wrap(entry), + current?true:false, + index, + total); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefNavigationEntryVisitorCppToC::CefNavigationEntryVisitorCppToC( + CefNavigationEntryVisitor* cls) + : CefCppToC(cls) { + struct_.struct_.visit = navigation_entry_visitor_visit; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h b/libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h new file mode 100644 index 000000000..574303278 --- /dev/null +++ b/libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_NAVIGATION_ENTRY_VISITOR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_NAVIGATION_ENTRY_VISITOR_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefNavigationEntryVisitorCppToC + : public CefCppToC { + public: + explicit CefNavigationEntryVisitorCppToC(CefNavigationEntryVisitor* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_NAVIGATION_ENTRY_VISITOR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/permission_handler_cpptoc.cc b/libcef_dll/cpptoc/permission_handler_cpptoc.cc new file mode 100644 index 000000000..5558de8eb --- /dev/null +++ b/libcef_dll/cpptoc/permission_handler_cpptoc.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/permission_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK permission_handler_on_before_script_extension_load( + struct _cef_permission_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_t* extensionName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: extensionName; type: string_byref_const + DCHECK(extensionName); + if (!extensionName) + return 0; + + // Execute + bool _retval = CefPermissionHandlerCppToC::Get( + self)->OnBeforeScriptExtensionLoad( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(extensionName)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPermissionHandlerCppToC::CefPermissionHandlerCppToC( + CefPermissionHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_script_extension_load = + permission_handler_on_before_script_extension_load; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/permission_handler_cpptoc.h b/libcef_dll/cpptoc/permission_handler_cpptoc.h new file mode 100644 index 000000000..6c8d2f86d --- /dev/null +++ b/libcef_dll/cpptoc/permission_handler_cpptoc.h @@ -0,0 +1,41 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_PERMISSION_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PERMISSION_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_permission_handler.h" +#include "include/capi/cef_permission_handler_capi.h" +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_frame.h" +#include "include/capi/cef_frame_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefPermissionHandlerCppToC + : public CefCppToC { + public: + explicit CefPermissionHandlerCppToC(CefPermissionHandler* cls); + virtual ~CefPermissionHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PERMISSION_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/post_data_cpptoc.cc b/libcef_dll/cpptoc/post_data_cpptoc.cc new file mode 100644 index 000000000..a0994b1a0 --- /dev/null +++ b/libcef_dll/cpptoc/post_data_cpptoc.cc @@ -0,0 +1,164 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include +#include "libcef_dll/cpptoc/post_data_cpptoc.h" +#include "libcef_dll/cpptoc/post_data_element_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_post_data_t* cef_post_data_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefPostData::Create(); + + // Return type: refptr_same + return CefPostDataCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK post_data_is_read_only(struct _cef_post_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPostDataCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +size_t CEF_CALLBACK post_data_get_element_count(struct _cef_post_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefPostDataCppToC::Get(self)->GetElementCount(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK post_data_get_elements(struct _cef_post_data_t* self, + size_t* elementsCount, struct _cef_post_data_element_t** elements) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: elements; type: refptr_vec_same_byref + DCHECK(elementsCount && (*elementsCount == 0 || elements)); + if (!elementsCount || (*elementsCount > 0 && !elements)) + return; + + // Translate param: elements; type: refptr_vec_same_byref + std::vector > elementsList; + if (elementsCount && *elementsCount > 0 && elements) { + for (size_t i = 0; i < *elementsCount; ++i) { + elementsList.push_back(CefPostDataElementCppToC::Unwrap(elements[i])); + } + } + + // Execute + CefPostDataCppToC::Get(self)->GetElements( + elementsList); + + // Restore param: elements; type: refptr_vec_same_byref + if (elementsCount && elements) { + *elementsCount = std::min(elementsList.size(), *elementsCount); + if (*elementsCount > 0) { + for (size_t i = 0; i < *elementsCount; ++i) { + elements[i] = CefPostDataElementCppToC::Wrap(elementsList[i]); + } + } + } +} + +int CEF_CALLBACK post_data_remove_element(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: element; type: refptr_same + DCHECK(element); + if (!element) + return 0; + + // Execute + bool _retval = CefPostDataCppToC::Get(self)->RemoveElement( + CefPostDataElementCppToC::Unwrap(element)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK post_data_add_element(struct _cef_post_data_t* self, + struct _cef_post_data_element_t* element) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: element; type: refptr_same + DCHECK(element); + if (!element) + return 0; + + // Execute + bool _retval = CefPostDataCppToC::Get(self)->AddElement( + CefPostDataElementCppToC::Unwrap(element)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK post_data_remove_elements(struct _cef_post_data_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPostDataCppToC::Get(self)->RemoveElements(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPostDataCppToC::CefPostDataCppToC(CefPostData* cls) + : CefCppToC(cls) { + struct_.struct_.is_read_only = post_data_is_read_only; + struct_.struct_.get_element_count = post_data_get_element_count; + struct_.struct_.get_elements = post_data_get_elements; + struct_.struct_.remove_element = post_data_remove_element; + struct_.struct_.add_element = post_data_add_element; + struct_.struct_.remove_elements = post_data_remove_elements; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/post_data_cpptoc.h b/libcef_dll/cpptoc/post_data_cpptoc.h new file mode 100644 index 000000000..48edf2119 --- /dev/null +++ b/libcef_dll/cpptoc/post_data_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_POST_DATA_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_POST_DATA_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request.h" +#include "include/capi/cef_request_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefPostDataCppToC + : public CefCppToC { + public: + explicit CefPostDataCppToC(CefPostData* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_POST_DATA_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/post_data_element_cpptoc.cc b/libcef_dll/cpptoc/post_data_element_cpptoc.cc new file mode 100644 index 000000000..4a4c2a7f6 --- /dev/null +++ b/libcef_dll/cpptoc/post_data_element_cpptoc.cc @@ -0,0 +1,180 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/post_data_element_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_post_data_element_t* cef_post_data_element_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefPostDataElement::Create(); + + // Return type: refptr_same + return CefPostDataElementCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK post_data_element_is_read_only( + struct _cef_post_data_element_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPostDataElementCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK post_data_element_set_to_empty( + struct _cef_post_data_element_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPostDataElementCppToC::Get(self)->SetToEmpty(); +} + +void CEF_CALLBACK post_data_element_set_to_file( + struct _cef_post_data_element_t* self, const cef_string_t* fileName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: fileName; type: string_byref_const + DCHECK(fileName); + if (!fileName) + return; + + // Execute + CefPostDataElementCppToC::Get(self)->SetToFile( + CefString(fileName)); +} + +void CEF_CALLBACK post_data_element_set_to_bytes( + struct _cef_post_data_element_t* self, size_t size, const void* bytes) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: bytes; type: simple_byaddr + DCHECK(bytes); + if (!bytes) + return; + + // Execute + CefPostDataElementCppToC::Get(self)->SetToBytes( + size, + bytes); +} + +cef_postdataelement_type_t CEF_CALLBACK post_data_element_get_type( + struct _cef_post_data_element_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return PDE_TYPE_EMPTY; + + // Execute + cef_postdataelement_type_t _retval = CefPostDataElementCppToC::Get( + self)->GetType(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK post_data_element_get_file( + struct _cef_post_data_element_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefPostDataElementCppToC::Get(self)->GetFile(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +size_t CEF_CALLBACK post_data_element_get_bytes_count( + struct _cef_post_data_element_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefPostDataElementCppToC::Get(self)->GetBytesCount(); + + // Return type: simple + return _retval; +} + +size_t CEF_CALLBACK post_data_element_get_bytes( + struct _cef_post_data_element_t* self, size_t size, void* bytes) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: bytes; type: simple_byaddr + DCHECK(bytes); + if (!bytes) + return 0; + + // Execute + size_t _retval = CefPostDataElementCppToC::Get(self)->GetBytes( + size, + bytes); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPostDataElementCppToC::CefPostDataElementCppToC(CefPostDataElement* cls) + : CefCppToC(cls) { + struct_.struct_.is_read_only = post_data_element_is_read_only; + struct_.struct_.set_to_empty = post_data_element_set_to_empty; + struct_.struct_.set_to_file = post_data_element_set_to_file; + struct_.struct_.set_to_bytes = post_data_element_set_to_bytes; + struct_.struct_.get_type = post_data_element_get_type; + struct_.struct_.get_file = post_data_element_get_file; + struct_.struct_.get_bytes_count = post_data_element_get_bytes_count; + struct_.struct_.get_bytes = post_data_element_get_bytes; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/post_data_element_cpptoc.h b/libcef_dll/cpptoc/post_data_element_cpptoc.h new file mode 100644 index 000000000..322368cfd --- /dev/null +++ b/libcef_dll/cpptoc/post_data_element_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_POST_DATA_ELEMENT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_POST_DATA_ELEMENT_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request.h" +#include "include/capi/cef_request_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefPostDataElementCppToC + : public CefCppToC { + public: + explicit CefPostDataElementCppToC(CefPostDataElement* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_POST_DATA_ELEMENT_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/print_dialog_callback_cpptoc.cc b/libcef_dll/cpptoc/print_dialog_callback_cpptoc.cc new file mode 100644 index 000000000..6cb888446 --- /dev/null +++ b/libcef_dll/cpptoc/print_dialog_callback_cpptoc.cc @@ -0,0 +1,64 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/print_dialog_callback_cpptoc.h" +#include "libcef_dll/cpptoc/print_settings_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK print_dialog_callback_cont( + struct _cef_print_dialog_callback_t* self, + struct _cef_print_settings_t* settings) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: settings; type: refptr_same + DCHECK(settings); + if (!settings) + return; + + // Execute + CefPrintDialogCallbackCppToC::Get(self)->Continue( + CefPrintSettingsCppToC::Unwrap(settings)); +} + +void CEF_CALLBACK print_dialog_callback_cancel( + struct _cef_print_dialog_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintDialogCallbackCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPrintDialogCallbackCppToC::CefPrintDialogCallbackCppToC( + CefPrintDialogCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = print_dialog_callback_cont; + struct_.struct_.cancel = print_dialog_callback_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/print_dialog_callback_cpptoc.h b/libcef_dll/cpptoc/print_dialog_callback_cpptoc.h new file mode 100644 index 000000000..48748778a --- /dev/null +++ b/libcef_dll/cpptoc/print_dialog_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_PRINT_DIALOG_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PRINT_DIALOG_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_print_handler.h" +#include "include/capi/cef_print_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefPrintDialogCallbackCppToC + : public CefCppToC { + public: + explicit CefPrintDialogCallbackCppToC(CefPrintDialogCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PRINT_DIALOG_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/print_handler_cpptoc.cc b/libcef_dll/cpptoc/print_handler_cpptoc.cc new file mode 100644 index 000000000..6f896aef8 --- /dev/null +++ b/libcef_dll/cpptoc/print_handler_cpptoc.cc @@ -0,0 +1,121 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/print_handler_cpptoc.h" +#include "libcef_dll/ctocpp/print_dialog_callback_ctocpp.h" +#include "libcef_dll/ctocpp/print_job_callback_ctocpp.h" +#include "libcef_dll/ctocpp/print_settings_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK print_handler_on_print_settings( + struct _cef_print_handler_t* self, struct _cef_print_settings_t* settings, + int get_defaults) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: settings; type: refptr_diff + DCHECK(settings); + if (!settings) + return; + + // Execute + CefPrintHandlerCppToC::Get(self)->OnPrintSettings( + CefPrintSettingsCToCpp::Wrap(settings), + get_defaults?true:false); +} + +int CEF_CALLBACK print_handler_on_print_dialog( + struct _cef_print_handler_t* self, int has_selection, + cef_print_dialog_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefPrintHandlerCppToC::Get(self)->OnPrintDialog( + has_selection?true:false, + CefPrintDialogCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK print_handler_on_print_job(struct _cef_print_handler_t* self, + const cef_string_t* document_name, const cef_string_t* pdf_file_path, + cef_print_job_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: document_name; type: string_byref_const + DCHECK(document_name); + if (!document_name) + return 0; + // Verify param: pdf_file_path; type: string_byref_const + DCHECK(pdf_file_path); + if (!pdf_file_path) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefPrintHandlerCppToC::Get(self)->OnPrintJob( + CefString(document_name), + CefString(pdf_file_path), + CefPrintJobCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK print_handler_on_print_reset( + struct _cef_print_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintHandlerCppToC::Get(self)->OnPrintReset(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPrintHandlerCppToC::CefPrintHandlerCppToC(CefPrintHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.on_print_settings = print_handler_on_print_settings; + struct_.struct_.on_print_dialog = print_handler_on_print_dialog; + struct_.struct_.on_print_job = print_handler_on_print_job; + struct_.struct_.on_print_reset = print_handler_on_print_reset; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/print_handler_cpptoc.h b/libcef_dll/cpptoc/print_handler_cpptoc.h new file mode 100644 index 000000000..64fc718e5 --- /dev/null +++ b/libcef_dll/cpptoc/print_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_PRINT_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PRINT_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_print_handler.h" +#include "include/capi/cef_print_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefPrintHandlerCppToC + : public CefCppToC { + public: + explicit CefPrintHandlerCppToC(CefPrintHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PRINT_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/print_job_callback_cpptoc.cc b/libcef_dll/cpptoc/print_job_callback_cpptoc.cc new file mode 100644 index 000000000..0f03a855e --- /dev/null +++ b/libcef_dll/cpptoc/print_job_callback_cpptoc.cc @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/print_job_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK print_job_callback_cont( + struct _cef_print_job_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintJobCallbackCppToC::Get(self)->Continue(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPrintJobCallbackCppToC::CefPrintJobCallbackCppToC(CefPrintJobCallback* cls) + : CefCppToC(cls) { + struct_.struct_.cont = print_job_callback_cont; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/print_job_callback_cpptoc.h b/libcef_dll/cpptoc/print_job_callback_cpptoc.h new file mode 100644 index 000000000..f16f09b5b --- /dev/null +++ b/libcef_dll/cpptoc/print_job_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_PRINT_JOB_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PRINT_JOB_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_print_handler.h" +#include "include/capi/cef_print_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefPrintJobCallbackCppToC + : public CefCppToC { + public: + explicit CefPrintJobCallbackCppToC(CefPrintJobCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PRINT_JOB_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/print_settings_cpptoc.cc b/libcef_dll/cpptoc/print_settings_cpptoc.cc new file mode 100644 index 000000000..82da835c6 --- /dev/null +++ b/libcef_dll/cpptoc/print_settings_cpptoc.cc @@ -0,0 +1,447 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include +#include "libcef_dll/cpptoc/print_settings_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_print_settings_t* cef_print_settings_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefPrintSettings::Create(); + + // Return type: refptr_same + return CefPrintSettingsCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK print_settings_is_valid(struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPrintSettingsCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK print_settings_is_read_only( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPrintSettingsCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +struct _cef_print_settings_t* CEF_CALLBACK print_settings_copy( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefPrintSettingsCppToC::Get(self)->Copy( + ); + + // Return type: refptr_same + return CefPrintSettingsCppToC::Wrap(_retval); +} + +void CEF_CALLBACK print_settings_set_orientation( + struct _cef_print_settings_t* self, int landscape) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetOrientation( + landscape?true:false); +} + +int CEF_CALLBACK print_settings_is_landscape( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPrintSettingsCppToC::Get(self)->IsLandscape(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK print_settings_set_printer_printable_area( + struct _cef_print_settings_t* self, + const cef_size_t* physical_size_device_units, + const cef_rect_t* printable_area_device_units, int landscape_needs_flip) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: physical_size_device_units; type: simple_byref_const + DCHECK(physical_size_device_units); + if (!physical_size_device_units) + return; + // Verify param: printable_area_device_units; type: simple_byref_const + DCHECK(printable_area_device_units); + if (!printable_area_device_units) + return; + + // Translate param: physical_size_device_units; type: simple_byref_const + CefSize physical_size_device_unitsVal = + physical_size_device_units?*physical_size_device_units:CefSize(); + // Translate param: printable_area_device_units; type: simple_byref_const + CefRect printable_area_device_unitsVal = + printable_area_device_units?*printable_area_device_units:CefRect(); + + // Execute + CefPrintSettingsCppToC::Get(self)->SetPrinterPrintableArea( + physical_size_device_unitsVal, + printable_area_device_unitsVal, + landscape_needs_flip?true:false); +} + +void CEF_CALLBACK print_settings_set_device_name( + struct _cef_print_settings_t* self, const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: name + + // Execute + CefPrintSettingsCppToC::Get(self)->SetDeviceName( + CefString(name)); +} + +cef_string_userfree_t CEF_CALLBACK print_settings_get_device_name( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefPrintSettingsCppToC::Get(self)->GetDeviceName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK print_settings_set_dpi(struct _cef_print_settings_t* self, + int dpi) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetDPI( + dpi); +} + +int CEF_CALLBACK print_settings_get_dpi(struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefPrintSettingsCppToC::Get(self)->GetDPI(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK print_settings_set_page_ranges( + struct _cef_print_settings_t* self, size_t rangesCount, + cef_page_range_t const* ranges) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: ranges; type: simple_vec_byref_const + DCHECK(rangesCount == 0 || ranges); + if (rangesCount > 0 && !ranges) + return; + + // Translate param: ranges; type: simple_vec_byref_const + std::vector rangesList; + if (rangesCount > 0) { + for (size_t i = 0; i < rangesCount; ++i) { + rangesList.push_back(ranges[i]); + } + } + + // Execute + CefPrintSettingsCppToC::Get(self)->SetPageRanges( + rangesList); +} + +size_t CEF_CALLBACK print_settings_get_page_ranges_count( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefPrintSettingsCppToC::Get(self)->GetPageRangesCount(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK print_settings_get_page_ranges( + struct _cef_print_settings_t* self, size_t* rangesCount, + cef_page_range_t* ranges) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: ranges; type: simple_vec_byref + DCHECK(rangesCount && (*rangesCount == 0 || ranges)); + if (!rangesCount || (*rangesCount > 0 && !ranges)) + return; + + // Translate param: ranges; type: simple_vec_byref + std::vector rangesList; + if (rangesCount && *rangesCount > 0 && ranges) { + for (size_t i = 0; i < *rangesCount; ++i) { + rangesList.push_back(ranges[i]); + } + } + + // Execute + CefPrintSettingsCppToC::Get(self)->GetPageRanges( + rangesList); + + // Restore param: ranges; type: simple_vec_byref + if (rangesCount && ranges) { + *rangesCount = std::min(rangesList.size(), *rangesCount); + if (*rangesCount > 0) { + for (size_t i = 0; i < *rangesCount; ++i) { + ranges[i] = rangesList[i]; + } + } + } +} + +void CEF_CALLBACK print_settings_set_selection_only( + struct _cef_print_settings_t* self, int selection_only) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetSelectionOnly( + selection_only?true:false); +} + +int CEF_CALLBACK print_settings_is_selection_only( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPrintSettingsCppToC::Get(self)->IsSelectionOnly(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK print_settings_set_collate(struct _cef_print_settings_t* self, + int collate) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetCollate( + collate?true:false); +} + +int CEF_CALLBACK print_settings_will_collate( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefPrintSettingsCppToC::Get(self)->WillCollate(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK print_settings_set_color_model( + struct _cef_print_settings_t* self, cef_color_model_t model) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetColorModel( + model); +} + +cef_color_model_t CEF_CALLBACK print_settings_get_color_model( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return COLOR_MODEL_UNKNOWN; + + // Execute + cef_color_model_t _retval = CefPrintSettingsCppToC::Get(self)->GetColorModel( + ); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK print_settings_set_copies(struct _cef_print_settings_t* self, + int copies) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetCopies( + copies); +} + +int CEF_CALLBACK print_settings_get_copies(struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefPrintSettingsCppToC::Get(self)->GetCopies(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK print_settings_set_duplex_mode( + struct _cef_print_settings_t* self, cef_duplex_mode_t mode) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefPrintSettingsCppToC::Get(self)->SetDuplexMode( + mode); +} + +cef_duplex_mode_t CEF_CALLBACK print_settings_get_duplex_mode( + struct _cef_print_settings_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return DUPLEX_MODE_UNKNOWN; + + // Execute + cef_duplex_mode_t _retval = CefPrintSettingsCppToC::Get(self)->GetDuplexMode( + ); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPrintSettingsCppToC::CefPrintSettingsCppToC(CefPrintSettings* cls) + : CefCppToC( + cls) { + struct_.struct_.is_valid = print_settings_is_valid; + struct_.struct_.is_read_only = print_settings_is_read_only; + struct_.struct_.copy = print_settings_copy; + struct_.struct_.set_orientation = print_settings_set_orientation; + struct_.struct_.is_landscape = print_settings_is_landscape; + struct_.struct_.set_printer_printable_area = + print_settings_set_printer_printable_area; + struct_.struct_.set_device_name = print_settings_set_device_name; + struct_.struct_.get_device_name = print_settings_get_device_name; + struct_.struct_.set_dpi = print_settings_set_dpi; + struct_.struct_.get_dpi = print_settings_get_dpi; + struct_.struct_.set_page_ranges = print_settings_set_page_ranges; + struct_.struct_.get_page_ranges_count = print_settings_get_page_ranges_count; + struct_.struct_.get_page_ranges = print_settings_get_page_ranges; + struct_.struct_.set_selection_only = print_settings_set_selection_only; + struct_.struct_.is_selection_only = print_settings_is_selection_only; + struct_.struct_.set_collate = print_settings_set_collate; + struct_.struct_.will_collate = print_settings_will_collate; + struct_.struct_.set_color_model = print_settings_set_color_model; + struct_.struct_.get_color_model = print_settings_get_color_model; + struct_.struct_.set_copies = print_settings_set_copies; + struct_.struct_.get_copies = print_settings_get_copies; + struct_.struct_.set_duplex_mode = print_settings_set_duplex_mode; + struct_.struct_.get_duplex_mode = print_settings_get_duplex_mode; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/print_settings_cpptoc.h b/libcef_dll/cpptoc/print_settings_cpptoc.h new file mode 100644 index 000000000..c17b2ca29 --- /dev/null +++ b/libcef_dll/cpptoc/print_settings_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_PRINT_SETTINGS_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PRINT_SETTINGS_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_print_settings.h" +#include "include/capi/cef_print_settings_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefPrintSettingsCppToC + : public CefCppToC { + public: + explicit CefPrintSettingsCppToC(CefPrintSettings* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PRINT_SETTINGS_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/process_message_cpptoc.cc b/libcef_dll/cpptoc/process_message_cpptoc.cc new file mode 100644 index 000000000..bac0a8cfb --- /dev/null +++ b/libcef_dll/cpptoc/process_message_cpptoc.cc @@ -0,0 +1,132 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/list_value_cpptoc.h" +#include "libcef_dll/cpptoc/process_message_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_process_message_t* cef_process_message_create( + const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return NULL; + + // Execute + CefRefPtr _retval = CefProcessMessage::Create( + CefString(name)); + + // Return type: refptr_same + return CefProcessMessageCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK process_message_is_valid(struct _cef_process_message_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefProcessMessageCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK process_message_is_read_only( + struct _cef_process_message_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefProcessMessageCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +struct _cef_process_message_t* CEF_CALLBACK process_message_copy( + struct _cef_process_message_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefProcessMessageCppToC::Get( + self)->Copy(); + + // Return type: refptr_same + return CefProcessMessageCppToC::Wrap(_retval); +} + +cef_string_userfree_t CEF_CALLBACK process_message_get_name( + struct _cef_process_message_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefProcessMessageCppToC::Get(self)->GetName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +struct _cef_list_value_t* CEF_CALLBACK process_message_get_argument_list( + struct _cef_process_message_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefProcessMessageCppToC::Get( + self)->GetArgumentList(); + + // Return type: refptr_same + return CefListValueCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefProcessMessageCppToC::CefProcessMessageCppToC(CefProcessMessage* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = process_message_is_valid; + struct_.struct_.is_read_only = process_message_is_read_only; + struct_.struct_.copy = process_message_copy; + struct_.struct_.get_name = process_message_get_name; + struct_.struct_.get_argument_list = process_message_get_argument_list; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/process_message_cpptoc.h b/libcef_dll/cpptoc/process_message_cpptoc.h new file mode 100644 index 000000000..03ec4b374 --- /dev/null +++ b/libcef_dll/cpptoc/process_message_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_PROCESS_MESSAGE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PROCESS_MESSAGE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_process_message.h" +#include "include/capi/cef_process_message_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefProcessMessageCppToC + : public CefCppToC { + public: + explicit CefProcessMessageCppToC(CefProcessMessage* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PROCESS_MESSAGE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/quota_callback_cpptoc.cc b/libcef_dll/cpptoc/quota_callback_cpptoc.cc new file mode 100644 index 000000000..21fcd0acf --- /dev/null +++ b/libcef_dll/cpptoc/quota_callback_cpptoc.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/quota_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK quota_callback_cont(struct _cef_quota_callback_t* self, + int allow) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefQuotaCallbackCppToC::Get(self)->Continue( + allow?true:false); +} + +void CEF_CALLBACK quota_callback_cancel(struct _cef_quota_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefQuotaCallbackCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefQuotaCallbackCppToC::CefQuotaCallbackCppToC(CefQuotaCallback* cls) + : CefCppToC( + cls) { + struct_.struct_.cont = quota_callback_cont; + struct_.struct_.cancel = quota_callback_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/quota_callback_cpptoc.h b/libcef_dll/cpptoc/quota_callback_cpptoc.h new file mode 100644 index 000000000..1d660d268 --- /dev/null +++ b/libcef_dll/cpptoc/quota_callback_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_QUOTA_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_QUOTA_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request_handler.h" +#include "include/capi/cef_request_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefQuotaCallbackCppToC + : public CefCppToC { + public: + explicit CefQuotaCallbackCppToC(CefQuotaCallback* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_QUOTA_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/read_handler_cpptoc.cc b/libcef_dll/cpptoc/read_handler_cpptoc.cc new file mode 100644 index 000000000..df23e9665 --- /dev/null +++ b/libcef_dll/cpptoc/read_handler_cpptoc.cc @@ -0,0 +1,115 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/read_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +size_t CEF_CALLBACK read_handler_read(struct _cef_read_handler_t* self, + void* ptr, size_t size, size_t n) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = CefReadHandlerCppToC::Get(self)->Read( + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK read_handler_seek(struct _cef_read_handler_t* self, + int64 offset, int whence) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefReadHandlerCppToC::Get(self)->Seek( + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK read_handler_tell(struct _cef_read_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefReadHandlerCppToC::Get(self)->Tell(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK read_handler_eof(struct _cef_read_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefReadHandlerCppToC::Get(self)->Eof(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK read_handler_may_block(struct _cef_read_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefReadHandlerCppToC::Get(self)->MayBlock(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefReadHandlerCppToC::CefReadHandlerCppToC(CefReadHandler* cls) + : CefCppToC(cls) { + struct_.struct_.read = read_handler_read; + struct_.struct_.seek = read_handler_seek; + struct_.struct_.tell = read_handler_tell; + struct_.struct_.eof = read_handler_eof; + struct_.struct_.may_block = read_handler_may_block; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/read_handler_cpptoc.h b/libcef_dll/cpptoc/read_handler_cpptoc.h new file mode 100644 index 000000000..f948301c9 --- /dev/null +++ b/libcef_dll/cpptoc/read_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_READ_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_READ_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefReadHandlerCppToC + : public CefCppToC { + public: + explicit CefReadHandlerCppToC(CefReadHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_READ_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/render_handler_cpptoc.cc b/libcef_dll/cpptoc/render_handler_cpptoc.cc new file mode 100644 index 000000000..66a919c8c --- /dev/null +++ b/libcef_dll/cpptoc/render_handler_cpptoc.cc @@ -0,0 +1,371 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/render_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/drag_data_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK render_handler_get_root_screen_rect( + struct _cef_render_handler_t* self, cef_browser_t* browser, + cef_rect_t* rect) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: rect; type: simple_byref + DCHECK(rect); + if (!rect) + return 0; + + // Translate param: rect; type: simple_byref + CefRect rectVal = rect?*rect:CefRect(); + + // Execute + bool _retval = CefRenderHandlerCppToC::Get(self)->GetRootScreenRect( + CefBrowserCToCpp::Wrap(browser), + rectVal); + + // Restore param: rect; type: simple_byref + if (rect) + *rect = rectVal; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK render_handler_get_view_rect( + struct _cef_render_handler_t* self, cef_browser_t* browser, + cef_rect_t* rect) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: rect; type: simple_byref + DCHECK(rect); + if (!rect) + return 0; + + // Translate param: rect; type: simple_byref + CefRect rectVal = rect?*rect:CefRect(); + + // Execute + bool _retval = CefRenderHandlerCppToC::Get(self)->GetViewRect( + CefBrowserCToCpp::Wrap(browser), + rectVal); + + // Restore param: rect; type: simple_byref + if (rect) + *rect = rectVal; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK render_handler_get_screen_point( + struct _cef_render_handler_t* self, cef_browser_t* browser, int viewX, + int viewY, int* screenX, int* screenY) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: screenX; type: simple_byref + DCHECK(screenX); + if (!screenX) + return 0; + // Verify param: screenY; type: simple_byref + DCHECK(screenY); + if (!screenY) + return 0; + + // Translate param: screenX; type: simple_byref + int screenXVal = screenX?*screenX:0; + // Translate param: screenY; type: simple_byref + int screenYVal = screenY?*screenY:0; + + // Execute + bool _retval = CefRenderHandlerCppToC::Get(self)->GetScreenPoint( + CefBrowserCToCpp::Wrap(browser), + viewX, + viewY, + screenXVal, + screenYVal); + + // Restore param: screenX; type: simple_byref + if (screenX) + *screenX = screenXVal; + // Restore param: screenY; type: simple_byref + if (screenY) + *screenY = screenYVal; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK render_handler_get_screen_info( + struct _cef_render_handler_t* self, cef_browser_t* browser, + struct _cef_screen_info_t* screen_info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: screen_info; type: struct_byref + DCHECK(screen_info); + if (!screen_info) + return 0; + + // Translate param: screen_info; type: struct_byref + CefScreenInfo screen_infoObj; + if (screen_info) + screen_infoObj.AttachTo(*screen_info); + + // Execute + bool _retval = CefRenderHandlerCppToC::Get(self)->GetScreenInfo( + CefBrowserCToCpp::Wrap(browser), + screen_infoObj); + + // Restore param: screen_info; type: struct_byref + if (screen_info) + screen_infoObj.DetachTo(*screen_info); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK render_handler_on_popup_show( + struct _cef_render_handler_t* self, cef_browser_t* browser, int show) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefRenderHandlerCppToC::Get(self)->OnPopupShow( + CefBrowserCToCpp::Wrap(browser), + show?true:false); +} + +void CEF_CALLBACK render_handler_on_popup_size( + struct _cef_render_handler_t* self, cef_browser_t* browser, + const cef_rect_t* rect) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: rect; type: simple_byref_const + DCHECK(rect); + if (!rect) + return; + + // Translate param: rect; type: simple_byref_const + CefRect rectVal = rect?*rect:CefRect(); + + // Execute + CefRenderHandlerCppToC::Get(self)->OnPopupSize( + CefBrowserCToCpp::Wrap(browser), + rectVal); +} + +void CEF_CALLBACK render_handler_on_paint(struct _cef_render_handler_t* self, + cef_browser_t* browser, cef_paint_element_type_t type, + size_t dirtyRectsCount, cef_rect_t const* dirtyRects, const void* buffer, + int width, int height) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: dirtyRects; type: simple_vec_byref_const + DCHECK(dirtyRectsCount == 0 || dirtyRects); + if (dirtyRectsCount > 0 && !dirtyRects) + return; + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return; + + // Translate param: dirtyRects; type: simple_vec_byref_const + std::vector dirtyRectsList; + if (dirtyRectsCount > 0) { + for (size_t i = 0; i < dirtyRectsCount; ++i) { + dirtyRectsList.push_back(dirtyRects[i]); + } + } + + // Execute + CefRenderHandlerCppToC::Get(self)->OnPaint( + CefBrowserCToCpp::Wrap(browser), + type, + dirtyRectsList, + buffer, + width, + height); +} + +void CEF_CALLBACK render_handler_on_cursor_change( + struct _cef_render_handler_t* self, cef_browser_t* browser, + cef_cursor_handle_t cursor, cef_cursor_type_t type, + const struct _cef_cursor_info_t* custom_cursor_info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: custom_cursor_info; type: struct_byref_const + DCHECK(custom_cursor_info); + if (!custom_cursor_info) + return; + + // Translate param: custom_cursor_info; type: struct_byref_const + CefCursorInfo custom_cursor_infoObj; + if (custom_cursor_info) + custom_cursor_infoObj.Set(*custom_cursor_info, false); + + // Execute + CefRenderHandlerCppToC::Get(self)->OnCursorChange( + CefBrowserCToCpp::Wrap(browser), + cursor, + type, + custom_cursor_infoObj); +} + +int CEF_CALLBACK render_handler_start_dragging( + struct _cef_render_handler_t* self, cef_browser_t* browser, + cef_drag_data_t* drag_data, cef_drag_operations_mask_t allowed_ops, int x, + int y) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: drag_data; type: refptr_diff + DCHECK(drag_data); + if (!drag_data) + return 0; + + // Execute + bool _retval = CefRenderHandlerCppToC::Get(self)->StartDragging( + CefBrowserCToCpp::Wrap(browser), + CefDragDataCToCpp::Wrap(drag_data), + allowed_ops, + x, + y); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK render_handler_update_drag_cursor( + struct _cef_render_handler_t* self, cef_browser_t* browser, + cef_drag_operations_mask_t operation) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefRenderHandlerCppToC::Get(self)->UpdateDragCursor( + CefBrowserCToCpp::Wrap(browser), + operation); +} + +void CEF_CALLBACK render_handler_on_scroll_offset_changed( + struct _cef_render_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefRenderHandlerCppToC::Get(self)->OnScrollOffsetChanged( + CefBrowserCToCpp::Wrap(browser)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRenderHandlerCppToC::CefRenderHandlerCppToC(CefRenderHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.get_root_screen_rect = render_handler_get_root_screen_rect; + struct_.struct_.get_view_rect = render_handler_get_view_rect; + struct_.struct_.get_screen_point = render_handler_get_screen_point; + struct_.struct_.get_screen_info = render_handler_get_screen_info; + struct_.struct_.on_popup_show = render_handler_on_popup_show; + struct_.struct_.on_popup_size = render_handler_on_popup_size; + struct_.struct_.on_paint = render_handler_on_paint; + struct_.struct_.on_cursor_change = render_handler_on_cursor_change; + struct_.struct_.start_dragging = render_handler_start_dragging; + struct_.struct_.update_drag_cursor = render_handler_update_drag_cursor; + struct_.struct_.on_scroll_offset_changed = + render_handler_on_scroll_offset_changed; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/render_handler_cpptoc.h b/libcef_dll/cpptoc/render_handler_cpptoc.h new file mode 100644 index 000000000..768b6200a --- /dev/null +++ b/libcef_dll/cpptoc/render_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_render_handler.h" +#include "include/capi/cef_render_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefRenderHandlerCppToC + : public CefCppToC { + public: + explicit CefRenderHandlerCppToC(CefRenderHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/render_process_handler_cpptoc.cc b/libcef_dll/cpptoc/render_process_handler_cpptoc.cc new file mode 100644 index 000000000..fdcd81f75 --- /dev/null +++ b/libcef_dll/cpptoc/render_process_handler_cpptoc.cc @@ -0,0 +1,321 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/load_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_process_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/list_value_ctocpp.h" +#include "libcef_dll/ctocpp/process_message_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" +#include "libcef_dll/ctocpp/v8exception_ctocpp.h" +#include "libcef_dll/ctocpp/v8stack_trace_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK render_process_handler_on_render_thread_created( + struct _cef_render_process_handler_t* self, + struct _cef_list_value_t* extra_info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: extra_info; type: refptr_diff + DCHECK(extra_info); + if (!extra_info) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnRenderThreadCreated( + CefListValueCToCpp::Wrap(extra_info)); +} + +void CEF_CALLBACK render_process_handler_on_web_kit_initialized( + struct _cef_render_process_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnWebKitInitialized(); +} + +void CEF_CALLBACK render_process_handler_on_browser_created( + struct _cef_render_process_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnBrowserCreated( + CefBrowserCToCpp::Wrap(browser)); +} + +void CEF_CALLBACK render_process_handler_on_browser_destroyed( + struct _cef_render_process_handler_t* self, cef_browser_t* browser) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnBrowserDestroyed( + CefBrowserCToCpp::Wrap(browser)); +} + +cef_load_handler_t* CEF_CALLBACK render_process_handler_get_load_handler( + struct _cef_render_process_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefRenderProcessHandlerCppToC::Get( + self)->GetLoadHandler(); + + // Return type: refptr_same + return CefLoadHandlerCppToC::Wrap(_retval); +} + +int CEF_CALLBACK render_process_handler_on_before_navigation( + struct _cef_render_process_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, struct _cef_request_t* request, + cef_navigation_type_t navigation_type, int is_redirect) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return 0; + + // Execute + bool _retval = CefRenderProcessHandlerCppToC::Get(self)->OnBeforeNavigation( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefRequestCToCpp::Wrap(request), + navigation_type, + is_redirect?true:false); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK render_process_handler_on_context_created( + struct _cef_render_process_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, struct _cef_v8context_t* context) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: context; type: refptr_diff + DCHECK(context); + if (!context) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnContextCreated( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefV8ContextCToCpp::Wrap(context)); +} + +void CEF_CALLBACK render_process_handler_on_context_released( + struct _cef_render_process_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, struct _cef_v8context_t* context) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: context; type: refptr_diff + DCHECK(context); + if (!context) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnContextReleased( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefV8ContextCToCpp::Wrap(context)); +} + +void CEF_CALLBACK render_process_handler_on_uncaught_exception( + struct _cef_render_process_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, struct _cef_v8context_t* context, + struct _cef_v8exception_t* exception, + struct _cef_v8stack_trace_t* stackTrace) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: context; type: refptr_diff + DCHECK(context); + if (!context) + return; + // Verify param: exception; type: refptr_diff + DCHECK(exception); + if (!exception) + return; + // Verify param: stackTrace; type: refptr_diff + DCHECK(stackTrace); + if (!stackTrace) + return; + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnUncaughtException( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefV8ContextCToCpp::Wrap(context), + CefV8ExceptionCToCpp::Wrap(exception), + CefV8StackTraceCToCpp::Wrap(stackTrace)); +} + +void CEF_CALLBACK render_process_handler_on_focused_node_changed( + struct _cef_render_process_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, cef_domnode_t* node) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Unverified params: frame, node + + // Execute + CefRenderProcessHandlerCppToC::Get(self)->OnFocusedNodeChanged( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefDOMNodeCToCpp::Wrap(node)); +} + +int CEF_CALLBACK render_process_handler_on_process_message_received( + struct _cef_render_process_handler_t* self, cef_browser_t* browser, + cef_process_id_t source_process, cef_process_message_t* message) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: message; type: refptr_diff + DCHECK(message); + if (!message) + return 0; + + // Execute + bool _retval = CefRenderProcessHandlerCppToC::Get( + self)->OnProcessMessageReceived( + CefBrowserCToCpp::Wrap(browser), + source_process, + CefProcessMessageCToCpp::Wrap(message)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRenderProcessHandlerCppToC::CefRenderProcessHandlerCppToC( + CefRenderProcessHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_render_thread_created = + render_process_handler_on_render_thread_created; + struct_.struct_.on_web_kit_initialized = + render_process_handler_on_web_kit_initialized; + struct_.struct_.on_browser_created = + render_process_handler_on_browser_created; + struct_.struct_.on_browser_destroyed = + render_process_handler_on_browser_destroyed; + struct_.struct_.get_load_handler = render_process_handler_get_load_handler; + struct_.struct_.on_before_navigation = + render_process_handler_on_before_navigation; + struct_.struct_.on_context_created = + render_process_handler_on_context_created; + struct_.struct_.on_context_released = + render_process_handler_on_context_released; + struct_.struct_.on_uncaught_exception = + render_process_handler_on_uncaught_exception; + struct_.struct_.on_focused_node_changed = + render_process_handler_on_focused_node_changed; + struct_.struct_.on_process_message_received = + render_process_handler_on_process_message_received; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/render_process_handler_cpptoc.h b/libcef_dll/cpptoc/render_process_handler_cpptoc.h new file mode 100644 index 000000000..d7402383c --- /dev/null +++ b/libcef_dll/cpptoc/render_process_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_RENDER_PROCESS_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_RENDER_PROCESS_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_render_process_handler.h" +#include "include/capi/cef_render_process_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefRenderProcessHandlerCppToC + : public CefCppToC { + public: + explicit CefRenderProcessHandlerCppToC(CefRenderProcessHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RENDER_PROCESS_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/request_context_cpptoc.cc b/libcef_dll/cpptoc/request_context_cpptoc.cc new file mode 100644 index 000000000..8286666f9 --- /dev/null +++ b/libcef_dll/cpptoc/request_context_cpptoc.cc @@ -0,0 +1,112 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/request_context_cpptoc.h" +#include "libcef_dll/ctocpp/request_context_handler_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_request_context_t* cef_request_context_get_global_context() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefRequestContext::GetGlobalContext(); + + // Return type: refptr_same + return CefRequestContextCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_request_context_t* cef_request_context_create_context( + struct _cef_request_context_handler_t* handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: handler + + // Execute + CefRefPtr _retval = CefRequestContext::CreateContext( + CefRequestContextHandlerCToCpp::Wrap(handler)); + + // Return type: refptr_same + return CefRequestContextCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK request_context_is_same(struct _cef_request_context_t* self, + struct _cef_request_context_t* other) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: other; type: refptr_same + DCHECK(other); + if (!other) + return 0; + + // Execute + bool _retval = CefRequestContextCppToC::Get(self)->IsSame( + CefRequestContextCppToC::Unwrap(other)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK request_context_is_global( + struct _cef_request_context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefRequestContextCppToC::Get(self)->IsGlobal(); + + // Return type: bool + return _retval; +} + +struct _cef_request_context_handler_t* CEF_CALLBACK request_context_get_handler( + struct _cef_request_context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefRequestContextCppToC::Get( + self)->GetHandler(); + + // Return type: refptr_diff + return CefRequestContextHandlerCToCpp::Unwrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRequestContextCppToC::CefRequestContextCppToC(CefRequestContext* cls) + : CefCppToC(cls) { + struct_.struct_.is_same = request_context_is_same; + struct_.struct_.is_global = request_context_is_global; + struct_.struct_.get_handler = request_context_get_handler; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/request_context_cpptoc.h b/libcef_dll/cpptoc/request_context_cpptoc.h new file mode 100644 index 000000000..4dcc12251 --- /dev/null +++ b/libcef_dll/cpptoc/request_context_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_REQUEST_CONTEXT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_REQUEST_CONTEXT_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request_context.h" +#include "include/capi/cef_request_context_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefRequestContextCppToC + : public CefCppToC { + public: + explicit CefRequestContextCppToC(CefRequestContext* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_REQUEST_CONTEXT_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/request_context_handler_cpptoc.cc b/libcef_dll/cpptoc/request_context_handler_cpptoc.cc new file mode 100644 index 000000000..001db907f --- /dev/null +++ b/libcef_dll/cpptoc/request_context_handler_cpptoc.cc @@ -0,0 +1,50 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/request_context_handler_cpptoc.h" +#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_cookie_manager_t* CEF_CALLBACK request_context_handler_get_cookie_manager( + struct _cef_request_context_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefRequestContextHandlerCppToC::Get( + self)->GetCookieManager(); + + // Return type: refptr_diff + return CefCookieManagerCToCpp::Unwrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRequestContextHandlerCppToC::CefRequestContextHandlerCppToC( + CefRequestContextHandler* cls) + : CefCppToC(cls) { + struct_.struct_.get_cookie_manager = + request_context_handler_get_cookie_manager; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/request_context_handler_cpptoc.h b/libcef_dll/cpptoc/request_context_handler_cpptoc.h new file mode 100644 index 000000000..958f030e2 --- /dev/null +++ b/libcef_dll/cpptoc/request_context_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_REQUEST_CONTEXT_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_REQUEST_CONTEXT_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request_context_handler.h" +#include "include/capi/cef_request_context_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefRequestContextHandlerCppToC + : public CefCppToC { + public: + explicit CefRequestContextHandlerCppToC(CefRequestContextHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_REQUEST_CONTEXT_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/request_cpptoc.cc b/libcef_dll/cpptoc/request_cpptoc.cc new file mode 100644 index 000000000..1768e3950 --- /dev/null +++ b/libcef_dll/cpptoc/request_cpptoc.cc @@ -0,0 +1,341 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/post_data_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_request_t* cef_request_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefRequest::Create(); + + // Return type: refptr_same + return CefRequestCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK request_is_read_only(struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefRequestCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK request_get_url( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefRequestCppToC::Get(self)->GetURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK request_set_url(struct _cef_request_t* self, + const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefRequestCppToC::Get(self)->SetURL( + CefString(url)); +} + +cef_string_userfree_t CEF_CALLBACK request_get_method( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefRequestCppToC::Get(self)->GetMethod(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK request_set_method(struct _cef_request_t* self, + const cef_string_t* method) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: method; type: string_byref_const + DCHECK(method); + if (!method) + return; + + // Execute + CefRequestCppToC::Get(self)->SetMethod( + CefString(method)); +} + +struct _cef_post_data_t* CEF_CALLBACK request_get_post_data( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefRequestCppToC::Get(self)->GetPostData(); + + // Return type: refptr_same + return CefPostDataCppToC::Wrap(_retval); +} + +void CEF_CALLBACK request_set_post_data(struct _cef_request_t* self, + struct _cef_post_data_t* postData) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: postData; type: refptr_same + DCHECK(postData); + if (!postData) + return; + + // Execute + CefRequestCppToC::Get(self)->SetPostData( + CefPostDataCppToC::Unwrap(postData)); +} + +void CEF_CALLBACK request_get_header_map(struct _cef_request_t* self, + cef_string_multimap_t headerMap) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: headerMap; type: string_map_multi_byref + DCHECK(headerMap); + if (!headerMap) + return; + + // Translate param: headerMap; type: string_map_multi_byref + std::multimap headerMapMultimap; + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + CefRequestCppToC::Get(self)->GetHeaderMap( + headerMapMultimap); + + // Restore param: headerMap; type: string_map_multi_byref + cef_string_multimap_clear(headerMap); + transfer_string_multimap_contents(headerMapMultimap, headerMap); +} + +void CEF_CALLBACK request_set_header_map(struct _cef_request_t* self, + cef_string_multimap_t headerMap) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: headerMap; type: string_map_multi_byref_const + DCHECK(headerMap); + if (!headerMap) + return; + + // Translate param: headerMap; type: string_map_multi_byref_const + std::multimap headerMapMultimap; + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + CefRequestCppToC::Get(self)->SetHeaderMap( + headerMapMultimap); +} + +void CEF_CALLBACK request_set(struct _cef_request_t* self, + const cef_string_t* url, const cef_string_t* method, + struct _cef_post_data_t* postData, cef_string_multimap_t headerMap) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + // Verify param: method; type: string_byref_const + DCHECK(method); + if (!method) + return; + // Verify param: headerMap; type: string_map_multi_byref_const + DCHECK(headerMap); + if (!headerMap) + return; + // Unverified params: postData + + // Translate param: headerMap; type: string_map_multi_byref_const + std::multimap headerMapMultimap; + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + CefRequestCppToC::Get(self)->Set( + CefString(url), + CefString(method), + CefPostDataCppToC::Unwrap(postData), + headerMapMultimap); +} + +int CEF_CALLBACK request_get_flags(struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return UR_FLAG_NONE; + + // Execute + int _retval = CefRequestCppToC::Get(self)->GetFlags(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK request_set_flags(struct _cef_request_t* self, int flags) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefRequestCppToC::Get(self)->SetFlags( + flags); +} + +cef_string_userfree_t CEF_CALLBACK request_get_first_party_for_cookies( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefRequestCppToC::Get(self)->GetFirstPartyForCookies(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK request_set_first_party_for_cookies( + struct _cef_request_t* self, const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefRequestCppToC::Get(self)->SetFirstPartyForCookies( + CefString(url)); +} + +cef_resource_type_t CEF_CALLBACK request_get_resource_type( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return RT_SUB_RESOURCE; + + // Execute + cef_resource_type_t _retval = CefRequestCppToC::Get(self)->GetResourceType(); + + // Return type: simple + return _retval; +} + +cef_transition_type_t CEF_CALLBACK request_get_transition_type( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return TT_EXPLICIT; + + // Execute + cef_transition_type_t _retval = CefRequestCppToC::Get( + self)->GetTransitionType(); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRequestCppToC::CefRequestCppToC(CefRequest* cls) + : CefCppToC(cls) { + struct_.struct_.is_read_only = request_is_read_only; + struct_.struct_.get_url = request_get_url; + struct_.struct_.set_url = request_set_url; + struct_.struct_.get_method = request_get_method; + struct_.struct_.set_method = request_set_method; + struct_.struct_.get_post_data = request_get_post_data; + struct_.struct_.set_post_data = request_set_post_data; + struct_.struct_.get_header_map = request_get_header_map; + struct_.struct_.set_header_map = request_set_header_map; + struct_.struct_.set = request_set; + struct_.struct_.get_flags = request_get_flags; + struct_.struct_.set_flags = request_set_flags; + struct_.struct_.get_first_party_for_cookies = + request_get_first_party_for_cookies; + struct_.struct_.set_first_party_for_cookies = + request_set_first_party_for_cookies; + struct_.struct_.get_resource_type = request_get_resource_type; + struct_.struct_.get_transition_type = request_get_transition_type; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/request_cpptoc.h b/libcef_dll/cpptoc/request_cpptoc.h new file mode 100644 index 000000000..aa3faa5c3 --- /dev/null +++ b/libcef_dll/cpptoc/request_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_REQUEST_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_REQUEST_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request.h" +#include "include/capi/cef_request_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefRequestCppToC + : public CefCppToC { + public: + explicit CefRequestCppToC(CefRequest* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_REQUEST_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/request_handler_cpptoc.cc b/libcef_dll/cpptoc/request_handler_cpptoc.cc new file mode 100644 index 000000000..5d5364dbe --- /dev/null +++ b/libcef_dll/cpptoc/request_handler_cpptoc.cc @@ -0,0 +1,398 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/request_handler_cpptoc.h" +#include "libcef_dll/cpptoc/resource_handler_cpptoc.h" +#include "libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.h" +#include "libcef_dll/ctocpp/auth_callback_ctocpp.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/quota_callback_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/web_plugin_info_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK request_handler_on_before_browse( + struct _cef_request_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, cef_request_t* request, int is_redirect) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return 0; + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnBeforeBrowse( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefRequestCToCpp::Wrap(request), + is_redirect?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK request_handler_on_before_resource_load( + struct _cef_request_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, cef_request_t* request) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return 0; + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnBeforeResourceLoad( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefRequestCToCpp::Wrap(request)); + + // Return type: bool + return _retval; +} + +struct _cef_resource_handler_t* CEF_CALLBACK request_handler_get_resource_handler( + struct _cef_request_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, cef_request_t* request) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return NULL; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return NULL; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return NULL; + + // Execute + CefRefPtr _retval = CefRequestHandlerCppToC::Get( + self)->GetResourceHandler( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefRequestCToCpp::Wrap(request)); + + // Return type: refptr_same + return CefResourceHandlerCppToC::Wrap(_retval); +} + +void CEF_CALLBACK request_handler_on_resource_redirect( + struct _cef_request_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_t* old_url, cef_string_t* new_url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + // Verify param: old_url; type: string_byref_const + DCHECK(old_url); + if (!old_url) + return; + // Verify param: new_url; type: string_byref + DCHECK(new_url); + if (!new_url) + return; + + // Translate param: new_url; type: string_byref + CefString new_urlStr(new_url); + + // Execute + CefRequestHandlerCppToC::Get(self)->OnResourceRedirect( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(old_url), + new_urlStr); +} + +int CEF_CALLBACK request_handler_get_auth_credentials( + struct _cef_request_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, int isProxy, const cef_string_t* host, int port, + const cef_string_t* realm, const cef_string_t* scheme, + cef_auth_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Verify param: host; type: string_byref_const + DCHECK(host); + if (!host) + return 0; + // Verify param: scheme; type: string_byref_const + DCHECK(scheme); + if (!scheme) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + // Unverified params: realm + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->GetAuthCredentials( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + isProxy?true:false, + CefString(host), + port, + CefString(realm), + CefString(scheme), + CefAuthCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK request_handler_on_quota_request( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* origin_url, int64 new_size, + cef_quota_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: origin_url; type: string_byref_const + DCHECK(origin_url); + if (!origin_url) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnQuotaRequest( + CefBrowserCToCpp::Wrap(browser), + CefString(origin_url), + new_size, + CefQuotaCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK request_handler_on_protocol_execution( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* url, int* allow_os_execution) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + // Verify param: allow_os_execution; type: bool_byref + DCHECK(allow_os_execution); + if (!allow_os_execution) + return; + + // Translate param: allow_os_execution; type: bool_byref + bool allow_os_executionBool = ( + allow_os_execution && *allow_os_execution)?true:false; + + // Execute + CefRequestHandlerCppToC::Get(self)->OnProtocolExecution( + CefBrowserCToCpp::Wrap(browser), + CefString(url), + allow_os_executionBool); + + // Restore param: allow_os_execution; type: bool_byref + if (allow_os_execution) + *allow_os_execution = allow_os_executionBool?true:false; +} + +int CEF_CALLBACK request_handler_on_certificate_error( + struct _cef_request_handler_t* self, cef_errorcode_t cert_error, + const cef_string_t* request_url, + cef_allow_certificate_error_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: request_url; type: string_byref_const + DCHECK(request_url); + if (!request_url) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnCertificateError( + cert_error, + CefString(request_url), + CefAllowCertificateErrorCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK request_handler_on_before_plugin_load( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* url, const cef_string_t* policy_url, + struct _cef_web_plugin_info_t* info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return 0; + // Verify param: info; type: refptr_diff + DCHECK(info); + if (!info) + return 0; + // Unverified params: url, policy_url + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnBeforePluginLoad( + CefBrowserCToCpp::Wrap(browser), + CefString(url), + CefString(policy_url), + CefWebPluginInfoCToCpp::Wrap(info)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK request_handler_on_plugin_crashed( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* plugin_path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + // Verify param: plugin_path; type: string_byref_const + DCHECK(plugin_path); + if (!plugin_path) + return; + + // Execute + CefRequestHandlerCppToC::Get(self)->OnPluginCrashed( + CefBrowserCToCpp::Wrap(browser), + CefString(plugin_path)); +} + +void CEF_CALLBACK request_handler_on_render_process_terminated( + struct _cef_request_handler_t* self, cef_browser_t* browser, + cef_termination_status_t status) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + return; + + // Execute + CefRequestHandlerCppToC::Get(self)->OnRenderProcessTerminated( + CefBrowserCToCpp::Wrap(browser), + status); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRequestHandlerCppToC::CefRequestHandlerCppToC(CefRequestHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_browse = request_handler_on_before_browse; + struct_.struct_.on_before_resource_load = + request_handler_on_before_resource_load; + struct_.struct_.get_resource_handler = request_handler_get_resource_handler; + struct_.struct_.on_resource_redirect = request_handler_on_resource_redirect; + struct_.struct_.get_auth_credentials = request_handler_get_auth_credentials; + struct_.struct_.on_quota_request = request_handler_on_quota_request; + struct_.struct_.on_protocol_execution = request_handler_on_protocol_execution; + struct_.struct_.on_certificate_error = request_handler_on_certificate_error; + struct_.struct_.on_before_plugin_load = request_handler_on_before_plugin_load; + struct_.struct_.on_plugin_crashed = request_handler_on_plugin_crashed; + struct_.struct_.on_render_process_terminated = + request_handler_on_render_process_terminated; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/request_handler_cpptoc.h b/libcef_dll/cpptoc/request_handler_cpptoc.h new file mode 100644 index 000000000..828145e54 --- /dev/null +++ b/libcef_dll/cpptoc/request_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_REQUEST_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_REQUEST_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request_handler.h" +#include "include/capi/cef_request_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefRequestHandlerCppToC + : public CefCppToC { + public: + explicit CefRequestHandlerCppToC(CefRequestHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_REQUEST_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc b/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc new file mode 100644 index 000000000..1d30888ec --- /dev/null +++ b/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc @@ -0,0 +1,98 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK resource_bundle_handler_get_localized_string( + struct _cef_resource_bundle_handler_t* self, int message_id, + cef_string_t* string) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: string; type: string_byref + DCHECK(string); + if (!string) + return 0; + + // Translate param: string; type: string_byref + CefString stringStr(string); + + // Execute + bool _retval = CefResourceBundleHandlerCppToC::Get(self)->GetLocalizedString( + message_id, + stringStr); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK resource_bundle_handler_get_data_resource( + struct _cef_resource_bundle_handler_t* self, int resource_id, void** data, + size_t* data_size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: data; type: simple_byref + DCHECK(data); + if (!data) + return 0; + // Verify param: data_size; type: simple_byref + DCHECK(data_size); + if (!data_size) + return 0; + + // Translate param: data; type: simple_byref + void* dataVal = data?*data:NULL; + // Translate param: data_size; type: simple_byref + size_t data_sizeVal = data_size?*data_size:0; + + // Execute + bool _retval = CefResourceBundleHandlerCppToC::Get(self)->GetDataResource( + resource_id, + dataVal, + data_sizeVal); + + // Restore param: data; type: simple_byref + if (data) + *data = dataVal; + // Restore param: data_size; type: simple_byref + if (data_size) + *data_size = data_sizeVal; + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefResourceBundleHandlerCppToC::CefResourceBundleHandlerCppToC( + CefResourceBundleHandler* cls) + : CefCppToC(cls) { + struct_.struct_.get_localized_string = + resource_bundle_handler_get_localized_string; + struct_.struct_.get_data_resource = resource_bundle_handler_get_data_resource; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h b/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h new file mode 100644 index 000000000..2aca1f1ef --- /dev/null +++ b/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_RESOURCE_BUNDLE_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_RESOURCE_BUNDLE_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_resource_bundle_handler.h" +#include "include/capi/cef_resource_bundle_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefResourceBundleHandlerCppToC + : public CefCppToC { + public: + explicit CefResourceBundleHandlerCppToC(CefResourceBundleHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RESOURCE_BUNDLE_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/resource_handler_cpptoc.cc b/libcef_dll/cpptoc/resource_handler_cpptoc.cc new file mode 100644 index 000000000..35a822b69 --- /dev/null +++ b/libcef_dll/cpptoc/resource_handler_cpptoc.cc @@ -0,0 +1,203 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/resource_handler_cpptoc.h" +#include "libcef_dll/ctocpp/callback_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/response_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK resource_handler_process_request( + struct _cef_resource_handler_t* self, cef_request_t* request, + cef_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefResourceHandlerCppToC::Get(self)->ProcessRequest( + CefRequestCToCpp::Wrap(request), + CefCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK resource_handler_get_response_headers( + struct _cef_resource_handler_t* self, struct _cef_response_t* response, + int64* response_length, cef_string_t* redirectUrl) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: response; type: refptr_diff + DCHECK(response); + if (!response) + return; + // Verify param: response_length; type: simple_byref + DCHECK(response_length); + if (!response_length) + return; + // Verify param: redirectUrl; type: string_byref + DCHECK(redirectUrl); + if (!redirectUrl) + return; + + // Translate param: response_length; type: simple_byref + int64 response_lengthVal = response_length?*response_length:0; + // Translate param: redirectUrl; type: string_byref + CefString redirectUrlStr(redirectUrl); + + // Execute + CefResourceHandlerCppToC::Get(self)->GetResponseHeaders( + CefResponseCToCpp::Wrap(response), + response_lengthVal, + redirectUrlStr); + + // Restore param: response_length; type: simple_byref + if (response_length) + *response_length = response_lengthVal; +} + +int CEF_CALLBACK resource_handler_read_response( + struct _cef_resource_handler_t* self, void* data_out, int bytes_to_read, + int* bytes_read, cef_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: data_out; type: simple_byaddr + DCHECK(data_out); + if (!data_out) + return 0; + // Verify param: bytes_read; type: simple_byref + DCHECK(bytes_read); + if (!bytes_read) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Translate param: bytes_read; type: simple_byref + int bytes_readVal = bytes_read?*bytes_read:0; + + // Execute + bool _retval = CefResourceHandlerCppToC::Get(self)->ReadResponse( + data_out, + bytes_to_read, + bytes_readVal, + CefCallbackCToCpp::Wrap(callback)); + + // Restore param: bytes_read; type: simple_byref + if (bytes_read) + *bytes_read = bytes_readVal; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK resource_handler_can_get_cookie( + struct _cef_resource_handler_t* self, const struct _cef_cookie_t* cookie) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: cookie; type: struct_byref_const + DCHECK(cookie); + if (!cookie) + return 0; + + // Translate param: cookie; type: struct_byref_const + CefCookie cookieObj; + if (cookie) + cookieObj.Set(*cookie, false); + + // Execute + bool _retval = CefResourceHandlerCppToC::Get(self)->CanGetCookie( + cookieObj); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK resource_handler_can_set_cookie( + struct _cef_resource_handler_t* self, const struct _cef_cookie_t* cookie) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: cookie; type: struct_byref_const + DCHECK(cookie); + if (!cookie) + return 0; + + // Translate param: cookie; type: struct_byref_const + CefCookie cookieObj; + if (cookie) + cookieObj.Set(*cookie, false); + + // Execute + bool _retval = CefResourceHandlerCppToC::Get(self)->CanSetCookie( + cookieObj); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK resource_handler_cancel( + struct _cef_resource_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefResourceHandlerCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefResourceHandlerCppToC::CefResourceHandlerCppToC(CefResourceHandler* cls) + : CefCppToC(cls) { + struct_.struct_.process_request = resource_handler_process_request; + struct_.struct_.get_response_headers = resource_handler_get_response_headers; + struct_.struct_.read_response = resource_handler_read_response; + struct_.struct_.can_get_cookie = resource_handler_can_get_cookie; + struct_.struct_.can_set_cookie = resource_handler_can_set_cookie; + struct_.struct_.cancel = resource_handler_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/resource_handler_cpptoc.h b/libcef_dll/cpptoc/resource_handler_cpptoc.h new file mode 100644 index 000000000..4549a4cf4 --- /dev/null +++ b/libcef_dll/cpptoc/resource_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_RESOURCE_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_RESOURCE_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_resource_handler.h" +#include "include/capi/cef_resource_handler_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefResourceHandlerCppToC + : public CefCppToC { + public: + explicit CefResourceHandlerCppToC(CefResourceHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RESOURCE_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/response_cpptoc.cc b/libcef_dll/cpptoc/response_cpptoc.cc new file mode 100644 index 000000000..12c6c92cb --- /dev/null +++ b/libcef_dll/cpptoc/response_cpptoc.cc @@ -0,0 +1,224 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/response_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_response_t* cef_response_create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefResponse::Create(); + + // Return type: refptr_same + return CefResponseCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK response_is_read_only(struct _cef_response_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefResponseCppToC::Get(self)->IsReadOnly(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK response_get_status(struct _cef_response_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefResponseCppToC::Get(self)->GetStatus(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK response_set_status(struct _cef_response_t* self, + int status) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefResponseCppToC::Get(self)->SetStatus( + status); +} + +cef_string_userfree_t CEF_CALLBACK response_get_status_text( + struct _cef_response_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefResponseCppToC::Get(self)->GetStatusText(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK response_set_status_text(struct _cef_response_t* self, + const cef_string_t* statusText) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: statusText; type: string_byref_const + DCHECK(statusText); + if (!statusText) + return; + + // Execute + CefResponseCppToC::Get(self)->SetStatusText( + CefString(statusText)); +} + +cef_string_userfree_t CEF_CALLBACK response_get_mime_type( + struct _cef_response_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefResponseCppToC::Get(self)->GetMimeType(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK response_set_mime_type(struct _cef_response_t* self, + const cef_string_t* mimeType) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: mimeType; type: string_byref_const + DCHECK(mimeType); + if (!mimeType) + return; + + // Execute + CefResponseCppToC::Get(self)->SetMimeType( + CefString(mimeType)); +} + +cef_string_userfree_t CEF_CALLBACK response_get_header( + struct _cef_response_t* self, const cef_string_t* name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return NULL; + + // Execute + CefString _retval = CefResponseCppToC::Get(self)->GetHeader( + CefString(name)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +void CEF_CALLBACK response_get_header_map(struct _cef_response_t* self, + cef_string_multimap_t headerMap) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: headerMap; type: string_map_multi_byref + DCHECK(headerMap); + if (!headerMap) + return; + + // Translate param: headerMap; type: string_map_multi_byref + std::multimap headerMapMultimap; + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + CefResponseCppToC::Get(self)->GetHeaderMap( + headerMapMultimap); + + // Restore param: headerMap; type: string_map_multi_byref + cef_string_multimap_clear(headerMap); + transfer_string_multimap_contents(headerMapMultimap, headerMap); +} + +void CEF_CALLBACK response_set_header_map(struct _cef_response_t* self, + cef_string_multimap_t headerMap) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: headerMap; type: string_map_multi_byref_const + DCHECK(headerMap); + if (!headerMap) + return; + + // Translate param: headerMap; type: string_map_multi_byref_const + std::multimap headerMapMultimap; + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + CefResponseCppToC::Get(self)->SetHeaderMap( + headerMapMultimap); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefResponseCppToC::CefResponseCppToC(CefResponse* cls) + : CefCppToC(cls) { + struct_.struct_.is_read_only = response_is_read_only; + struct_.struct_.get_status = response_get_status; + struct_.struct_.set_status = response_set_status; + struct_.struct_.get_status_text = response_get_status_text; + struct_.struct_.set_status_text = response_set_status_text; + struct_.struct_.get_mime_type = response_get_mime_type; + struct_.struct_.set_mime_type = response_set_mime_type; + struct_.struct_.get_header = response_get_header; + struct_.struct_.get_header_map = response_get_header_map; + struct_.struct_.set_header_map = response_set_header_map; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/response_cpptoc.h b/libcef_dll/cpptoc/response_cpptoc.h new file mode 100644 index 000000000..235194e9e --- /dev/null +++ b/libcef_dll/cpptoc/response_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_RESPONSE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_RESPONSE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_response.h" +#include "include/capi/cef_response_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefResponseCppToC + : public CefCppToC { + public: + explicit CefResponseCppToC(CefResponse* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RESPONSE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.cc b/libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.cc new file mode 100644 index 000000000..d668d3a87 --- /dev/null +++ b/libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.cc @@ -0,0 +1,58 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK run_file_dialog_callback_on_file_dialog_dismissed( + struct _cef_run_file_dialog_callback_t* self, int selected_accept_filter, + cef_string_list_t file_paths) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return; + // Unverified params: file_paths + + // Translate param: file_paths; type: string_vec_byref_const + std::vector file_pathsList; + transfer_string_list_contents(file_paths, file_pathsList); + + // Execute + CefRunFileDialogCallbackCppToC::Get(self)->OnFileDialogDismissed( + selected_accept_filter, + file_pathsList); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRunFileDialogCallbackCppToC::CefRunFileDialogCallbackCppToC( + CefRunFileDialogCallback* cls) + : CefCppToC(cls) { + struct_.struct_.on_file_dialog_dismissed = + run_file_dialog_callback_on_file_dialog_dismissed; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h b/libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h new file mode 100644 index 000000000..c590940b1 --- /dev/null +++ b/libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_RUN_FILE_DIALOG_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_RUN_FILE_DIALOG_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefRunFileDialogCallbackCppToC + : public CefCppToC { + public: + explicit CefRunFileDialogCallbackCppToC(CefRunFileDialogCallback* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RUN_FILE_DIALOG_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc new file mode 100644 index 000000000..a05fe790b --- /dev/null +++ b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc @@ -0,0 +1,67 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/resource_handler_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_resource_handler_t* CEF_CALLBACK scheme_handler_factory_create( + struct _cef_scheme_handler_factory_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_t* scheme_name, + cef_request_t* request) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: scheme_name; type: string_byref_const + DCHECK(scheme_name); + if (!scheme_name) + return NULL; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return NULL; + // Unverified params: browser, frame + + // Execute + CefRefPtr _retval = CefSchemeHandlerFactoryCppToC::Get( + self)->Create( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(scheme_name), + CefRequestCToCpp::Wrap(request)); + + // Return type: refptr_same + return CefResourceHandlerCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeHandlerFactoryCppToC::CefSchemeHandlerFactoryCppToC( + CefSchemeHandlerFactory* cls) + : CefCppToC(cls) { + struct_.struct_.create = scheme_handler_factory_create; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h new file mode 100644 index 000000000..6c34c1e13 --- /dev/null +++ b/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_FACTORY_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_FACTORY_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_scheme.h" +#include "include/capi/cef_scheme_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefSchemeHandlerFactoryCppToC + : public CefCppToC { + public: + explicit CefSchemeHandlerFactoryCppToC(CefSchemeHandlerFactory* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_FACTORY_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/scheme_registrar_cpptoc.cc b/libcef_dll/cpptoc/scheme_registrar_cpptoc.cc new file mode 100644 index 000000000..5b2cc2fc5 --- /dev/null +++ b/libcef_dll/cpptoc/scheme_registrar_cpptoc.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/scheme_registrar_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK scheme_registrar_add_custom_scheme( + struct _cef_scheme_registrar_t* self, const cef_string_t* scheme_name, + int is_standard, int is_local, int is_display_isolated) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: scheme_name; type: string_byref_const + DCHECK(scheme_name); + if (!scheme_name) + return 0; + + // Execute + bool _retval = CefSchemeRegistrarCppToC::Get(self)->AddCustomScheme( + CefString(scheme_name), + is_standard?true:false, + is_local?true:false, + is_display_isolated?true:false); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeRegistrarCppToC::CefSchemeRegistrarCppToC(CefSchemeRegistrar* cls) + : CefCppToC(cls) { + struct_.struct_.add_custom_scheme = scheme_registrar_add_custom_scheme; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/scheme_registrar_cpptoc.h b/libcef_dll/cpptoc/scheme_registrar_cpptoc.h new file mode 100644 index 000000000..2c2cfa981 --- /dev/null +++ b/libcef_dll/cpptoc/scheme_registrar_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_SCHEME_REGISTRAR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_SCHEME_REGISTRAR_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_scheme.h" +#include "include/capi/cef_scheme_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefSchemeRegistrarCppToC + : public CefCppToC { + public: + explicit CefSchemeRegistrarCppToC(CefSchemeRegistrar* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_SCHEME_REGISTRAR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/stream_reader_cpptoc.cc b/libcef_dll/cpptoc/stream_reader_cpptoc.cc new file mode 100644 index 000000000..75d826105 --- /dev/null +++ b/libcef_dll/cpptoc/stream_reader_cpptoc.cc @@ -0,0 +1,172 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" +#include "libcef_dll/ctocpp/read_handler_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_file( + const cef_string_t* fileName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(fileName); + if (!fileName) + return NULL; + + // Execute + CefRefPtr _retval = CefStreamReader::CreateForFile( + CefString(fileName)); + + // Return type: refptr_same + return CefStreamReaderCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_data(void* data, + size_t size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return NULL; + + // Execute + CefRefPtr _retval = CefStreamReader::CreateForData( + data, + size); + + // Return type: refptr_same + return CefStreamReaderCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_stream_reader_t* cef_stream_reader_create_for_handler( + cef_read_handler_t* handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: handler; type: refptr_diff + DCHECK(handler); + if (!handler) + return NULL; + + // Execute + CefRefPtr _retval = CefStreamReader::CreateForHandler( + CefReadHandlerCToCpp::Wrap(handler)); + + // Return type: refptr_same + return CefStreamReaderCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +size_t CEF_CALLBACK stream_reader_read(struct _cef_stream_reader_t* self, + void* ptr, size_t size, size_t n) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = CefStreamReaderCppToC::Get(self)->Read( + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK stream_reader_seek(struct _cef_stream_reader_t* self, + int64 offset, int whence) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefStreamReaderCppToC::Get(self)->Seek( + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK stream_reader_tell(struct _cef_stream_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefStreamReaderCppToC::Get(self)->Tell(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK stream_reader_eof(struct _cef_stream_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefStreamReaderCppToC::Get(self)->Eof(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK stream_reader_may_block(struct _cef_stream_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefStreamReaderCppToC::Get(self)->MayBlock(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefStreamReaderCppToC::CefStreamReaderCppToC(CefStreamReader* cls) + : CefCppToC( + cls) { + struct_.struct_.read = stream_reader_read; + struct_.struct_.seek = stream_reader_seek; + struct_.struct_.tell = stream_reader_tell; + struct_.struct_.eof = stream_reader_eof; + struct_.struct_.may_block = stream_reader_may_block; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/stream_reader_cpptoc.h b/libcef_dll/cpptoc/stream_reader_cpptoc.h new file mode 100644 index 000000000..f74b731a4 --- /dev/null +++ b/libcef_dll/cpptoc/stream_reader_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_STREAM_READER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_STREAM_READER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefStreamReaderCppToC + : public CefCppToC { + public: + explicit CefStreamReaderCppToC(CefStreamReader* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_STREAM_READER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/stream_writer_cpptoc.cc b/libcef_dll/cpptoc/stream_writer_cpptoc.cc new file mode 100644 index 000000000..b49931dde --- /dev/null +++ b/libcef_dll/cpptoc/stream_writer_cpptoc.cc @@ -0,0 +1,154 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/stream_writer_cpptoc.h" +#include "libcef_dll/ctocpp/write_handler_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_file( + const cef_string_t* fileName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(fileName); + if (!fileName) + return NULL; + + // Execute + CefRefPtr _retval = CefStreamWriter::CreateForFile( + CefString(fileName)); + + // Return type: refptr_same + return CefStreamWriterCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_stream_writer_t* cef_stream_writer_create_for_handler( + cef_write_handler_t* handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: handler; type: refptr_diff + DCHECK(handler); + if (!handler) + return NULL; + + // Execute + CefRefPtr _retval = CefStreamWriter::CreateForHandler( + CefWriteHandlerCToCpp::Wrap(handler)); + + // Return type: refptr_same + return CefStreamWriterCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +size_t CEF_CALLBACK stream_writer_write(struct _cef_stream_writer_t* self, + const void* ptr, size_t size, size_t n) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = CefStreamWriterCppToC::Get(self)->Write( + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK stream_writer_seek(struct _cef_stream_writer_t* self, + int64 offset, int whence) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefStreamWriterCppToC::Get(self)->Seek( + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK stream_writer_tell(struct _cef_stream_writer_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefStreamWriterCppToC::Get(self)->Tell(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK stream_writer_flush(struct _cef_stream_writer_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefStreamWriterCppToC::Get(self)->Flush(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK stream_writer_may_block(struct _cef_stream_writer_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefStreamWriterCppToC::Get(self)->MayBlock(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefStreamWriterCppToC::CefStreamWriterCppToC(CefStreamWriter* cls) + : CefCppToC( + cls) { + struct_.struct_.write = stream_writer_write; + struct_.struct_.seek = stream_writer_seek; + struct_.struct_.tell = stream_writer_tell; + struct_.struct_.flush = stream_writer_flush; + struct_.struct_.may_block = stream_writer_may_block; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/stream_writer_cpptoc.h b/libcef_dll/cpptoc/stream_writer_cpptoc.h new file mode 100644 index 000000000..85652da85 --- /dev/null +++ b/libcef_dll/cpptoc/stream_writer_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_STREAM_WRITER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_STREAM_WRITER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefStreamWriterCppToC + : public CefCppToC { + public: + explicit CefStreamWriterCppToC(CefStreamWriter* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_STREAM_WRITER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/string_visitor_cpptoc.cc b/libcef_dll/cpptoc/string_visitor_cpptoc.cc new file mode 100644 index 000000000..98d4673de --- /dev/null +++ b/libcef_dll/cpptoc/string_visitor_cpptoc.cc @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/string_visitor_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK string_visitor_visit(struct _cef_string_visitor_t* self, + const cef_string_t* string) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Unverified params: string + + // Execute + CefStringVisitorCppToC::Get(self)->Visit( + CefString(string)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefStringVisitorCppToC::CefStringVisitorCppToC(CefStringVisitor* cls) + : CefCppToC( + cls) { + struct_.struct_.visit = string_visitor_visit; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/string_visitor_cpptoc.h b/libcef_dll/cpptoc/string_visitor_cpptoc.h new file mode 100644 index 000000000..8aa23fde7 --- /dev/null +++ b/libcef_dll/cpptoc/string_visitor_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_STRING_VISITOR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_STRING_VISITOR_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_string_visitor.h" +#include "include/capi/cef_string_visitor_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefStringVisitorCppToC + : public CefCppToC { + public: + explicit CefStringVisitorCppToC(CefStringVisitor* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_STRING_VISITOR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/task_cpptoc.cc b/libcef_dll/cpptoc/task_cpptoc.cc new file mode 100644 index 000000000..a9b5cd258 --- /dev/null +++ b/libcef_dll/cpptoc/task_cpptoc.cc @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/task_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK task_execute(struct _cef_task_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefTaskCppToC::Get(self)->Execute(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefTaskCppToC::CefTaskCppToC(CefTask* cls) + : CefCppToC(cls) { + struct_.struct_.execute = task_execute; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/task_cpptoc.h b/libcef_dll/cpptoc/task_cpptoc.h new file mode 100644 index 000000000..42a6b62d0 --- /dev/null +++ b/libcef_dll/cpptoc/task_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_TASK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_TASK_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_task.h" +#include "include/capi/cef_task_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefTaskCppToC + : public CefCppToC { + public: + explicit CefTaskCppToC(CefTask* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_TASK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/task_runner_cpptoc.cc b/libcef_dll/cpptoc/task_runner_cpptoc.cc new file mode 100644 index 000000000..e83d48baa --- /dev/null +++ b/libcef_dll/cpptoc/task_runner_cpptoc.cc @@ -0,0 +1,153 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/task_runner_cpptoc.h" +#include "libcef_dll/ctocpp/task_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_task_runner_t* cef_task_runner_get_for_current_thread() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefTaskRunner::GetForCurrentThread(); + + // Return type: refptr_same + return CefTaskRunnerCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_task_runner_t* cef_task_runner_get_for_thread( + cef_thread_id_t threadId) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefTaskRunner::GetForThread( + threadId); + + // Return type: refptr_same + return CefTaskRunnerCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK task_runner_is_same(struct _cef_task_runner_t* self, + struct _cef_task_runner_t* that) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: that; type: refptr_same + DCHECK(that); + if (!that) + return 0; + + // Execute + bool _retval = CefTaskRunnerCppToC::Get(self)->IsSame( + CefTaskRunnerCppToC::Unwrap(that)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK task_runner_belongs_to_current_thread( + struct _cef_task_runner_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefTaskRunnerCppToC::Get(self)->BelongsToCurrentThread(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK task_runner_belongs_to_thread(struct _cef_task_runner_t* self, + cef_thread_id_t threadId) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefTaskRunnerCppToC::Get(self)->BelongsToThread( + threadId); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK task_runner_post_task(struct _cef_task_runner_t* self, + cef_task_t* task) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: task; type: refptr_diff + DCHECK(task); + if (!task) + return 0; + + // Execute + bool _retval = CefTaskRunnerCppToC::Get(self)->PostTask( + CefTaskCToCpp::Wrap(task)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK task_runner_post_delayed_task(struct _cef_task_runner_t* self, + cef_task_t* task, int64 delay_ms) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: task; type: refptr_diff + DCHECK(task); + if (!task) + return 0; + + // Execute + bool _retval = CefTaskRunnerCppToC::Get(self)->PostDelayedTask( + CefTaskCToCpp::Wrap(task), + delay_ms); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefTaskRunnerCppToC::CefTaskRunnerCppToC(CefTaskRunner* cls) + : CefCppToC(cls) { + struct_.struct_.is_same = task_runner_is_same; + struct_.struct_.belongs_to_current_thread = + task_runner_belongs_to_current_thread; + struct_.struct_.belongs_to_thread = task_runner_belongs_to_thread; + struct_.struct_.post_task = task_runner_post_task; + struct_.struct_.post_delayed_task = task_runner_post_delayed_task; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/task_runner_cpptoc.h b/libcef_dll/cpptoc/task_runner_cpptoc.h new file mode 100644 index 000000000..579bc0da3 --- /dev/null +++ b/libcef_dll/cpptoc/task_runner_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_TASK_RUNNER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_TASK_RUNNER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_task.h" +#include "include/capi/cef_task_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefTaskRunnerCppToC + : public CefCppToC { + public: + explicit CefTaskRunnerCppToC(CefTaskRunner* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_TASK_RUNNER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/urlrequest_client_cpptoc.cc b/libcef_dll/cpptoc/urlrequest_client_cpptoc.cc new file mode 100644 index 000000000..52d9581a0 --- /dev/null +++ b/libcef_dll/cpptoc/urlrequest_client_cpptoc.cc @@ -0,0 +1,154 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/urlrequest_client_cpptoc.h" +#include "libcef_dll/ctocpp/auth_callback_ctocpp.h" +#include "libcef_dll/ctocpp/urlrequest_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK urlrequest_client_on_request_complete( + struct _cef_urlrequest_client_t* self, cef_urlrequest_t* request) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return; + + // Execute + CefURLRequestClientCppToC::Get(self)->OnRequestComplete( + CefURLRequestCToCpp::Wrap(request)); +} + +void CEF_CALLBACK urlrequest_client_on_upload_progress( + struct _cef_urlrequest_client_t* self, cef_urlrequest_t* request, + int64 current, int64 total) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return; + + // Execute + CefURLRequestClientCppToC::Get(self)->OnUploadProgress( + CefURLRequestCToCpp::Wrap(request), + current, + total); +} + +void CEF_CALLBACK urlrequest_client_on_download_progress( + struct _cef_urlrequest_client_t* self, cef_urlrequest_t* request, + int64 current, int64 total) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return; + + // Execute + CefURLRequestClientCppToC::Get(self)->OnDownloadProgress( + CefURLRequestCToCpp::Wrap(request), + current, + total); +} + +void CEF_CALLBACK urlrequest_client_on_download_data( + struct _cef_urlrequest_client_t* self, cef_urlrequest_t* request, + const void* data, size_t data_length) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return; + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return; + + // Execute + CefURLRequestClientCppToC::Get(self)->OnDownloadData( + CefURLRequestCToCpp::Wrap(request), + data, + data_length); +} + +int CEF_CALLBACK urlrequest_client_get_auth_credentials( + struct _cef_urlrequest_client_t* self, int isProxy, + const cef_string_t* host, int port, const cef_string_t* realm, + const cef_string_t* scheme, cef_auth_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: host; type: string_byref_const + DCHECK(host); + if (!host) + return 0; + // Verify param: scheme; type: string_byref_const + DCHECK(scheme); + if (!scheme) + return 0; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + // Unverified params: realm + + // Execute + bool _retval = CefURLRequestClientCppToC::Get(self)->GetAuthCredentials( + isProxy?true:false, + CefString(host), + port, + CefString(realm), + CefString(scheme), + CefAuthCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefURLRequestClientCppToC::CefURLRequestClientCppToC(CefURLRequestClient* cls) + : CefCppToC(cls) { + struct_.struct_.on_request_complete = urlrequest_client_on_request_complete; + struct_.struct_.on_upload_progress = urlrequest_client_on_upload_progress; + struct_.struct_.on_download_progress = urlrequest_client_on_download_progress; + struct_.struct_.on_download_data = urlrequest_client_on_download_data; + struct_.struct_.get_auth_credentials = urlrequest_client_get_auth_credentials; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/urlrequest_client_cpptoc.h b/libcef_dll/cpptoc/urlrequest_client_cpptoc.h new file mode 100644 index 000000000..4799e21aa --- /dev/null +++ b/libcef_dll/cpptoc/urlrequest_client_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_URLREQUEST_CLIENT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_URLREQUEST_CLIENT_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_urlrequest.h" +#include "include/capi/cef_urlrequest_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefURLRequestClientCppToC + : public CefCppToC { + public: + explicit CefURLRequestClientCppToC(CefURLRequestClient* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_URLREQUEST_CLIENT_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/urlrequest_cpptoc.cc b/libcef_dll/cpptoc/urlrequest_cpptoc.cc new file mode 100644 index 000000000..9f301ea87 --- /dev/null +++ b/libcef_dll/cpptoc/urlrequest_cpptoc.cc @@ -0,0 +1,152 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/response_cpptoc.h" +#include "libcef_dll/cpptoc/urlrequest_cpptoc.h" +#include "libcef_dll/ctocpp/urlrequest_client_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_urlrequest_t* cef_urlrequest_create(cef_request_t* request, + struct _cef_urlrequest_client_t* client) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_same + DCHECK(request); + if (!request) + return NULL; + // Verify param: client; type: refptr_diff + DCHECK(client); + if (!client) + return NULL; + + // Execute + CefRefPtr _retval = CefURLRequest::Create( + CefRequestCppToC::Unwrap(request), + CefURLRequestClientCToCpp::Wrap(client)); + + // Return type: refptr_same + return CefURLRequestCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_request_t* CEF_CALLBACK urlrequest_get_request( + struct _cef_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefURLRequestCppToC::Get(self)->GetRequest(); + + // Return type: refptr_same + return CefRequestCppToC::Wrap(_retval); +} + +struct _cef_urlrequest_client_t* CEF_CALLBACK urlrequest_get_client( + struct _cef_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefURLRequestCppToC::Get( + self)->GetClient(); + + // Return type: refptr_diff + return CefURLRequestClientCToCpp::Unwrap(_retval); +} + +cef_urlrequest_status_t CEF_CALLBACK urlrequest_get_request_status( + struct _cef_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return UR_UNKNOWN; + + // Execute + cef_urlrequest_status_t _retval = CefURLRequestCppToC::Get( + self)->GetRequestStatus(); + + // Return type: simple + return _retval; +} + +cef_errorcode_t CEF_CALLBACK urlrequest_get_request_error( + struct _cef_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return ERR_NONE; + + // Execute + cef_errorcode_t _retval = CefURLRequestCppToC::Get(self)->GetRequestError(); + + // Return type: simple + return _retval; +} + +cef_response_t* CEF_CALLBACK urlrequest_get_response( + struct _cef_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefURLRequestCppToC::Get(self)->GetResponse( + ); + + // Return type: refptr_same + return CefResponseCppToC::Wrap(_retval); +} + +void CEF_CALLBACK urlrequest_cancel(struct _cef_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefURLRequestCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefURLRequestCppToC::CefURLRequestCppToC(CefURLRequest* cls) + : CefCppToC(cls) { + struct_.struct_.get_request = urlrequest_get_request; + struct_.struct_.get_client = urlrequest_get_client; + struct_.struct_.get_request_status = urlrequest_get_request_status; + struct_.struct_.get_request_error = urlrequest_get_request_error; + struct_.struct_.get_response = urlrequest_get_response; + struct_.struct_.cancel = urlrequest_cancel; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/urlrequest_cpptoc.h b/libcef_dll/cpptoc/urlrequest_cpptoc.h new file mode 100644 index 000000000..1c16742e3 --- /dev/null +++ b/libcef_dll/cpptoc/urlrequest_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_URLREQUEST_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_URLREQUEST_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_urlrequest.h" +#include "include/capi/cef_urlrequest_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefURLRequestCppToC + : public CefCppToC { + public: + explicit CefURLRequestCppToC(CefURLRequest* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_URLREQUEST_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8accessor_cpptoc.cc b/libcef_dll/cpptoc/v8accessor_cpptoc.cc new file mode 100644 index 000000000..64ea845ea --- /dev/null +++ b/libcef_dll/cpptoc/v8accessor_cpptoc.cc @@ -0,0 +1,126 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8accessor_cpptoc.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK v8accessor_get(struct _cef_v8accessor_t* self, + const cef_string_t* name, struct _cef_v8value_t* object, + struct _cef_v8value_t** retval, cef_string_t* exception) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return 0; + // Verify param: object; type: refptr_diff + DCHECK(object); + if (!object) + return 0; + // Verify param: retval; type: refptr_diff_byref + DCHECK(retval); + if (!retval) + return 0; + // Verify param: exception; type: string_byref + DCHECK(exception); + if (!exception) + return 0; + + // Translate param: retval; type: refptr_diff_byref + CefRefPtr retvalPtr; + if (retval && *retval) + retvalPtr = CefV8ValueCToCpp::Wrap(*retval); + CefV8Value* retvalOrig = retvalPtr.get(); + // Translate param: exception; type: string_byref + CefString exceptionStr(exception); + + // Execute + bool _retval = CefV8AccessorCppToC::Get(self)->Get( + CefString(name), + CefV8ValueCToCpp::Wrap(object), + retvalPtr, + exceptionStr); + + // Restore param: retval; type: refptr_diff_byref + if (retval) { + if (retvalPtr.get()) { + if (retvalPtr.get() != retvalOrig) { + *retval = CefV8ValueCToCpp::Unwrap(retvalPtr); + } + } else { + *retval = NULL; + } + } + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8accessor_set(struct _cef_v8accessor_t* self, + const cef_string_t* name, struct _cef_v8value_t* object, + struct _cef_v8value_t* value, cef_string_t* exception) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return 0; + // Verify param: object; type: refptr_diff + DCHECK(object); + if (!object) + return 0; + // Verify param: value; type: refptr_diff + DCHECK(value); + if (!value) + return 0; + // Verify param: exception; type: string_byref + DCHECK(exception); + if (!exception) + return 0; + + // Translate param: exception; type: string_byref + CefString exceptionStr(exception); + + // Execute + bool _retval = CefV8AccessorCppToC::Get(self)->Set( + CefString(name), + CefV8ValueCToCpp::Wrap(object), + CefV8ValueCToCpp::Wrap(value), + exceptionStr); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8AccessorCppToC::CefV8AccessorCppToC(CefV8Accessor* cls) + : CefCppToC(cls) { + struct_.struct_.get = v8accessor_get; + struct_.struct_.set = v8accessor_set; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8accessor_cpptoc.h b/libcef_dll/cpptoc/v8accessor_cpptoc.h new file mode 100644 index 000000000..82e534a6e --- /dev/null +++ b/libcef_dll/cpptoc/v8accessor_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8ACCESSOR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8ACCESSOR_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefV8AccessorCppToC + : public CefCppToC { + public: + explicit CefV8AccessorCppToC(CefV8Accessor* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8ACCESSOR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8context_cpptoc.cc b/libcef_dll/cpptoc/v8context_cpptoc.cc new file mode 100644 index 000000000..0cc19fabe --- /dev/null +++ b/libcef_dll/cpptoc/v8context_cpptoc.cc @@ -0,0 +1,261 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/task_runner_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/cpptoc/v8exception_cpptoc.h" +#include "libcef_dll/cpptoc/v8value_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_v8context_t* cef_v8context_get_current_context() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Context::GetCurrentContext(); + + // Return type: refptr_same + return CefV8ContextCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8context_t* cef_v8context_get_entered_context() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Context::GetEnteredContext(); + + // Return type: refptr_same + return CefV8ContextCppToC::Wrap(_retval); +} + +CEF_EXPORT int cef_v8context_in_context() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + bool _retval = CefV8Context::InContext(); + + // Return type: bool + return _retval; +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_task_runner_t* CEF_CALLBACK v8context_get_task_runner( + struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ContextCppToC::Get( + self)->GetTaskRunner(); + + // Return type: refptr_same + return CefTaskRunnerCppToC::Wrap(_retval); +} + +int CEF_CALLBACK v8context_is_valid(struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ContextCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +cef_browser_t* CEF_CALLBACK v8context_get_browser( + struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ContextCppToC::Get(self)->GetBrowser(); + + // Return type: refptr_same + return CefBrowserCppToC::Wrap(_retval); +} + +cef_frame_t* CEF_CALLBACK v8context_get_frame(struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ContextCppToC::Get(self)->GetFrame(); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +struct _cef_v8value_t* CEF_CALLBACK v8context_get_global( + struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ContextCppToC::Get(self)->GetGlobal(); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +int CEF_CALLBACK v8context_enter(struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ContextCppToC::Get(self)->Enter(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8context_exit(struct _cef_v8context_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ContextCppToC::Get(self)->Exit(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8context_is_same(struct _cef_v8context_t* self, + struct _cef_v8context_t* that) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: that; type: refptr_same + DCHECK(that); + if (!that) + return 0; + + // Execute + bool _retval = CefV8ContextCppToC::Get(self)->IsSame( + CefV8ContextCppToC::Unwrap(that)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8context_eval(struct _cef_v8context_t* self, + const cef_string_t* code, struct _cef_v8value_t** retval, + struct _cef_v8exception_t** exception) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: code; type: string_byref_const + DCHECK(code); + if (!code) + return 0; + // Verify param: retval; type: refptr_same_byref + DCHECK(retval); + if (!retval) + return 0; + // Verify param: exception; type: refptr_same_byref + DCHECK(exception); + if (!exception) + return 0; + + // Translate param: retval; type: refptr_same_byref + CefRefPtr retvalPtr; + if (retval && *retval) + retvalPtr = CefV8ValueCppToC::Unwrap(*retval); + CefV8Value* retvalOrig = retvalPtr.get(); + // Translate param: exception; type: refptr_same_byref + CefRefPtr exceptionPtr; + if (exception && *exception) + exceptionPtr = CefV8ExceptionCppToC::Unwrap(*exception); + CefV8Exception* exceptionOrig = exceptionPtr.get(); + + // Execute + bool _retval = CefV8ContextCppToC::Get(self)->Eval( + CefString(code), + retvalPtr, + exceptionPtr); + + // Restore param: retval; type: refptr_same_byref + if (retval) { + if (retvalPtr.get()) { + if (retvalPtr.get() != retvalOrig) { + *retval = CefV8ValueCppToC::Wrap(retvalPtr); + } + } else { + *retval = NULL; + } + } + // Restore param: exception; type: refptr_same_byref + if (exception) { + if (exceptionPtr.get()) { + if (exceptionPtr.get() != exceptionOrig) { + *exception = CefV8ExceptionCppToC::Wrap(exceptionPtr); + } + } else { + *exception = NULL; + } + } + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8ContextCppToC::CefV8ContextCppToC(CefV8Context* cls) + : CefCppToC(cls) { + struct_.struct_.get_task_runner = v8context_get_task_runner; + struct_.struct_.is_valid = v8context_is_valid; + struct_.struct_.get_browser = v8context_get_browser; + struct_.struct_.get_frame = v8context_get_frame; + struct_.struct_.get_global = v8context_get_global; + struct_.struct_.enter = v8context_enter; + struct_.struct_.exit = v8context_exit; + struct_.struct_.is_same = v8context_is_same; + struct_.struct_.eval = v8context_eval; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8context_cpptoc.h b/libcef_dll/cpptoc/v8context_cpptoc.h new file mode 100644 index 000000000..1348cc4f3 --- /dev/null +++ b/libcef_dll/cpptoc/v8context_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8CONTEXT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8CONTEXT_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefV8ContextCppToC + : public CefCppToC { + public: + explicit CefV8ContextCppToC(CefV8Context* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8CONTEXT_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8exception_cpptoc.cc b/libcef_dll/cpptoc/v8exception_cpptoc.cc new file mode 100644 index 000000000..25ecc431b --- /dev/null +++ b/libcef_dll/cpptoc/v8exception_cpptoc.cc @@ -0,0 +1,154 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8exception_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_string_userfree_t CEF_CALLBACK v8exception_get_message( + struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8ExceptionCppToC::Get(self)->GetMessage(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK v8exception_get_source_line( + struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8ExceptionCppToC::Get(self)->GetSourceLine(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK v8exception_get_script_resource_name( + struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8ExceptionCppToC::Get(self)->GetScriptResourceName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK v8exception_get_line_number(struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ExceptionCppToC::Get(self)->GetLineNumber(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8exception_get_start_position( + struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ExceptionCppToC::Get(self)->GetStartPosition(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8exception_get_end_position(struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ExceptionCppToC::Get(self)->GetEndPosition(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8exception_get_start_column(struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ExceptionCppToC::Get(self)->GetStartColumn(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8exception_get_end_column(struct _cef_v8exception_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ExceptionCppToC::Get(self)->GetEndColumn(); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8ExceptionCppToC::CefV8ExceptionCppToC(CefV8Exception* cls) + : CefCppToC(cls) { + struct_.struct_.get_message = v8exception_get_message; + struct_.struct_.get_source_line = v8exception_get_source_line; + struct_.struct_.get_script_resource_name = + v8exception_get_script_resource_name; + struct_.struct_.get_line_number = v8exception_get_line_number; + struct_.struct_.get_start_position = v8exception_get_start_position; + struct_.struct_.get_end_position = v8exception_get_end_position; + struct_.struct_.get_start_column = v8exception_get_start_column; + struct_.struct_.get_end_column = v8exception_get_end_column; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8exception_cpptoc.h b/libcef_dll/cpptoc/v8exception_cpptoc.h new file mode 100644 index 000000000..b24ff42c1 --- /dev/null +++ b/libcef_dll/cpptoc/v8exception_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8EXCEPTION_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8EXCEPTION_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefV8ExceptionCppToC + : public CefCppToC { + public: + explicit CefV8ExceptionCppToC(CefV8Exception* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8EXCEPTION_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8handler_cpptoc.cc b/libcef_dll/cpptoc/v8handler_cpptoc.cc new file mode 100644 index 000000000..59c74cc5c --- /dev/null +++ b/libcef_dll/cpptoc/v8handler_cpptoc.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8handler_cpptoc.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK v8handler_execute(struct _cef_v8handler_t* self, + const cef_string_t* name, struct _cef_v8value_t* object, + size_t argumentsCount, struct _cef_v8value_t* const* arguments, + struct _cef_v8value_t** retval, cef_string_t* exception) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return 0; + // Verify param: object; type: refptr_diff + DCHECK(object); + if (!object) + return 0; + // Verify param: arguments; type: refptr_vec_diff_byref_const + DCHECK(argumentsCount == 0 || arguments); + if (argumentsCount > 0 && !arguments) + return 0; + // Verify param: retval; type: refptr_diff_byref + DCHECK(retval); + if (!retval) + return 0; + // Verify param: exception; type: string_byref + DCHECK(exception); + if (!exception) + return 0; + + // Translate param: arguments; type: refptr_vec_diff_byref_const + std::vector > argumentsList; + if (argumentsCount > 0) { + for (size_t i = 0; i < argumentsCount; ++i) { + argumentsList.push_back(CefV8ValueCToCpp::Wrap(arguments[i])); + } + } + // Translate param: retval; type: refptr_diff_byref + CefRefPtr retvalPtr; + if (retval && *retval) + retvalPtr = CefV8ValueCToCpp::Wrap(*retval); + CefV8Value* retvalOrig = retvalPtr.get(); + // Translate param: exception; type: string_byref + CefString exceptionStr(exception); + + // Execute + bool _retval = CefV8HandlerCppToC::Get(self)->Execute( + CefString(name), + CefV8ValueCToCpp::Wrap(object), + argumentsList, + retvalPtr, + exceptionStr); + + // Restore param: retval; type: refptr_diff_byref + if (retval) { + if (retvalPtr.get()) { + if (retvalPtr.get() != retvalOrig) { + *retval = CefV8ValueCToCpp::Unwrap(retvalPtr); + } + } else { + *retval = NULL; + } + } + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8HandlerCppToC::CefV8HandlerCppToC(CefV8Handler* cls) + : CefCppToC(cls) { + struct_.struct_.execute = v8handler_execute; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8handler_cpptoc.h b/libcef_dll/cpptoc/v8handler_cpptoc.h new file mode 100644 index 000000000..1c113e3b5 --- /dev/null +++ b/libcef_dll/cpptoc/v8handler_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefV8HandlerCppToC + : public CefCppToC { + public: + explicit CefV8HandlerCppToC(CefV8Handler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8stack_frame_cpptoc.cc b/libcef_dll/cpptoc/v8stack_frame_cpptoc.cc new file mode 100644 index 000000000..e30aaef65 --- /dev/null +++ b/libcef_dll/cpptoc/v8stack_frame_cpptoc.cc @@ -0,0 +1,157 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8stack_frame_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK v8stack_frame_is_valid(struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8StackFrameCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK v8stack_frame_get_script_name( + struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8StackFrameCppToC::Get(self)->GetScriptName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK v8stack_frame_get_script_name_or_source_url( + struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8StackFrameCppToC::Get( + self)->GetScriptNameOrSourceURL(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK v8stack_frame_get_function_name( + struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8StackFrameCppToC::Get(self)->GetFunctionName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK v8stack_frame_get_line_number( + struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8StackFrameCppToC::Get(self)->GetLineNumber(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8stack_frame_get_column(struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8StackFrameCppToC::Get(self)->GetColumn(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8stack_frame_is_eval(struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8StackFrameCppToC::Get(self)->IsEval(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8stack_frame_is_constructor( + struct _cef_v8stack_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8StackFrameCppToC::Get(self)->IsConstructor(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8StackFrameCppToC::CefV8StackFrameCppToC(CefV8StackFrame* cls) + : CefCppToC( + cls) { + struct_.struct_.is_valid = v8stack_frame_is_valid; + struct_.struct_.get_script_name = v8stack_frame_get_script_name; + struct_.struct_.get_script_name_or_source_url = + v8stack_frame_get_script_name_or_source_url; + struct_.struct_.get_function_name = v8stack_frame_get_function_name; + struct_.struct_.get_line_number = v8stack_frame_get_line_number; + struct_.struct_.get_column = v8stack_frame_get_column; + struct_.struct_.is_eval = v8stack_frame_is_eval; + struct_.struct_.is_constructor = v8stack_frame_is_constructor; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8stack_frame_cpptoc.h b/libcef_dll/cpptoc/v8stack_frame_cpptoc.h new file mode 100644 index 000000000..32b15e5f0 --- /dev/null +++ b/libcef_dll/cpptoc/v8stack_frame_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8STACK_FRAME_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8STACK_FRAME_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefV8StackFrameCppToC + : public CefCppToC { + public: + explicit CefV8StackFrameCppToC(CefV8StackFrame* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8STACK_FRAME_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8stack_trace_cpptoc.cc b/libcef_dll/cpptoc/v8stack_trace_cpptoc.cc new file mode 100644 index 000000000..5b05b365b --- /dev/null +++ b/libcef_dll/cpptoc/v8stack_trace_cpptoc.cc @@ -0,0 +1,94 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8stack_frame_cpptoc.h" +#include "libcef_dll/cpptoc/v8stack_trace_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_v8stack_trace_t* cef_v8stack_trace_get_current(int frame_limit) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8StackTrace::GetCurrent( + frame_limit); + + // Return type: refptr_same + return CefV8StackTraceCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK v8stack_trace_is_valid(struct _cef_v8stack_trace_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8StackTraceCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8stack_trace_get_frame_count( + struct _cef_v8stack_trace_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8StackTraceCppToC::Get(self)->GetFrameCount(); + + // Return type: simple + return _retval; +} + +struct _cef_v8stack_frame_t* CEF_CALLBACK v8stack_trace_get_frame( + struct _cef_v8stack_trace_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8StackTraceCppToC::Get( + self)->GetFrame( + index); + + // Return type: refptr_same + return CefV8StackFrameCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8StackTraceCppToC::CefV8StackTraceCppToC(CefV8StackTrace* cls) + : CefCppToC( + cls) { + struct_.struct_.is_valid = v8stack_trace_is_valid; + struct_.struct_.get_frame_count = v8stack_trace_get_frame_count; + struct_.struct_.get_frame = v8stack_trace_get_frame; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8stack_trace_cpptoc.h b/libcef_dll/cpptoc/v8stack_trace_cpptoc.h new file mode 100644 index 000000000..c9f81f403 --- /dev/null +++ b/libcef_dll/cpptoc/v8stack_trace_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8STACK_TRACE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8STACK_TRACE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefV8StackTraceCppToC + : public CefCppToC { + public: + explicit CefV8StackTraceCppToC(CefV8StackTrace* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8STACK_TRACE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/v8value_cpptoc.cc b/libcef_dll/cpptoc/v8value_cpptoc.cc new file mode 100644 index 000000000..2b4b9646d --- /dev/null +++ b/libcef_dll/cpptoc/v8value_cpptoc.cc @@ -0,0 +1,973 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/cpptoc/v8exception_cpptoc.h" +#include "libcef_dll/cpptoc/v8value_cpptoc.h" +#include "libcef_dll/ctocpp/base_ctocpp.h" +#include "libcef_dll/ctocpp/v8accessor_ctocpp.h" +#include "libcef_dll/ctocpp/v8handler_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_v8value_t* cef_v8value_create_undefined() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateUndefined(); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_null() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateNull(); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_bool(int value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateBool( + value?true:false); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_int(int32 value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateInt( + value); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_uint(uint32 value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateUInt( + value); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_double(double value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateDouble( + value); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_date(const cef_time_t* date) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: date; type: simple_byref_const + DCHECK(date); + if (!date) + return NULL; + + // Translate param: date; type: simple_byref_const + CefTime dateVal = date?*date:CefTime(); + + // Execute + CefRefPtr _retval = CefV8Value::CreateDate( + dateVal); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_string(const cef_string_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: value + + // Execute + CefRefPtr _retval = CefV8Value::CreateString( + CefString(value)); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_object( + cef_v8accessor_t* accessor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: accessor + + // Execute + CefRefPtr _retval = CefV8Value::CreateObject( + CefV8AccessorCToCpp::Wrap(accessor)); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_array(int length) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefV8Value::CreateArray( + length); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +CEF_EXPORT cef_v8value_t* cef_v8value_create_function(const cef_string_t* name, + cef_v8handler_t* handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(name); + if (!name) + return NULL; + // Verify param: handler; type: refptr_diff + DCHECK(handler); + if (!handler) + return NULL; + + // Execute + CefRefPtr _retval = CefV8Value::CreateFunction( + CefString(name), + CefV8HandlerCToCpp::Wrap(handler)); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK v8value_is_valid(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsValid(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_undefined(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsUndefined(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_null(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsNull(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_bool(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsBool(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_int(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsInt(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_uint(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsUInt(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_double(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsDouble(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_date(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsDate(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_string(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsString(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_object(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsObject(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_array(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsArray(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_function(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsFunction(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_is_same(struct _cef_v8value_t* self, + struct _cef_v8value_t* that) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: that; type: refptr_same + DCHECK(that); + if (!that) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsSame( + CefV8ValueCppToC::Unwrap(that)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_get_bool_value(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->GetBoolValue(); + + // Return type: bool + return _retval; +} + +int32 CEF_CALLBACK v8value_get_int_value(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int32 _retval = CefV8ValueCppToC::Get(self)->GetIntValue(); + + // Return type: simple + return _retval; +} + +uint32 CEF_CALLBACK v8value_get_uint_value(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + uint32 _retval = CefV8ValueCppToC::Get(self)->GetUIntValue(); + + // Return type: simple + return _retval; +} + +double CEF_CALLBACK v8value_get_double_value(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + double _retval = CefV8ValueCppToC::Get(self)->GetDoubleValue(); + + // Return type: simple + return _retval; +} + +cef_time_t CEF_CALLBACK v8value_get_date_value(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return CefTime(); + + // Execute + cef_time_t _retval = CefV8ValueCppToC::Get(self)->GetDateValue(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK v8value_get_string_value( + struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8ValueCppToC::Get(self)->GetStringValue(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK v8value_is_user_created(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->IsUserCreated(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_has_exception(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->HasException(); + + // Return type: bool + return _retval; +} + +cef_v8exception_t* CEF_CALLBACK v8value_get_exception( + struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get(self)->GetException( + ); + + // Return type: refptr_same + return CefV8ExceptionCppToC::Wrap(_retval); +} + +int CEF_CALLBACK v8value_clear_exception(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->ClearException(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_will_rethrow_exceptions(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->WillRethrowExceptions(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_set_rethrow_exceptions(struct _cef_v8value_t* self, + int rethrow) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->SetRethrowExceptions( + rethrow?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_has_value_bykey(struct _cef_v8value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: key + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->HasValue( + CefString(key)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_has_value_byindex(struct _cef_v8value_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->HasValue( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_delete_value_bykey(struct _cef_v8value_t* self, + const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: key + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->DeleteValue( + CefString(key)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_delete_value_byindex(struct _cef_v8value_t* self, + int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->DeleteValue( + index); + + // Return type: bool + return _retval; +} + +struct _cef_v8value_t* CEF_CALLBACK v8value_get_value_bykey( + struct _cef_v8value_t* self, const cef_string_t* key) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Unverified params: key + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get(self)->GetValue( + CefString(key)); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +struct _cef_v8value_t* CEF_CALLBACK v8value_get_value_byindex( + struct _cef_v8value_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get(self)->GetValue( + index); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +int CEF_CALLBACK v8value_set_value_bykey(struct _cef_v8value_t* self, + const cef_string_t* key, struct _cef_v8value_t* value, + cef_v8_propertyattribute_t attribute) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + // Unverified params: key + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->SetValue( + CefString(key), + CefV8ValueCppToC::Unwrap(value), + attribute); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_set_value_byindex(struct _cef_v8value_t* self, + int index, struct _cef_v8value_t* value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + // Verify param: value; type: refptr_same + DCHECK(value); + if (!value) + return 0; + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->SetValue( + index, + CefV8ValueCppToC::Unwrap(value)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_set_value_byaccessor(struct _cef_v8value_t* self, + const cef_string_t* key, cef_v8_accesscontrol_t settings, + cef_v8_propertyattribute_t attribute) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: key + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->SetValue( + CefString(key), + settings, + attribute); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_get_keys(struct _cef_v8value_t* self, + cef_string_list_t keys) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: keys; type: string_vec_byref + DCHECK(keys); + if (!keys) + return 0; + + // Translate param: keys; type: string_vec_byref + std::vector keysList; + transfer_string_list_contents(keys, keysList); + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->GetKeys( + keysList); + + // Restore param: keys; type: string_vec_byref + cef_string_list_clear(keys); + transfer_string_list_contents(keysList, keys); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK v8value_set_user_data(struct _cef_v8value_t* self, + cef_base_t* user_data) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: user_data + + // Execute + bool _retval = CefV8ValueCppToC::Get(self)->SetUserData( + CefBaseCToCpp::Wrap(user_data)); + + // Return type: bool + return _retval; +} + +cef_base_t* CEF_CALLBACK v8value_get_user_data(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get(self)->GetUserData(); + + // Return type: refptr_diff + return CefBaseCToCpp::Unwrap(_retval); +} + +int CEF_CALLBACK v8value_get_externally_allocated_memory( + struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ValueCppToC::Get(self)->GetExternallyAllocatedMemory(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8value_adjust_externally_allocated_memory( + struct _cef_v8value_t* self, int change_in_bytes) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ValueCppToC::Get(self)->AdjustExternallyAllocatedMemory( + change_in_bytes); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK v8value_get_array_length(struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefV8ValueCppToC::Get(self)->GetArrayLength(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK v8value_get_function_name( + struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefV8ValueCppToC::Get(self)->GetFunctionName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_v8handler_t* CEF_CALLBACK v8value_get_function_handler( + struct _cef_v8value_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get( + self)->GetFunctionHandler(); + + // Return type: refptr_diff + return CefV8HandlerCToCpp::Unwrap(_retval); +} + +struct _cef_v8value_t* CEF_CALLBACK v8value_execute_function( + struct _cef_v8value_t* self, struct _cef_v8value_t* object, + size_t argumentsCount, struct _cef_v8value_t* const* arguments) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: arguments; type: refptr_vec_same_byref_const + DCHECK(argumentsCount == 0 || arguments); + if (argumentsCount > 0 && !arguments) + return NULL; + // Unverified params: object + + // Translate param: arguments; type: refptr_vec_same_byref_const + std::vector > argumentsList; + if (argumentsCount > 0) { + for (size_t i = 0; i < argumentsCount; ++i) { + argumentsList.push_back(CefV8ValueCppToC::Unwrap(arguments[i])); + } + } + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get(self)->ExecuteFunction( + CefV8ValueCppToC::Unwrap(object), + argumentsList); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + +struct _cef_v8value_t* CEF_CALLBACK v8value_execute_function_with_context( + struct _cef_v8value_t* self, cef_v8context_t* context, + struct _cef_v8value_t* object, size_t argumentsCount, + struct _cef_v8value_t* const* arguments) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: context; type: refptr_same + DCHECK(context); + if (!context) + return NULL; + // Verify param: arguments; type: refptr_vec_same_byref_const + DCHECK(argumentsCount == 0 || arguments); + if (argumentsCount > 0 && !arguments) + return NULL; + // Unverified params: object + + // Translate param: arguments; type: refptr_vec_same_byref_const + std::vector > argumentsList; + if (argumentsCount > 0) { + for (size_t i = 0; i < argumentsCount; ++i) { + argumentsList.push_back(CefV8ValueCppToC::Unwrap(arguments[i])); + } + } + + // Execute + CefRefPtr _retval = CefV8ValueCppToC::Get( + self)->ExecuteFunctionWithContext( + CefV8ContextCppToC::Unwrap(context), + CefV8ValueCppToC::Unwrap(object), + argumentsList); + + // Return type: refptr_same + return CefV8ValueCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8ValueCppToC::CefV8ValueCppToC(CefV8Value* cls) + : CefCppToC(cls) { + struct_.struct_.is_valid = v8value_is_valid; + struct_.struct_.is_undefined = v8value_is_undefined; + struct_.struct_.is_null = v8value_is_null; + struct_.struct_.is_bool = v8value_is_bool; + struct_.struct_.is_int = v8value_is_int; + struct_.struct_.is_uint = v8value_is_uint; + struct_.struct_.is_double = v8value_is_double; + struct_.struct_.is_date = v8value_is_date; + struct_.struct_.is_string = v8value_is_string; + struct_.struct_.is_object = v8value_is_object; + struct_.struct_.is_array = v8value_is_array; + struct_.struct_.is_function = v8value_is_function; + struct_.struct_.is_same = v8value_is_same; + struct_.struct_.get_bool_value = v8value_get_bool_value; + struct_.struct_.get_int_value = v8value_get_int_value; + struct_.struct_.get_uint_value = v8value_get_uint_value; + struct_.struct_.get_double_value = v8value_get_double_value; + struct_.struct_.get_date_value = v8value_get_date_value; + struct_.struct_.get_string_value = v8value_get_string_value; + struct_.struct_.is_user_created = v8value_is_user_created; + struct_.struct_.has_exception = v8value_has_exception; + struct_.struct_.get_exception = v8value_get_exception; + struct_.struct_.clear_exception = v8value_clear_exception; + struct_.struct_.will_rethrow_exceptions = v8value_will_rethrow_exceptions; + struct_.struct_.set_rethrow_exceptions = v8value_set_rethrow_exceptions; + struct_.struct_.has_value_bykey = v8value_has_value_bykey; + struct_.struct_.has_value_byindex = v8value_has_value_byindex; + struct_.struct_.delete_value_bykey = v8value_delete_value_bykey; + struct_.struct_.delete_value_byindex = v8value_delete_value_byindex; + struct_.struct_.get_value_bykey = v8value_get_value_bykey; + struct_.struct_.get_value_byindex = v8value_get_value_byindex; + struct_.struct_.set_value_bykey = v8value_set_value_bykey; + struct_.struct_.set_value_byindex = v8value_set_value_byindex; + struct_.struct_.set_value_byaccessor = v8value_set_value_byaccessor; + struct_.struct_.get_keys = v8value_get_keys; + struct_.struct_.set_user_data = v8value_set_user_data; + struct_.struct_.get_user_data = v8value_get_user_data; + struct_.struct_.get_externally_allocated_memory = + v8value_get_externally_allocated_memory; + struct_.struct_.adjust_externally_allocated_memory = + v8value_adjust_externally_allocated_memory; + struct_.struct_.get_array_length = v8value_get_array_length; + struct_.struct_.get_function_name = v8value_get_function_name; + struct_.struct_.get_function_handler = v8value_get_function_handler; + struct_.struct_.execute_function = v8value_execute_function; + struct_.struct_.execute_function_with_context = + v8value_execute_function_with_context; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/v8value_cpptoc.h b/libcef_dll/cpptoc/v8value_cpptoc.h new file mode 100644 index 000000000..02135e3c7 --- /dev/null +++ b/libcef_dll/cpptoc/v8value_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_V8VALUE_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8VALUE_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefV8ValueCppToC + : public CefCppToC { + public: + explicit CefV8ValueCppToC(CefV8Value* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8VALUE_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/web_plugin_info_cpptoc.cc b/libcef_dll/cpptoc/web_plugin_info_cpptoc.cc new file mode 100644 index 000000000..ba4fd2b9b --- /dev/null +++ b/libcef_dll/cpptoc/web_plugin_info_cpptoc.cc @@ -0,0 +1,94 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/web_plugin_info_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_string_userfree_t CEF_CALLBACK web_plugin_info_get_name( + struct _cef_web_plugin_info_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefWebPluginInfoCppToC::Get(self)->GetName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK web_plugin_info_get_path( + struct _cef_web_plugin_info_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefWebPluginInfoCppToC::Get(self)->GetPath(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK web_plugin_info_get_version( + struct _cef_web_plugin_info_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefWebPluginInfoCppToC::Get(self)->GetVersion(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK web_plugin_info_get_description( + struct _cef_web_plugin_info_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefWebPluginInfoCppToC::Get(self)->GetDescription(); + + // Return type: string + return _retval.DetachToUserFree(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefWebPluginInfoCppToC::CefWebPluginInfoCppToC(CefWebPluginInfo* cls) + : CefCppToC(cls) { + struct_.struct_.get_name = web_plugin_info_get_name; + struct_.struct_.get_path = web_plugin_info_get_path; + struct_.struct_.get_version = web_plugin_info_get_version; + struct_.struct_.get_description = web_plugin_info_get_description; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/web_plugin_info_cpptoc.h b/libcef_dll/cpptoc/web_plugin_info_cpptoc.h new file mode 100644 index 000000000..ddc14cdc2 --- /dev/null +++ b/libcef_dll/cpptoc/web_plugin_info_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefWebPluginInfoCppToC + : public CefCppToC { + public: + explicit CefWebPluginInfoCppToC(CefWebPluginInfo* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.cc b/libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.cc new file mode 100644 index 000000000..d4874cd35 --- /dev/null +++ b/libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.h" +#include "libcef_dll/ctocpp/web_plugin_info_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK web_plugin_info_visitor_visit( + struct _cef_web_plugin_info_visitor_t* self, cef_web_plugin_info_t* info, + int count, int total) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: info; type: refptr_diff + DCHECK(info); + if (!info) + return 0; + + // Execute + bool _retval = CefWebPluginInfoVisitorCppToC::Get(self)->Visit( + CefWebPluginInfoCToCpp::Wrap(info), + count, + total); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefWebPluginInfoVisitorCppToC::CefWebPluginInfoVisitorCppToC( + CefWebPluginInfoVisitor* cls) + : CefCppToC(cls) { + struct_.struct_.visit = web_plugin_info_visitor_visit; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.h b/libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.h new file mode 100644 index 000000000..8e4156171 --- /dev/null +++ b/libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_VISITOR_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_VISITOR_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefWebPluginInfoVisitorCppToC + : public CefCppToC { + public: + explicit CefWebPluginInfoVisitorCppToC(CefWebPluginInfoVisitor* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_VISITOR_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.cc b/libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.cc new file mode 100644 index 000000000..2e42864dd --- /dev/null +++ b/libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK web_plugin_unstable_callback_is_unstable( + struct _cef_web_plugin_unstable_callback_t* self, const cef_string_t* path, + int unstable) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + + // Execute + CefWebPluginUnstableCallbackCppToC::Get(self)->IsUnstable( + CefString(path), + unstable?true:false); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefWebPluginUnstableCallbackCppToC::CefWebPluginUnstableCallbackCppToC( + CefWebPluginUnstableCallback* cls) + : CefCppToC( + cls) { + struct_.struct_.is_unstable = web_plugin_unstable_callback_is_unstable; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.h b/libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.h new file mode 100644 index 000000000..583c4d5e1 --- /dev/null +++ b/libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.h @@ -0,0 +1,37 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_UNSTABLE_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_UNSTABLE_CALLBACK_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefWebPluginUnstableCallbackCppToC + : public CefCppToC { + public: + explicit CefWebPluginUnstableCallbackCppToC( + CefWebPluginUnstableCallback* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_UNSTABLE_CALLBACK_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/write_handler_cpptoc.cc b/libcef_dll/cpptoc/write_handler_cpptoc.cc new file mode 100644 index 000000000..dcf12daf6 --- /dev/null +++ b/libcef_dll/cpptoc/write_handler_cpptoc.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/write_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +size_t CEF_CALLBACK write_handler_write(struct _cef_write_handler_t* self, + const void* ptr, size_t size, size_t n) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = CefWriteHandlerCppToC::Get(self)->Write( + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK write_handler_seek(struct _cef_write_handler_t* self, + int64 offset, int whence) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefWriteHandlerCppToC::Get(self)->Seek( + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK write_handler_tell(struct _cef_write_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefWriteHandlerCppToC::Get(self)->Tell(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK write_handler_flush(struct _cef_write_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefWriteHandlerCppToC::Get(self)->Flush(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK write_handler_may_block(struct _cef_write_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefWriteHandlerCppToC::Get(self)->MayBlock(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefWriteHandlerCppToC::CefWriteHandlerCppToC(CefWriteHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.write = write_handler_write; + struct_.struct_.seek = write_handler_seek; + struct_.struct_.tell = write_handler_tell; + struct_.struct_.flush = write_handler_flush; + struct_.struct_.may_block = write_handler_may_block; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/write_handler_cpptoc.h b/libcef_dll/cpptoc/write_handler_cpptoc.h new file mode 100644 index 000000000..a945c4b63 --- /dev/null +++ b/libcef_dll/cpptoc/write_handler_cpptoc.h @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_WRITE_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_WRITE_HANDLER_CPPTOC_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed wrapper-side only. +class CefWriteHandlerCppToC + : public CefCppToC { + public: + explicit CefWriteHandlerCppToC(CefWriteHandler* cls); +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WRITE_HANDLER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/xml_reader_cpptoc.cc b/libcef_dll/cpptoc/xml_reader_cpptoc.cc new file mode 100644 index 000000000..a23830d0c --- /dev/null +++ b/libcef_dll/cpptoc/xml_reader_cpptoc.cc @@ -0,0 +1,558 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" +#include "libcef_dll/cpptoc/xml_reader_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_xml_reader_t* cef_xml_reader_create(cef_stream_reader_t* stream, + cef_xml_encoding_type_t encodingType, const cef_string_t* URI) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: stream; type: refptr_same + DCHECK(stream); + if (!stream) + return NULL; + // Verify param: URI; type: string_byref_const + DCHECK(URI); + if (!URI) + return NULL; + + // Execute + CefRefPtr _retval = CefXmlReader::Create( + CefStreamReaderCppToC::Unwrap(stream), + encodingType, + CefString(URI)); + + // Return type: refptr_same + return CefXmlReaderCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK xml_reader_move_to_next_node(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToNextNode(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_close(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->Close(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_has_error(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->HasError(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_error( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetError(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_xml_node_type_t CEF_CALLBACK xml_reader_get_type( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return XML_NODE_UNSUPPORTED; + + // Execute + cef_xml_node_type_t _retval = CefXmlReaderCppToC::Get(self)->GetType(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK xml_reader_get_depth(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefXmlReaderCppToC::Get(self)->GetDepth(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_local_name( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetLocalName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_prefix( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetPrefix(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_qualified_name( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetQualifiedName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_namespace_uri( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetNamespaceURI(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_base_uri( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetBaseURI(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_xml_lang( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetXmlLang(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK xml_reader_is_empty_element(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->IsEmptyElement(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_has_value(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->HasValue(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_value( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetValue(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK xml_reader_has_attributes(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->HasAttributes(); + + // Return type: bool + return _retval; +} + +size_t CEF_CALLBACK xml_reader_get_attribute_count( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + size_t _retval = CefXmlReaderCppToC::Get(self)->GetAttributeCount(); + + // Return type: simple + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_attribute_byindex( + struct _cef_xml_reader_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetAttribute( + index); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_attribute_byqname( + struct _cef_xml_reader_t* self, const cef_string_t* qualifiedName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: qualifiedName; type: string_byref_const + DCHECK(qualifiedName); + if (!qualifiedName) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetAttribute( + CefString(qualifiedName)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_attribute_bylname( + struct _cef_xml_reader_t* self, const cef_string_t* localName, + const cef_string_t* namespaceURI) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + // Verify param: localName; type: string_byref_const + DCHECK(localName); + if (!localName) + return NULL; + // Verify param: namespaceURI; type: string_byref_const + DCHECK(namespaceURI); + if (!namespaceURI) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetAttribute( + CefString(localName), + CefString(namespaceURI)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_inner_xml( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetInnerXml(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK xml_reader_get_outer_xml( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefXmlReaderCppToC::Get(self)->GetOuterXml(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int CEF_CALLBACK xml_reader_get_line_number(struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int _retval = CefXmlReaderCppToC::Get(self)->GetLineNumber(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK xml_reader_move_to_attribute_byindex( + struct _cef_xml_reader_t* self, int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToAttribute( + index); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_move_to_attribute_byqname( + struct _cef_xml_reader_t* self, const cef_string_t* qualifiedName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: qualifiedName; type: string_byref_const + DCHECK(qualifiedName); + if (!qualifiedName) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToAttribute( + CefString(qualifiedName)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_move_to_attribute_bylname( + struct _cef_xml_reader_t* self, const cef_string_t* localName, + const cef_string_t* namespaceURI) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: localName; type: string_byref_const + DCHECK(localName); + if (!localName) + return 0; + // Verify param: namespaceURI; type: string_byref_const + DCHECK(namespaceURI); + if (!namespaceURI) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToAttribute( + CefString(localName), + CefString(namespaceURI)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_move_to_first_attribute( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToFirstAttribute(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_move_to_next_attribute( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToNextAttribute(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK xml_reader_move_to_carrying_element( + struct _cef_xml_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefXmlReaderCppToC::Get(self)->MoveToCarryingElement(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefXmlReaderCppToC::CefXmlReaderCppToC(CefXmlReader* cls) + : CefCppToC(cls) { + struct_.struct_.move_to_next_node = xml_reader_move_to_next_node; + struct_.struct_.close = xml_reader_close; + struct_.struct_.has_error = xml_reader_has_error; + struct_.struct_.get_error = xml_reader_get_error; + struct_.struct_.get_type = xml_reader_get_type; + struct_.struct_.get_depth = xml_reader_get_depth; + struct_.struct_.get_local_name = xml_reader_get_local_name; + struct_.struct_.get_prefix = xml_reader_get_prefix; + struct_.struct_.get_qualified_name = xml_reader_get_qualified_name; + struct_.struct_.get_namespace_uri = xml_reader_get_namespace_uri; + struct_.struct_.get_base_uri = xml_reader_get_base_uri; + struct_.struct_.get_xml_lang = xml_reader_get_xml_lang; + struct_.struct_.is_empty_element = xml_reader_is_empty_element; + struct_.struct_.has_value = xml_reader_has_value; + struct_.struct_.get_value = xml_reader_get_value; + struct_.struct_.has_attributes = xml_reader_has_attributes; + struct_.struct_.get_attribute_count = xml_reader_get_attribute_count; + struct_.struct_.get_attribute_byindex = xml_reader_get_attribute_byindex; + struct_.struct_.get_attribute_byqname = xml_reader_get_attribute_byqname; + struct_.struct_.get_attribute_bylname = xml_reader_get_attribute_bylname; + struct_.struct_.get_inner_xml = xml_reader_get_inner_xml; + struct_.struct_.get_outer_xml = xml_reader_get_outer_xml; + struct_.struct_.get_line_number = xml_reader_get_line_number; + struct_.struct_.move_to_attribute_byindex = + xml_reader_move_to_attribute_byindex; + struct_.struct_.move_to_attribute_byqname = + xml_reader_move_to_attribute_byqname; + struct_.struct_.move_to_attribute_bylname = + xml_reader_move_to_attribute_bylname; + struct_.struct_.move_to_first_attribute = xml_reader_move_to_first_attribute; + struct_.struct_.move_to_next_attribute = xml_reader_move_to_next_attribute; + struct_.struct_.move_to_carrying_element = + xml_reader_move_to_carrying_element; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/xml_reader_cpptoc.h b/libcef_dll/cpptoc/xml_reader_cpptoc.h new file mode 100644 index 000000000..29a79239d --- /dev/null +++ b/libcef_dll/cpptoc/xml_reader_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_XML_READER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_XML_READER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_xml_reader.h" +#include "include/capi/cef_xml_reader_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefXmlReaderCppToC + : public CefCppToC { + public: + explicit CefXmlReaderCppToC(CefXmlReader* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_XML_READER_CPPTOC_H_ + diff --git a/libcef_dll/cpptoc/zip_reader_cpptoc.cc b/libcef_dll/cpptoc/zip_reader_cpptoc.cc new file mode 100644 index 000000000..0fd9b17c1 --- /dev/null +++ b/libcef_dll/cpptoc/zip_reader_cpptoc.cc @@ -0,0 +1,249 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" +#include "libcef_dll/cpptoc/zip_reader_cpptoc.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_zip_reader_t* cef_zip_reader_create( + cef_stream_reader_t* stream) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: stream; type: refptr_same + DCHECK(stream); + if (!stream) + return NULL; + + // Execute + CefRefPtr _retval = CefZipReader::Create( + CefStreamReaderCppToC::Unwrap(stream)); + + // Return type: refptr_same + return CefZipReaderCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK zip_reader_move_to_first_file(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->MoveToFirstFile(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK zip_reader_move_to_next_file(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->MoveToNextFile(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK zip_reader_move_to_file(struct _cef_zip_reader_t* self, + const cef_string_t* fileName, int caseSensitive) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: fileName; type: string_byref_const + DCHECK(fileName); + if (!fileName) + return 0; + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->MoveToFile( + CefString(fileName), + caseSensitive?true:false); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK zip_reader_close(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->Close(); + + // Return type: bool + return _retval; +} + +cef_string_userfree_t CEF_CALLBACK zip_reader_get_file_name( + struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefZipReaderCppToC::Get(self)->GetFileName(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +int64 CEF_CALLBACK zip_reader_get_file_size(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefZipReaderCppToC::Get(self)->GetFileSize(); + + // Return type: simple + return _retval; +} + +time_t CEF_CALLBACK zip_reader_get_file_last_modified( + struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + time_t _retval = CefZipReaderCppToC::Get(self)->GetFileLastModified(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK zip_reader_open_file(struct _cef_zip_reader_t* self, + const cef_string_t* password) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Unverified params: password + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->OpenFile( + CefString(password)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK zip_reader_close_file(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->CloseFile(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK zip_reader_read_file(struct _cef_zip_reader_t* self, + void* buffer, size_t bufferSize) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return 0; + + // Execute + int _retval = CefZipReaderCppToC::Get(self)->ReadFile( + buffer, + bufferSize); + + // Return type: simple + return _retval; +} + +int64 CEF_CALLBACK zip_reader_tell(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + int64 _retval = CefZipReaderCppToC::Get(self)->Tell(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK zip_reader_eof(struct _cef_zip_reader_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefZipReaderCppToC::Get(self)->Eof(); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefZipReaderCppToC::CefZipReaderCppToC(CefZipReader* cls) + : CefCppToC(cls) { + struct_.struct_.move_to_first_file = zip_reader_move_to_first_file; + struct_.struct_.move_to_next_file = zip_reader_move_to_next_file; + struct_.struct_.move_to_file = zip_reader_move_to_file; + struct_.struct_.close = zip_reader_close; + struct_.struct_.get_file_name = zip_reader_get_file_name; + struct_.struct_.get_file_size = zip_reader_get_file_size; + struct_.struct_.get_file_last_modified = zip_reader_get_file_last_modified; + struct_.struct_.open_file = zip_reader_open_file; + struct_.struct_.close_file = zip_reader_close_file; + struct_.struct_.read_file = zip_reader_read_file; + struct_.struct_.tell = zip_reader_tell; + struct_.struct_.eof = zip_reader_eof; +} + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCppToC::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/cpptoc/zip_reader_cpptoc.h b/libcef_dll/cpptoc/zip_reader_cpptoc.h new file mode 100644 index 000000000..0b78ab1b7 --- /dev/null +++ b/libcef_dll/cpptoc/zip_reader_cpptoc.h @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CPPTOC_ZIP_READER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_ZIP_READER_CPPTOC_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_zip_reader.h" +#include "include/capi/cef_zip_reader_capi.h" +#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +// This class may be instantiated and accessed DLL-side only. +class CefZipReaderCppToC + : public CefCppToC { + public: + explicit CefZipReaderCppToC(CefZipReader* cls); +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_ZIP_READER_CPPTOC_H_ + diff --git a/libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.cc b/libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.cc new file mode 100644 index 000000000..9cf77f041 --- /dev/null +++ b/libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.cc @@ -0,0 +1,35 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefAllowCertificateErrorCallbackCToCpp::Continue(bool allow) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cont(struct_, + allow); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.h b/libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.h new file mode 100644 index 000000000..17f1c2357 --- /dev/null +++ b/libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_ALLOW_CERTIFICATE_ERROR_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_ALLOW_CERTIFICATE_ERROR_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request_handler.h" +#include "include/capi/cef_request_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefAllowCertificateErrorCallbackCToCpp + : public CefCToCpp { + public: + explicit CefAllowCertificateErrorCallbackCToCpp( + cef_allow_certificate_error_callback_t* str) + : CefCToCpp(str) {} + + // CefAllowCertificateErrorCallback methods + virtual void Continue(bool allow) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_ALLOW_CERTIFICATE_ERROR_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/app_ctocpp.cc b/libcef_dll/ctocpp/app_ctocpp.cc new file mode 100644 index 000000000..cf1c779e6 --- /dev/null +++ b/libcef_dll/ctocpp/app_ctocpp.cc @@ -0,0 +1,106 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/command_line_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_registrar_cpptoc.h" +#include "libcef_dll/ctocpp/app_ctocpp.h" +#include "libcef_dll/ctocpp/browser_process_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_process_handler_ctocpp.h" +#include "libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefAppCToCpp::OnBeforeCommandLineProcessing(const CefString& process_type, + CefRefPtr command_line) { + if (CEF_MEMBER_MISSING(struct_, on_before_command_line_processing)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: command_line; type: refptr_diff + DCHECK(command_line.get()); + if (!command_line.get()) + return; + // Unverified params: process_type + + // Execute + struct_->on_before_command_line_processing(struct_, + process_type.GetStruct(), + CefCommandLineCppToC::Wrap(command_line)); +} + +void CefAppCToCpp::OnRegisterCustomSchemes( + CefRefPtr registrar) { + if (CEF_MEMBER_MISSING(struct_, on_register_custom_schemes)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: registrar; type: refptr_diff + DCHECK(registrar.get()); + if (!registrar.get()) + return; + + // Execute + struct_->on_register_custom_schemes(struct_, + CefSchemeRegistrarCppToC::Wrap(registrar)); +} + +CefRefPtr CefAppCToCpp::GetResourceBundleHandler() { + if (CEF_MEMBER_MISSING(struct_, get_resource_bundle_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_resource_bundle_handler_t* _retval = struct_->get_resource_bundle_handler( + struct_); + + // Return type: refptr_same + return CefResourceBundleHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefAppCToCpp::GetBrowserProcessHandler() { + if (CEF_MEMBER_MISSING(struct_, get_browser_process_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_browser_process_handler_t* _retval = struct_->get_browser_process_handler( + struct_); + + // Return type: refptr_same + return CefBrowserProcessHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefAppCToCpp::GetRenderProcessHandler() { + if (CEF_MEMBER_MISSING(struct_, get_render_process_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_render_process_handler_t* _retval = struct_->get_render_process_handler( + struct_); + + // Return type: refptr_same + return CefRenderProcessHandlerCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/app_ctocpp.h b/libcef_dll/ctocpp/app_ctocpp.h new file mode 100644 index 000000000..7c870d060 --- /dev/null +++ b/libcef_dll/ctocpp/app_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_APP_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_APP_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_app.h" +#include "include/capi/cef_app_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefAppCToCpp + : public CefCToCpp { + public: + explicit CefAppCToCpp(cef_app_t* str) + : CefCToCpp(str) {} + + // CefApp methods + void OnBeforeCommandLineProcessing(const CefString& process_type, + CefRefPtr command_line) override; + void OnRegisterCustomSchemes( + CefRefPtr registrar) override; + CefRefPtr GetResourceBundleHandler() override; + CefRefPtr GetBrowserProcessHandler() override; + CefRefPtr GetRenderProcessHandler() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_APP_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/auth_callback_ctocpp.cc b/libcef_dll/ctocpp/auth_callback_ctocpp.cc new file mode 100644 index 000000000..ce5a8307d --- /dev/null +++ b/libcef_dll/ctocpp/auth_callback_ctocpp.cc @@ -0,0 +1,55 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/auth_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefAuthCallbackCToCpp::Continue(const CefString& username, + const CefString& password) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: username; type: string_byref_const + DCHECK(!username.empty()); + if (username.empty()) + return; + // Verify param: password; type: string_byref_const + DCHECK(!password.empty()); + if (password.empty()) + return; + + // Execute + struct_->cont(struct_, + username.GetStruct(), + password.GetStruct()); +} + +void CefAuthCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/auth_callback_ctocpp.h b/libcef_dll/ctocpp/auth_callback_ctocpp.h new file mode 100644 index 000000000..e4b8b4e7f --- /dev/null +++ b/libcef_dll/ctocpp/auth_callback_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_AUTH_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_AUTH_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_auth_callback.h" +#include "include/capi/cef_auth_callback_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefAuthCallbackCToCpp + : public CefCToCpp { + public: + explicit CefAuthCallbackCToCpp(cef_auth_callback_t* str) + : CefCToCpp( + str) {} + + // CefAuthCallback methods + virtual void Continue(const CefString& username, + const CefString& password) OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_AUTH_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/base_ctocpp.h b/libcef_dll/ctocpp/base_ctocpp.h new file mode 100644 index 000000000..f085183b1 --- /dev/null +++ b/libcef_dll/ctocpp/base_ctocpp.h @@ -0,0 +1,101 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DLL_CTOCPP_BASE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_BASE_CTOCPP_H_ +#pragma once + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_base.h" +#include "include/capi/cef_base_capi.h" + + +// CefCToCpp implementation for CefBase. +class CefBaseCToCpp : public CefBase { + public: + // Use this method to create a wrapper class instance for a structure + // received from the other side. + static CefRefPtr Wrap(cef_base_t* s) { + if (!s) + return NULL; + + // Wrap their structure with the CefCToCpp object. + CefBaseCToCpp* wrapper = new CefBaseCToCpp(s); + // Put the wrapper object in a smart pointer. + CefRefPtr wrapperPtr(wrapper); + // Release the reference that was added to the CefCppToC wrapper object on + // the other side before their structure was passed to us. + wrapper->UnderlyingRelease(); + // Return the smart pointer. + return wrapperPtr; + } + + // Use this method to retrieve the underlying structure from a wrapper class + // instance for return back to the other side. + static cef_base_t* Unwrap(CefRefPtr c) { + if (!c.get()) + return NULL; + + // Cast the object to our wrapper class type. + CefBaseCToCpp* wrapper = static_cast(c.get()); + // Add a reference to the CefCppToC wrapper object on the other side that + // will be released once the structure is received. + wrapper->UnderlyingAddRef(); + // Return their original structure. + return wrapper->GetStruct(); + } + + explicit CefBaseCToCpp(cef_base_t* str) + : struct_(str) { + DCHECK(str); + } + virtual ~CefBaseCToCpp() {} + + // If returning the structure across the DLL boundary you should call + // UnderlyingAddRef() on this wrapping CefCToCpp object. On the other side of + // the DLL boundary, call Release() on the CefCppToC object. + cef_base_t* GetStruct() { return struct_; } + + // CefBase methods increment/decrement reference counts on both this object + // and the underlying wrapped structure. + void AddRef() const { + UnderlyingAddRef(); + ref_count_.AddRef(); + } + bool Release() const { + UnderlyingRelease(); + if (ref_count_.Release()) { + delete this; + return true; + } + return false; + } + bool HasOneRef() const { return ref_count_.HasOneRef(); } + + // Increment/decrement reference counts on only the underlying class. + void UnderlyingAddRef() const { + if (struct_->add_ref) + struct_->add_ref(struct_); + } + bool UnderlyingRelease() const { + if (!struct_->release) + return false; + return struct_->release(struct_) ? true : false; + } + bool UnderlyingHasOneRef() const { + if (!struct_->has_one_ref) + return false; + return struct_->has_one_ref(struct_) ? true : false; + } + + private: + CefRefCount ref_count_; + cef_base_t* struct_; + + DISALLOW_COPY_AND_ASSIGN(CefBaseCToCpp); +}; + + +#endif // CEF_LIBCEF_DLL_CTOCPP_BASE_CTOCPP_H_ diff --git a/libcef_dll/ctocpp/before_download_callback_ctocpp.cc b/libcef_dll/ctocpp/before_download_callback_ctocpp.cc new file mode 100644 index 000000000..602df784d --- /dev/null +++ b/libcef_dll/ctocpp/before_download_callback_ctocpp.cc @@ -0,0 +1,39 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/before_download_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefBeforeDownloadCallbackCToCpp::Continue(const CefString& download_path, + bool show_dialog) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: download_path + + // Execute + struct_->cont(struct_, + download_path.GetStruct(), + show_dialog); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/ctocpp/before_download_callback_ctocpp.h b/libcef_dll/ctocpp/before_download_callback_ctocpp.h new file mode 100644 index 000000000..25042ba8e --- /dev/null +++ b/libcef_dll/ctocpp/before_download_callback_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_BEFORE_DOWNLOAD_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_BEFORE_DOWNLOAD_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_download_handler.h" +#include "include/capi/cef_download_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefBeforeDownloadCallbackCToCpp + : public CefCToCpp { + public: + explicit CefBeforeDownloadCallbackCToCpp(cef_before_download_callback_t* str) + : CefCToCpp(str) {} + + // CefBeforeDownloadCallback methods + virtual void Continue(const CefString& download_path, + bool show_dialog) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_BEFORE_DOWNLOAD_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/binary_value_ctocpp.cc b/libcef_dll/ctocpp/binary_value_ctocpp.cc new file mode 100644 index 000000000..c09ac1fbc --- /dev/null +++ b/libcef_dll/ctocpp/binary_value_ctocpp.cc @@ -0,0 +1,118 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/binary_value_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefBinaryValue::Create(const void* data, + size_t data_size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return NULL; + + // Execute + cef_binary_value_t* _retval = cef_binary_value_create( + data, + data_size); + + // Return type: refptr_same + return CefBinaryValueCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefBinaryValueCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefBinaryValueCToCpp::IsOwned() { + if (CEF_MEMBER_MISSING(struct_, is_owned)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_owned(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefBinaryValueCToCpp::Copy() { + if (CEF_MEMBER_MISSING(struct_, copy)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_binary_value_t* _retval = struct_->copy(struct_); + + // Return type: refptr_same + return CefBinaryValueCToCpp::Wrap(_retval); +} + +size_t CefBinaryValueCToCpp::GetSize() { + if (CEF_MEMBER_MISSING(struct_, get_size)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_size(struct_); + + // Return type: simple + return _retval; +} + +size_t CefBinaryValueCToCpp::GetData(void* buffer, size_t buffer_size, + size_t data_offset) { + if (CEF_MEMBER_MISSING(struct_, get_data)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return 0; + + // Execute + size_t _retval = struct_->get_data(struct_, + buffer, + buffer_size, + data_offset); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/binary_value_ctocpp.h b/libcef_dll/ctocpp/binary_value_ctocpp.h new file mode 100644 index 000000000..23c3622c8 --- /dev/null +++ b/libcef_dll/ctocpp/binary_value_ctocpp.h @@ -0,0 +1,46 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_BINARY_VALUE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_BINARY_VALUE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_values.h" +#include "include/capi/cef_values_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefBinaryValueCToCpp + : public CefCToCpp { + public: + explicit CefBinaryValueCToCpp(cef_binary_value_t* str) + : CefCToCpp( + str) {} + + // CefBinaryValue methods + virtual bool IsValid() OVERRIDE; + virtual bool IsOwned() OVERRIDE; + virtual CefRefPtr Copy() OVERRIDE; + virtual size_t GetSize() OVERRIDE; + virtual size_t GetData(void* buffer, size_t buffer_size, + size_t data_offset) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_BINARY_VALUE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/browser_ctocpp.cc b/libcef_dll/ctocpp/browser_ctocpp.cc new file mode 100644 index 000000000..c97e3e75f --- /dev/null +++ b/libcef_dll/ctocpp/browser_ctocpp.cc @@ -0,0 +1,340 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/browser_host_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/process_message_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefBrowserCToCpp::GetHost() { + if (CEF_MEMBER_MISSING(struct_, get_host)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_browser_host_t* _retval = struct_->get_host(struct_); + + // Return type: refptr_same + return CefBrowserHostCToCpp::Wrap(_retval); +} + +bool CefBrowserCToCpp::CanGoBack() { + if (CEF_MEMBER_MISSING(struct_, can_go_back)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->can_go_back(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserCToCpp::GoBack() { + if (CEF_MEMBER_MISSING(struct_, go_back)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->go_back(struct_); +} + +bool CefBrowserCToCpp::CanGoForward() { + if (CEF_MEMBER_MISSING(struct_, can_go_forward)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->can_go_forward(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserCToCpp::GoForward() { + if (CEF_MEMBER_MISSING(struct_, go_forward)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->go_forward(struct_); +} + +bool CefBrowserCToCpp::IsLoading() { + if (CEF_MEMBER_MISSING(struct_, is_loading)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_loading(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserCToCpp::Reload() { + if (CEF_MEMBER_MISSING(struct_, reload)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->reload(struct_); +} + +void CefBrowserCToCpp::ReloadIgnoreCache() { + if (CEF_MEMBER_MISSING(struct_, reload_ignore_cache)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->reload_ignore_cache(struct_); +} + +void CefBrowserCToCpp::StopLoad() { + if (CEF_MEMBER_MISSING(struct_, stop_load)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->stop_load(struct_); +} + +int CefBrowserCToCpp::GetIdentifier() { + if (CEF_MEMBER_MISSING(struct_, get_identifier)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_identifier(struct_); + + // Return type: simple + return _retval; +} + +bool CefBrowserCToCpp::IsSame(CefRefPtr that) { + if (CEF_MEMBER_MISSING(struct_, is_same)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: that; type: refptr_same + DCHECK(that.get()); + if (!that.get()) + return false; + + // Execute + int _retval = struct_->is_same(struct_, + CefBrowserCToCpp::Unwrap(that)); + + // Return type: bool + return _retval?true:false; +} + +bool CefBrowserCToCpp::IsPopup() { + if (CEF_MEMBER_MISSING(struct_, is_popup)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_popup(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefBrowserCToCpp::HasDocument() { + if (CEF_MEMBER_MISSING(struct_, has_document)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_document(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefBrowserCToCpp::GetMainFrame() { + if (CEF_MEMBER_MISSING(struct_, get_main_frame)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_frame_t* _retval = struct_->get_main_frame(struct_); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +CefRefPtr CefBrowserCToCpp::GetFocusedFrame() { + if (CEF_MEMBER_MISSING(struct_, get_focused_frame)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_frame_t* _retval = struct_->get_focused_frame(struct_); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +CefRefPtr CefBrowserCToCpp::GetFrame(int64 identifier) { + if (CEF_MEMBER_MISSING(struct_, get_frame_byident)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_frame_t* _retval = struct_->get_frame_byident(struct_, + identifier); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +CefRefPtr CefBrowserCToCpp::GetFrame(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, get_frame)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: name + + // Execute + cef_frame_t* _retval = struct_->get_frame(struct_, + name.GetStruct()); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +size_t CefBrowserCToCpp::GetFrameCount() { + if (CEF_MEMBER_MISSING(struct_, get_frame_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_frame_count(struct_); + + // Return type: simple + return _retval; +} + +void CefBrowserCToCpp::GetFrameIdentifiers(std::vector& identifiers) { + if (CEF_MEMBER_MISSING(struct_, get_frame_identifiers)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: identifiers; type: simple_vec_byref + size_t identifiersSize = identifiers.size(); + size_t identifiersCount = std::max(GetFrameCount(), identifiersSize); + int64* identifiersList = NULL; + if (identifiersCount > 0) { + identifiersList = new int64[identifiersCount]; + DCHECK(identifiersList); + if (identifiersList) { + memset(identifiersList, 0, sizeof(int64)*identifiersCount); + } + if (identifiersList && identifiersSize > 0) { + for (size_t i = 0; i < identifiersSize; ++i) { + identifiersList[i] = identifiers[i]; + } + } + } + + // Execute + struct_->get_frame_identifiers(struct_, + &identifiersCount, + identifiersList); + + // Restore param:identifiers; type: simple_vec_byref + identifiers.clear(); + if (identifiersCount > 0 && identifiersList) { + for (size_t i = 0; i < identifiersCount; ++i) { + identifiers.push_back(identifiersList[i]); + } + delete [] identifiersList; + } +} + +void CefBrowserCToCpp::GetFrameNames(std::vector& names) { + if (CEF_MEMBER_MISSING(struct_, get_frame_names)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: names; type: string_vec_byref + cef_string_list_t namesList = cef_string_list_alloc(); + DCHECK(namesList); + if (namesList) + transfer_string_list_contents(names, namesList); + + // Execute + struct_->get_frame_names(struct_, + namesList); + + // Restore param:names; type: string_vec_byref + if (namesList) { + names.clear(); + transfer_string_list_contents(namesList, names); + cef_string_list_free(namesList); + } +} + +bool CefBrowserCToCpp::SendProcessMessage(CefProcessId target_process, + CefRefPtr message) { + if (CEF_MEMBER_MISSING(struct_, send_process_message)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: message; type: refptr_same + DCHECK(message.get()); + if (!message.get()) + return false; + + // Execute + int _retval = struct_->send_process_message(struct_, + target_process, + CefProcessMessageCToCpp::Unwrap(message)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/browser_ctocpp.h b/libcef_dll/ctocpp/browser_ctocpp.h new file mode 100644 index 000000000..c18bfd602 --- /dev/null +++ b/libcef_dll/ctocpp/browser_ctocpp.h @@ -0,0 +1,63 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_BROWSER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_BROWSER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefBrowserCToCpp + : public CefCToCpp { + public: + explicit CefBrowserCToCpp(cef_browser_t* str) + : CefCToCpp(str) {} + + // CefBrowser methods + virtual CefRefPtr GetHost() OVERRIDE; + virtual bool CanGoBack() OVERRIDE; + virtual void GoBack() OVERRIDE; + virtual bool CanGoForward() OVERRIDE; + virtual void GoForward() OVERRIDE; + virtual bool IsLoading() OVERRIDE; + virtual void Reload() OVERRIDE; + virtual void ReloadIgnoreCache() OVERRIDE; + virtual void StopLoad() OVERRIDE; + virtual int GetIdentifier() OVERRIDE; + virtual bool IsSame(CefRefPtr that) OVERRIDE; + virtual bool IsPopup() OVERRIDE; + virtual bool HasDocument() OVERRIDE; + virtual CefRefPtr GetMainFrame() OVERRIDE; + virtual CefRefPtr GetFocusedFrame() OVERRIDE; + virtual CefRefPtr GetFrame(int64 identifier) OVERRIDE; + virtual CefRefPtr GetFrame(const CefString& name) OVERRIDE; + virtual size_t GetFrameCount() OVERRIDE; + virtual void GetFrameIdentifiers(std::vector& identifiers) OVERRIDE; + virtual void GetFrameNames(std::vector& names) OVERRIDE; + virtual bool SendProcessMessage(CefProcessId target_process, + CefRefPtr message) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_BROWSER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/browser_host_ctocpp.cc b/libcef_dll/ctocpp/browser_host_ctocpp.cc new file mode 100644 index 000000000..1d6b220e3 --- /dev/null +++ b/libcef_dll/ctocpp/browser_host_ctocpp.cc @@ -0,0 +1,651 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/client_cpptoc.h" +#include "libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h" +#include "libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/browser_host_ctocpp.h" +#include "libcef_dll/ctocpp/drag_data_ctocpp.h" +#include "libcef_dll/ctocpp/request_context_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +bool CefBrowserHost::CreateBrowser(const CefWindowInfo& windowInfo, + CefRefPtr client, const CefString& url, + const CefBrowserSettings& settings, + CefRefPtr request_context) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: client, url, request_context + + // Execute + int _retval = cef_browser_host_create_browser( + &windowInfo, + CefClientCppToC::Wrap(client), + url.GetStruct(), + &settings, + CefRequestContextCToCpp::Unwrap(request_context)); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefBrowserHost::CreateBrowserSync( + const CefWindowInfo& windowInfo, CefRefPtr client, + const CefString& url, const CefBrowserSettings& settings, + CefRefPtr request_context) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: client, url, request_context + + // Execute + cef_browser_t* _retval = cef_browser_host_create_browser_sync( + &windowInfo, + CefClientCppToC::Wrap(client), + url.GetStruct(), + &settings, + CefRequestContextCToCpp::Unwrap(request_context)); + + // Return type: refptr_same + return CefBrowserCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefBrowserHostCToCpp::GetBrowser() { + if (CEF_MEMBER_MISSING(struct_, get_browser)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_browser_t* _retval = struct_->get_browser(struct_); + + // Return type: refptr_same + return CefBrowserCToCpp::Wrap(_retval); +} + +void CefBrowserHostCToCpp::CloseBrowser(bool force_close) { + if (CEF_MEMBER_MISSING(struct_, close_browser)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->close_browser(struct_, + force_close); +} + +void CefBrowserHostCToCpp::SetFocus(bool focus) { + if (CEF_MEMBER_MISSING(struct_, set_focus)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_focus(struct_, + focus); +} + +void CefBrowserHostCToCpp::SetWindowVisibility(bool visible) { + if (CEF_MEMBER_MISSING(struct_, set_window_visibility)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_window_visibility(struct_, + visible); +} + +CefWindowHandle CefBrowserHostCToCpp::GetWindowHandle() { + if (CEF_MEMBER_MISSING(struct_, get_window_handle)) + return kNullWindowHandle; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_window_handle_t _retval = struct_->get_window_handle(struct_); + + // Return type: simple + return _retval; +} + +CefWindowHandle CefBrowserHostCToCpp::GetOpenerWindowHandle() { + if (CEF_MEMBER_MISSING(struct_, get_opener_window_handle)) + return kNullWindowHandle; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_window_handle_t _retval = struct_->get_opener_window_handle(struct_); + + // Return type: simple + return _retval; +} + +CefRefPtr CefBrowserHostCToCpp::GetClient() { + if (CEF_MEMBER_MISSING(struct_, get_client)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_client_t* _retval = struct_->get_client(struct_); + + // Return type: refptr_diff + return CefClientCppToC::Unwrap(_retval); +} + +CefRefPtr CefBrowserHostCToCpp::GetRequestContext() { + if (CEF_MEMBER_MISSING(struct_, get_request_context)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_request_context_t* _retval = struct_->get_request_context(struct_); + + // Return type: refptr_same + return CefRequestContextCToCpp::Wrap(_retval); +} + +double CefBrowserHostCToCpp::GetZoomLevel() { + if (CEF_MEMBER_MISSING(struct_, get_zoom_level)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + double _retval = struct_->get_zoom_level(struct_); + + // Return type: simple + return _retval; +} + +void CefBrowserHostCToCpp::SetZoomLevel(double zoomLevel) { + if (CEF_MEMBER_MISSING(struct_, set_zoom_level)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_zoom_level(struct_, + zoomLevel); +} + +void CefBrowserHostCToCpp::RunFileDialog(FileDialogMode mode, + const CefString& title, const CefString& default_file_path, + const std::vector& accept_filters, int selected_accept_filter, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, run_file_dialog)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return; + // Unverified params: title, default_file_path, accept_filters + + // Translate param: accept_filters; type: string_vec_byref_const + cef_string_list_t accept_filtersList = cef_string_list_alloc(); + DCHECK(accept_filtersList); + if (accept_filtersList) + transfer_string_list_contents(accept_filters, accept_filtersList); + + // Execute + struct_->run_file_dialog(struct_, + mode, + title.GetStruct(), + default_file_path.GetStruct(), + accept_filtersList, + selected_accept_filter, + CefRunFileDialogCallbackCppToC::Wrap(callback)); + + // Restore param:accept_filters; type: string_vec_byref_const + if (accept_filtersList) + cef_string_list_free(accept_filtersList); +} + +void CefBrowserHostCToCpp::StartDownload(const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, start_download)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->start_download(struct_, + url.GetStruct()); +} + +void CefBrowserHostCToCpp::Print() { + if (CEF_MEMBER_MISSING(struct_, print)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->print(struct_); +} + +void CefBrowserHostCToCpp::Find(int identifier, const CefString& searchText, + bool forward, bool matchCase, bool findNext) { + if (CEF_MEMBER_MISSING(struct_, find)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: searchText; type: string_byref_const + DCHECK(!searchText.empty()); + if (searchText.empty()) + return; + + // Execute + struct_->find(struct_, + identifier, + searchText.GetStruct(), + forward, + matchCase, + findNext); +} + +void CefBrowserHostCToCpp::StopFinding(bool clearSelection) { + if (CEF_MEMBER_MISSING(struct_, stop_finding)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->stop_finding(struct_, + clearSelection); +} + +void CefBrowserHostCToCpp::ShowDevTools(const CefWindowInfo& windowInfo, + CefRefPtr client, const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) { + if (CEF_MEMBER_MISSING(struct_, show_dev_tools)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: client; type: refptr_diff + DCHECK(client.get()); + if (!client.get()) + return; + // Unverified params: inspect_element_at + + // Execute + struct_->show_dev_tools(struct_, + &windowInfo, + CefClientCppToC::Wrap(client), + &settings, + &inspect_element_at); +} + +void CefBrowserHostCToCpp::CloseDevTools() { + if (CEF_MEMBER_MISSING(struct_, close_dev_tools)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->close_dev_tools(struct_); +} + +void CefBrowserHostCToCpp::GetNavigationEntries( + CefRefPtr visitor, bool current_only) { + if (CEF_MEMBER_MISSING(struct_, get_navigation_entries)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return; + + // Execute + struct_->get_navigation_entries(struct_, + CefNavigationEntryVisitorCppToC::Wrap(visitor), + current_only); +} + +void CefBrowserHostCToCpp::SetMouseCursorChangeDisabled(bool disabled) { + if (CEF_MEMBER_MISSING(struct_, set_mouse_cursor_change_disabled)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_mouse_cursor_change_disabled(struct_, + disabled); +} + +bool CefBrowserHostCToCpp::IsMouseCursorChangeDisabled() { + if (CEF_MEMBER_MISSING(struct_, is_mouse_cursor_change_disabled)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_mouse_cursor_change_disabled(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserHostCToCpp::ReplaceMisspelling(const CefString& word) { + if (CEF_MEMBER_MISSING(struct_, replace_misspelling)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: word; type: string_byref_const + DCHECK(!word.empty()); + if (word.empty()) + return; + + // Execute + struct_->replace_misspelling(struct_, + word.GetStruct()); +} + +void CefBrowserHostCToCpp::AddWordToDictionary(const CefString& word) { + if (CEF_MEMBER_MISSING(struct_, add_word_to_dictionary)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: word; type: string_byref_const + DCHECK(!word.empty()); + if (word.empty()) + return; + + // Execute + struct_->add_word_to_dictionary(struct_, + word.GetStruct()); +} + +bool CefBrowserHostCToCpp::IsWindowRenderingDisabled() { + if (CEF_MEMBER_MISSING(struct_, is_window_rendering_disabled)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_window_rendering_disabled(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserHostCToCpp::WasResized() { + if (CEF_MEMBER_MISSING(struct_, was_resized)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->was_resized(struct_); +} + +void CefBrowserHostCToCpp::WasHidden(bool hidden) { + if (CEF_MEMBER_MISSING(struct_, was_hidden)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->was_hidden(struct_, + hidden); +} + +void CefBrowserHostCToCpp::NotifyScreenInfoChanged() { + if (CEF_MEMBER_MISSING(struct_, notify_screen_info_changed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->notify_screen_info_changed(struct_); +} + +void CefBrowserHostCToCpp::Invalidate(PaintElementType type) { + if (CEF_MEMBER_MISSING(struct_, invalidate)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->invalidate(struct_, + type); +} + +void CefBrowserHostCToCpp::SendKeyEvent(const CefKeyEvent& event) { + if (CEF_MEMBER_MISSING(struct_, send_key_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_key_event(struct_, + &event); +} + +void CefBrowserHostCToCpp::SendMouseClickEvent(const CefMouseEvent& event, + MouseButtonType type, bool mouseUp, int clickCount) { + if (CEF_MEMBER_MISSING(struct_, send_mouse_click_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_mouse_click_event(struct_, + &event, + type, + mouseUp, + clickCount); +} + +void CefBrowserHostCToCpp::SendMouseMoveEvent(const CefMouseEvent& event, + bool mouseLeave) { + if (CEF_MEMBER_MISSING(struct_, send_mouse_move_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_mouse_move_event(struct_, + &event, + mouseLeave); +} + +void CefBrowserHostCToCpp::SendMouseWheelEvent(const CefMouseEvent& event, + int deltaX, int deltaY) { + if (CEF_MEMBER_MISSING(struct_, send_mouse_wheel_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_mouse_wheel_event(struct_, + &event, + deltaX, + deltaY); +} + +void CefBrowserHostCToCpp::SendFocusEvent(bool setFocus) { + if (CEF_MEMBER_MISSING(struct_, send_focus_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_focus_event(struct_, + setFocus); +} + +void CefBrowserHostCToCpp::SendCaptureLostEvent() { + if (CEF_MEMBER_MISSING(struct_, send_capture_lost_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_capture_lost_event(struct_); +} + +void CefBrowserHostCToCpp::NotifyMoveOrResizeStarted() { + if (CEF_MEMBER_MISSING(struct_, notify_move_or_resize_started)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->notify_move_or_resize_started(struct_); +} + +CefTextInputContext CefBrowserHostCToCpp::GetNSTextInputContext() { + if (CEF_MEMBER_MISSING(struct_, get_nstext_input_context)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_text_input_context_t _retval = struct_->get_nstext_input_context(struct_); + + // Return type: simple + return _retval; +} + +void CefBrowserHostCToCpp::HandleKeyEventBeforeTextInputClient( + CefEventHandle keyEvent) { + if (CEF_MEMBER_MISSING(struct_, handle_key_event_before_text_input_client)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->handle_key_event_before_text_input_client(struct_, + keyEvent); +} + +void CefBrowserHostCToCpp::HandleKeyEventAfterTextInputClient( + CefEventHandle keyEvent) { + if (CEF_MEMBER_MISSING(struct_, handle_key_event_after_text_input_client)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->handle_key_event_after_text_input_client(struct_, + keyEvent); +} + +void CefBrowserHostCToCpp::DragTargetDragEnter(CefRefPtr drag_data, + const CefMouseEvent& event, DragOperationsMask allowed_ops) { + if (CEF_MEMBER_MISSING(struct_, drag_target_drag_enter)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: drag_data; type: refptr_same + DCHECK(drag_data.get()); + if (!drag_data.get()) + return; + + // Execute + struct_->drag_target_drag_enter(struct_, + CefDragDataCToCpp::Unwrap(drag_data), + &event, + allowed_ops); +} + +void CefBrowserHostCToCpp::DragTargetDragOver(const CefMouseEvent& event, + DragOperationsMask allowed_ops) { + if (CEF_MEMBER_MISSING(struct_, drag_target_drag_over)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->drag_target_drag_over(struct_, + &event, + allowed_ops); +} + +void CefBrowserHostCToCpp::DragTargetDragLeave() { + if (CEF_MEMBER_MISSING(struct_, drag_target_drag_leave)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->drag_target_drag_leave(struct_); +} + +void CefBrowserHostCToCpp::DragTargetDrop(const CefMouseEvent& event) { + if (CEF_MEMBER_MISSING(struct_, drag_target_drop)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->drag_target_drop(struct_, + &event); +} + +void CefBrowserHostCToCpp::DragSourceEndedAt(int x, int y, + DragOperationsMask op) { + if (CEF_MEMBER_MISSING(struct_, drag_source_ended_at)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->drag_source_ended_at(struct_, + x, + y, + op); +} + +void CefBrowserHostCToCpp::DragSourceSystemDragEnded() { + if (CEF_MEMBER_MISSING(struct_, drag_source_system_drag_ended)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->drag_source_system_drag_ended(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/browser_host_ctocpp.h b/libcef_dll/ctocpp/browser_host_ctocpp.h new file mode 100644 index 000000000..9c5290ee3 --- /dev/null +++ b/libcef_dll/ctocpp/browser_host_ctocpp.h @@ -0,0 +1,101 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_BROWSER_HOST_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_BROWSER_HOST_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefBrowserHostCToCpp + : public CefCToCpp { + public: + explicit CefBrowserHostCToCpp(cef_browser_host_t* str) + : CefCToCpp( + str) {} + + // CefBrowserHost methods + virtual CefRefPtr GetBrowser() OVERRIDE; + virtual void CloseBrowser(bool force_close) OVERRIDE; + virtual void SetFocus(bool focus) OVERRIDE; + virtual void SetWindowVisibility(bool visible) OVERRIDE; + virtual CefWindowHandle GetWindowHandle() OVERRIDE; + virtual CefWindowHandle GetOpenerWindowHandle() OVERRIDE; + virtual CefRefPtr GetClient() OVERRIDE; + virtual CefRefPtr GetRequestContext() OVERRIDE; + virtual double GetZoomLevel() OVERRIDE; + virtual void SetZoomLevel(double zoomLevel) OVERRIDE; + virtual void RunFileDialog(FileDialogMode mode, const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, int selected_accept_filter, + CefRefPtr callback) OVERRIDE; + virtual void StartDownload(const CefString& url) OVERRIDE; + virtual void Print() OVERRIDE; + virtual void Find(int identifier, const CefString& searchText, bool forward, + bool matchCase, bool findNext) OVERRIDE; + virtual void StopFinding(bool clearSelection) OVERRIDE; + virtual void ShowDevTools(const CefWindowInfo& windowInfo, + CefRefPtr client, const CefBrowserSettings& settings, + const CefPoint& inspect_element_at) OVERRIDE; + virtual void CloseDevTools() OVERRIDE; + virtual void GetNavigationEntries( + CefRefPtr visitor, + bool current_only) OVERRIDE; + virtual void SetMouseCursorChangeDisabled(bool disabled) OVERRIDE; + virtual bool IsMouseCursorChangeDisabled() OVERRIDE; + virtual void ReplaceMisspelling(const CefString& word) OVERRIDE; + virtual void AddWordToDictionary(const CefString& word) OVERRIDE; + virtual bool IsWindowRenderingDisabled() OVERRIDE; + virtual void WasResized() OVERRIDE; + virtual void WasHidden(bool hidden) OVERRIDE; + virtual void NotifyScreenInfoChanged() OVERRIDE; + virtual void Invalidate(PaintElementType type) OVERRIDE; + virtual void SendKeyEvent(const CefKeyEvent& event) OVERRIDE; + virtual void SendMouseClickEvent(const CefMouseEvent& event, + MouseButtonType type, bool mouseUp, int clickCount) OVERRIDE; + virtual void SendMouseMoveEvent(const CefMouseEvent& event, + bool mouseLeave) OVERRIDE; + virtual void SendMouseWheelEvent(const CefMouseEvent& event, int deltaX, + int deltaY) OVERRIDE; + virtual void SendFocusEvent(bool setFocus) OVERRIDE; + virtual void SendCaptureLostEvent() OVERRIDE; + virtual void NotifyMoveOrResizeStarted() OVERRIDE; + virtual CefTextInputContext GetNSTextInputContext() OVERRIDE; + virtual void HandleKeyEventBeforeTextInputClient( + CefEventHandle keyEvent) OVERRIDE; + virtual void HandleKeyEventAfterTextInputClient( + CefEventHandle keyEvent) OVERRIDE; + virtual void DragTargetDragEnter(CefRefPtr drag_data, + const CefMouseEvent& event, DragOperationsMask allowed_ops) OVERRIDE; + virtual void DragTargetDragOver(const CefMouseEvent& event, + DragOperationsMask allowed_ops) OVERRIDE; + virtual void DragTargetDragLeave() OVERRIDE; + virtual void DragTargetDrop(const CefMouseEvent& event) OVERRIDE; + virtual void DragSourceEndedAt(int x, int y, DragOperationsMask op) OVERRIDE; + virtual void DragSourceSystemDragEnded() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_BROWSER_HOST_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/browser_process_handler_ctocpp.cc b/libcef_dll/ctocpp/browser_process_handler_ctocpp.cc new file mode 100644 index 000000000..c2c0d7b40 --- /dev/null +++ b/libcef_dll/ctocpp/browser_process_handler_ctocpp.cc @@ -0,0 +1,83 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/command_line_cpptoc.h" +#include "libcef_dll/cpptoc/list_value_cpptoc.h" +#include "libcef_dll/ctocpp/browser_process_handler_ctocpp.h" +#include "libcef_dll/ctocpp/print_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefBrowserProcessHandlerCToCpp::OnContextInitialized() { + if (CEF_MEMBER_MISSING(struct_, on_context_initialized)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->on_context_initialized(struct_); +} + +void CefBrowserProcessHandlerCToCpp::OnBeforeChildProcessLaunch( + CefRefPtr command_line) { + if (CEF_MEMBER_MISSING(struct_, on_before_child_process_launch)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: command_line; type: refptr_diff + DCHECK(command_line.get()); + if (!command_line.get()) + return; + + // Execute + struct_->on_before_child_process_launch(struct_, + CefCommandLineCppToC::Wrap(command_line)); +} + +void CefBrowserProcessHandlerCToCpp::OnRenderProcessThreadCreated( + CefRefPtr extra_info) { + if (CEF_MEMBER_MISSING(struct_, on_render_process_thread_created)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: extra_info; type: refptr_diff + DCHECK(extra_info.get()); + if (!extra_info.get()) + return; + + // Execute + struct_->on_render_process_thread_created(struct_, + CefListValueCppToC::Wrap(extra_info)); +} + +CefRefPtr CefBrowserProcessHandlerCToCpp::GetPrintHandler() { + if (CEF_MEMBER_MISSING(struct_, get_print_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_print_handler_t* _retval = struct_->get_print_handler(struct_); + + // Return type: refptr_same + return CefPrintHandlerCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/browser_process_handler_ctocpp.h b/libcef_dll/ctocpp/browser_process_handler_ctocpp.h new file mode 100644 index 000000000..0f0acd8f1 --- /dev/null +++ b/libcef_dll/ctocpp/browser_process_handler_ctocpp.h @@ -0,0 +1,46 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_BROWSER_PROCESS_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_BROWSER_PROCESS_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_browser_process_handler.h" +#include "include/capi/cef_browser_process_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefBrowserProcessHandlerCToCpp + : public CefCToCpp { + public: + explicit CefBrowserProcessHandlerCToCpp(cef_browser_process_handler_t* str) + : CefCToCpp(str) {} + + // CefBrowserProcessHandler methods + void OnContextInitialized() override; + void OnBeforeChildProcessLaunch( + CefRefPtr command_line) override; + void OnRenderProcessThreadCreated( + CefRefPtr extra_info) override; + CefRefPtr GetPrintHandler() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_BROWSER_PROCESS_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/callback_ctocpp.cc b/libcef_dll/ctocpp/callback_ctocpp.cc new file mode 100644 index 000000000..dfa507301 --- /dev/null +++ b/libcef_dll/ctocpp/callback_ctocpp.cc @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefCallbackCToCpp::Continue() { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cont(struct_); +} + +void CefCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/callback_ctocpp.h b/libcef_dll/ctocpp/callback_ctocpp.h new file mode 100644 index 000000000..ed90e6c38 --- /dev/null +++ b/libcef_dll/ctocpp/callback_ctocpp.h @@ -0,0 +1,40 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_callback.h" +#include "include/capi/cef_callback_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefCallbackCToCpp + : public CefCToCpp { + public: + explicit CefCallbackCToCpp(cef_callback_t* str) + : CefCToCpp(str) {} + + // CefCallback methods + virtual void Continue() OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/client_ctocpp.cc b/libcef_dll/ctocpp/client_ctocpp.cc new file mode 100644 index 000000000..9a20b35c6 --- /dev/null +++ b/libcef_dll/ctocpp/client_ctocpp.cc @@ -0,0 +1,249 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/process_message_cpptoc.h" +#include "libcef_dll/ctocpp/client_ctocpp.h" +#include "libcef_dll/ctocpp/context_menu_handler_ctocpp.h" +#include "libcef_dll/ctocpp/dialog_handler_ctocpp.h" +#include "libcef_dll/ctocpp/display_handler_ctocpp.h" +#include "libcef_dll/ctocpp/download_handler_ctocpp.h" +#include "libcef_dll/ctocpp/drag_handler_ctocpp.h" +#include "libcef_dll/ctocpp/find_handler_ctocpp.h" +#include "libcef_dll/ctocpp/focus_handler_ctocpp.h" +#include "libcef_dll/ctocpp/geolocation_handler_ctocpp.h" +#include "libcef_dll/ctocpp/jsdialog_handler_ctocpp.h" +#include "libcef_dll/ctocpp/keyboard_handler_ctocpp.h" +#include "libcef_dll/ctocpp/life_span_handler_ctocpp.h" +#include "libcef_dll/ctocpp/load_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_handler_ctocpp.h" +#include "libcef_dll/ctocpp/request_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefClientCToCpp::GetContextMenuHandler() { + if (CEF_MEMBER_MISSING(struct_, get_context_menu_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_context_menu_handler_t* _retval = struct_->get_context_menu_handler( + struct_); + + // Return type: refptr_same + return CefContextMenuHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetDialogHandler() { + if (CEF_MEMBER_MISSING(struct_, get_dialog_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dialog_handler_t* _retval = struct_->get_dialog_handler(struct_); + + // Return type: refptr_same + return CefDialogHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetDisplayHandler() { + if (CEF_MEMBER_MISSING(struct_, get_display_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_display_handler_t* _retval = struct_->get_display_handler(struct_); + + // Return type: refptr_same + return CefDisplayHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetDownloadHandler() { + if (CEF_MEMBER_MISSING(struct_, get_download_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_download_handler_t* _retval = struct_->get_download_handler(struct_); + + // Return type: refptr_same + return CefDownloadHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetDragHandler() { + if (CEF_MEMBER_MISSING(struct_, get_drag_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_drag_handler_t* _retval = struct_->get_drag_handler(struct_); + + // Return type: refptr_same + return CefDragHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetFindHandler() { + if (CEF_MEMBER_MISSING(struct_, get_find_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_find_handler_t* _retval = struct_->get_find_handler(struct_); + + // Return type: refptr_same + return CefFindHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetFocusHandler() { + if (CEF_MEMBER_MISSING(struct_, get_focus_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_focus_handler_t* _retval = struct_->get_focus_handler(struct_); + + // Return type: refptr_same + return CefFocusHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetGeolocationHandler() { + if (CEF_MEMBER_MISSING(struct_, get_geolocation_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_geolocation_handler_t* _retval = struct_->get_geolocation_handler( + struct_); + + // Return type: refptr_same + return CefGeolocationHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetJSDialogHandler() { + if (CEF_MEMBER_MISSING(struct_, get_jsdialog_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_jsdialog_handler_t* _retval = struct_->get_jsdialog_handler(struct_); + + // Return type: refptr_same + return CefJSDialogHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetKeyboardHandler() { + if (CEF_MEMBER_MISSING(struct_, get_keyboard_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_keyboard_handler_t* _retval = struct_->get_keyboard_handler(struct_); + + // Return type: refptr_same + return CefKeyboardHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetLifeSpanHandler() { + if (CEF_MEMBER_MISSING(struct_, get_life_span_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_life_span_handler_t* _retval = struct_->get_life_span_handler(struct_); + + // Return type: refptr_same + return CefLifeSpanHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetLoadHandler() { + if (CEF_MEMBER_MISSING(struct_, get_load_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_load_handler_t* _retval = struct_->get_load_handler(struct_); + + // Return type: refptr_same + return CefLoadHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetRenderHandler() { + if (CEF_MEMBER_MISSING(struct_, get_render_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_render_handler_t* _retval = struct_->get_render_handler(struct_); + + // Return type: refptr_same + return CefRenderHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetRequestHandler() { + if (CEF_MEMBER_MISSING(struct_, get_request_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_request_handler_t* _retval = struct_->get_request_handler(struct_); + + // Return type: refptr_same + return CefRequestHandlerCToCpp::Wrap(_retval); +} + +bool CefClientCToCpp::OnProcessMessageReceived(CefRefPtr browser, + CefProcessId source_process, CefRefPtr message) { + if (CEF_MEMBER_MISSING(struct_, on_process_message_received)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: message; type: refptr_diff + DCHECK(message.get()); + if (!message.get()) + return false; + + // Execute + int _retval = struct_->on_process_message_received(struct_, + CefBrowserCppToC::Wrap(browser), + source_process, + CefProcessMessageCppToC::Wrap(message)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/client_ctocpp.h b/libcef_dll/ctocpp/client_ctocpp.h new file mode 100644 index 000000000..b5dacbe0d --- /dev/null +++ b/libcef_dll/ctocpp/client_ctocpp.h @@ -0,0 +1,55 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_CLIENT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_CLIENT_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefClientCToCpp + : public CefCToCpp { + public: + explicit CefClientCToCpp(cef_client_t* str) + : CefCToCpp(str) {} + + // CefClient methods + CefRefPtr GetContextMenuHandler() override; + CefRefPtr GetDialogHandler() override; + CefRefPtr GetDisplayHandler() override; + CefRefPtr GetDownloadHandler() override; + CefRefPtr GetDragHandler() override; + CefRefPtr GetFindHandler() override; + CefRefPtr GetFocusHandler() override; + CefRefPtr GetGeolocationHandler() override; + CefRefPtr GetJSDialogHandler() override; + CefRefPtr GetKeyboardHandler() override; + CefRefPtr GetLifeSpanHandler() override; + CefRefPtr GetLoadHandler() override; + CefRefPtr GetRenderHandler() override; + CefRefPtr GetRequestHandler() override; + bool OnProcessMessageReceived(CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_CLIENT_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/command_line_ctocpp.cc b/libcef_dll/ctocpp/command_line_ctocpp.cc new file mode 100644 index 000000000..2f7d28b77 --- /dev/null +++ b/libcef_dll/ctocpp/command_line_ctocpp.cc @@ -0,0 +1,398 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "include/cef_version.h" +#include "libcef_dll/ctocpp/command_line_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefCommandLine::CreateCommandLine() { + const char* api_hash = cef_api_hash(0); + if (strcmp(api_hash, CEF_API_HASH_PLATFORM)) { + // The libcef API hash does not match the current header API hash. + NOTREACHED(); + return NULL; + } + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_command_line_t* _retval = cef_command_line_create(); + + // Return type: refptr_same + return CefCommandLineCToCpp::Wrap(_retval); +} + +CefRefPtr CefCommandLine::GetGlobalCommandLine() { + const char* api_hash = cef_api_hash(0); + if (strcmp(api_hash, CEF_API_HASH_PLATFORM)) { + // The libcef API hash does not match the current header API hash. + NOTREACHED(); + return NULL; + } + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_command_line_t* _retval = cef_command_line_get_global(); + + // Return type: refptr_same + return CefCommandLineCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefCommandLineCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefCommandLineCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefCommandLineCToCpp::Copy() { + if (CEF_MEMBER_MISSING(struct_, copy)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_command_line_t* _retval = struct_->copy(struct_); + + // Return type: refptr_same + return CefCommandLineCToCpp::Wrap(_retval); +} + +void CefCommandLineCToCpp::InitFromArgv(int argc, const char* const* argv) { + if (CEF_MEMBER_MISSING(struct_, init_from_argv)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: argv; type: simple_byaddr + DCHECK(argv); + if (!argv) + return; + + // Execute + struct_->init_from_argv(struct_, + argc, + argv); +} + +void CefCommandLineCToCpp::InitFromString(const CefString& command_line) { + if (CEF_MEMBER_MISSING(struct_, init_from_string)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: command_line; type: string_byref_const + DCHECK(!command_line.empty()); + if (command_line.empty()) + return; + + // Execute + struct_->init_from_string(struct_, + command_line.GetStruct()); +} + +void CefCommandLineCToCpp::Reset() { + if (CEF_MEMBER_MISSING(struct_, reset)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->reset(struct_); +} + +void CefCommandLineCToCpp::GetArgv(std::vector& argv) { + if (CEF_MEMBER_MISSING(struct_, get_argv)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: argv; type: string_vec_byref + cef_string_list_t argvList = cef_string_list_alloc(); + DCHECK(argvList); + if (argvList) + transfer_string_list_contents(argv, argvList); + + // Execute + struct_->get_argv(struct_, + argvList); + + // Restore param:argv; type: string_vec_byref + if (argvList) { + argv.clear(); + transfer_string_list_contents(argvList, argv); + cef_string_list_free(argvList); + } +} + +CefString CefCommandLineCToCpp::GetCommandLineString() { + if (CEF_MEMBER_MISSING(struct_, get_command_line_string)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_command_line_string(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefCommandLineCToCpp::GetProgram() { + if (CEF_MEMBER_MISSING(struct_, get_program)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_program(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefCommandLineCToCpp::SetProgram(const CefString& program) { + if (CEF_MEMBER_MISSING(struct_, set_program)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: program; type: string_byref_const + DCHECK(!program.empty()); + if (program.empty()) + return; + + // Execute + struct_->set_program(struct_, + program.GetStruct()); +} + +bool CefCommandLineCToCpp::HasSwitches() { + if (CEF_MEMBER_MISSING(struct_, has_switches)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_switches(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefCommandLineCToCpp::HasSwitch(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, has_switch)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return false; + + // Execute + int _retval = struct_->has_switch(struct_, + name.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefString CefCommandLineCToCpp::GetSwitchValue(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, get_switch_value)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_switch_value(struct_, + name.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefCommandLineCToCpp::GetSwitches(SwitchMap& switches) { + if (CEF_MEMBER_MISSING(struct_, get_switches)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: switches; type: string_map_single_byref + cef_string_map_t switchesMap = cef_string_map_alloc(); + DCHECK(switchesMap); + if (switchesMap) + transfer_string_map_contents(switches, switchesMap); + + // Execute + struct_->get_switches(struct_, + switchesMap); + + // Restore param:switches; type: string_map_single_byref + if (switchesMap) { + switches.clear(); + transfer_string_map_contents(switchesMap, switches); + cef_string_map_free(switchesMap); + } +} + +void CefCommandLineCToCpp::AppendSwitch(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, append_switch)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return; + + // Execute + struct_->append_switch(struct_, + name.GetStruct()); +} + +void CefCommandLineCToCpp::AppendSwitchWithValue(const CefString& name, + const CefString& value) { + if (CEF_MEMBER_MISSING(struct_, append_switch_with_value)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return; + // Verify param: value; type: string_byref_const + DCHECK(!value.empty()); + if (value.empty()) + return; + + // Execute + struct_->append_switch_with_value(struct_, + name.GetStruct(), + value.GetStruct()); +} + +bool CefCommandLineCToCpp::HasArguments() { + if (CEF_MEMBER_MISSING(struct_, has_arguments)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_arguments(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefCommandLineCToCpp::GetArguments(ArgumentList& arguments) { + if (CEF_MEMBER_MISSING(struct_, get_arguments)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: arguments; type: string_vec_byref + cef_string_list_t argumentsList = cef_string_list_alloc(); + DCHECK(argumentsList); + if (argumentsList) + transfer_string_list_contents(arguments, argumentsList); + + // Execute + struct_->get_arguments(struct_, + argumentsList); + + // Restore param:arguments; type: string_vec_byref + if (argumentsList) { + arguments.clear(); + transfer_string_list_contents(argumentsList, arguments); + cef_string_list_free(argumentsList); + } +} + +void CefCommandLineCToCpp::AppendArgument(const CefString& argument) { + if (CEF_MEMBER_MISSING(struct_, append_argument)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: argument; type: string_byref_const + DCHECK(!argument.empty()); + if (argument.empty()) + return; + + // Execute + struct_->append_argument(struct_, + argument.GetStruct()); +} + +void CefCommandLineCToCpp::PrependWrapper(const CefString& wrapper) { + if (CEF_MEMBER_MISSING(struct_, prepend_wrapper)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: wrapper; type: string_byref_const + DCHECK(!wrapper.empty()); + if (wrapper.empty()) + return; + + // Execute + struct_->prepend_wrapper(struct_, + wrapper.GetStruct()); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/command_line_ctocpp.h b/libcef_dll/ctocpp/command_line_ctocpp.h new file mode 100644 index 000000000..97add3654 --- /dev/null +++ b/libcef_dll/ctocpp/command_line_ctocpp.h @@ -0,0 +1,62 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_COMMAND_LINE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_COMMAND_LINE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_command_line.h" +#include "include/capi/cef_command_line_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefCommandLineCToCpp + : public CefCToCpp { + public: + explicit CefCommandLineCToCpp(cef_command_line_t* str) + : CefCToCpp( + str) {} + + // CefCommandLine methods + virtual bool IsValid() OVERRIDE; + virtual bool IsReadOnly() OVERRIDE; + virtual CefRefPtr Copy() OVERRIDE; + virtual void InitFromArgv(int argc, const char* const* argv) OVERRIDE; + virtual void InitFromString(const CefString& command_line) OVERRIDE; + virtual void Reset() OVERRIDE; + virtual void GetArgv(std::vector& argv) OVERRIDE; + virtual CefString GetCommandLineString() OVERRIDE; + virtual CefString GetProgram() OVERRIDE; + virtual void SetProgram(const CefString& program) OVERRIDE; + virtual bool HasSwitches() OVERRIDE; + virtual bool HasSwitch(const CefString& name) OVERRIDE; + virtual CefString GetSwitchValue(const CefString& name) OVERRIDE; + virtual void GetSwitches(SwitchMap& switches) OVERRIDE; + virtual void AppendSwitch(const CefString& name) OVERRIDE; + virtual void AppendSwitchWithValue(const CefString& name, + const CefString& value) OVERRIDE; + virtual bool HasArguments() OVERRIDE; + virtual void GetArguments(ArgumentList& arguments) OVERRIDE; + virtual void AppendArgument(const CefString& argument) OVERRIDE; + virtual void PrependWrapper(const CefString& wrapper) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_COMMAND_LINE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/completion_callback_ctocpp.cc b/libcef_dll/ctocpp/completion_callback_ctocpp.cc new file mode 100644 index 000000000..2ea3f31bc --- /dev/null +++ b/libcef_dll/ctocpp/completion_callback_ctocpp.cc @@ -0,0 +1,33 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/completion_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefCompletionCallbackCToCpp::OnComplete() { + if (CEF_MEMBER_MISSING(struct_, on_complete)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->on_complete(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/completion_callback_ctocpp.h b/libcef_dll/ctocpp/completion_callback_ctocpp.h new file mode 100644 index 000000000..147811f26 --- /dev/null +++ b/libcef_dll/ctocpp/completion_callback_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_COMPLETION_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_COMPLETION_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_callback.h" +#include "include/capi/cef_callback_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefCompletionCallbackCToCpp + : public CefCToCpp { + public: + explicit CefCompletionCallbackCToCpp(cef_completion_callback_t* str) + : CefCToCpp(str) {} + + // CefCompletionCallback methods + void OnComplete() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_COMPLETION_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/context_menu_handler_ctocpp.cc b/libcef_dll/ctocpp/context_menu_handler_ctocpp.cc new file mode 100644 index 000000000..e02406558 --- /dev/null +++ b/libcef_dll/ctocpp/context_menu_handler_ctocpp.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/context_menu_params_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/menu_model_cpptoc.h" +#include "libcef_dll/ctocpp/context_menu_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefContextMenuHandlerCToCpp::OnBeforeContextMenu( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr params, CefRefPtr model) { + if (CEF_MEMBER_MISSING(struct_, on_before_context_menu)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: params; type: refptr_diff + DCHECK(params.get()); + if (!params.get()) + return; + // Verify param: model; type: refptr_diff + DCHECK(model.get()); + if (!model.get()) + return; + + // Execute + struct_->on_before_context_menu(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefContextMenuParamsCppToC::Wrap(params), + CefMenuModelCppToC::Wrap(model)); +} + +bool CefContextMenuHandlerCToCpp::OnContextMenuCommand( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr params, int command_id, + EventFlags event_flags) { + if (CEF_MEMBER_MISSING(struct_, on_context_menu_command)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: params; type: refptr_diff + DCHECK(params.get()); + if (!params.get()) + return false; + + // Execute + int _retval = struct_->on_context_menu_command(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefContextMenuParamsCppToC::Wrap(params), + command_id, + event_flags); + + // Return type: bool + return _retval?true:false; +} + +void CefContextMenuHandlerCToCpp::OnContextMenuDismissed( + CefRefPtr browser, CefRefPtr frame) { + if (CEF_MEMBER_MISSING(struct_, on_context_menu_dismissed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + + // Execute + struct_->on_context_menu_dismissed(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/context_menu_handler_ctocpp.h b/libcef_dll/ctocpp/context_menu_handler_ctocpp.h new file mode 100644 index 000000000..f9ca11d3d --- /dev/null +++ b/libcef_dll/ctocpp/context_menu_handler_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_CONTEXT_MENU_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_CONTEXT_MENU_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_context_menu_handler.h" +#include "include/capi/cef_context_menu_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefContextMenuHandlerCToCpp + : public CefCToCpp { + public: + explicit CefContextMenuHandlerCToCpp(cef_context_menu_handler_t* str) + : CefCToCpp(str) {} + + // CefContextMenuHandler methods + void OnBeforeContextMenu(CefRefPtr browser, + CefRefPtr frame, CefRefPtr params, + CefRefPtr model) override; + bool OnContextMenuCommand(CefRefPtr browser, + CefRefPtr frame, CefRefPtr params, + int command_id, EventFlags event_flags) override; + void OnContextMenuDismissed(CefRefPtr browser, + CefRefPtr frame) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_CONTEXT_MENU_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/context_menu_params_ctocpp.cc b/libcef_dll/ctocpp/context_menu_params_ctocpp.cc new file mode 100644 index 000000000..11af7e2c8 --- /dev/null +++ b/libcef_dll/ctocpp/context_menu_params_ctocpp.cc @@ -0,0 +1,306 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/context_menu_params_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +int CefContextMenuParamsCToCpp::GetXCoord() { + if (CEF_MEMBER_MISSING(struct_, get_xcoord)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_xcoord(struct_); + + // Return type: simple + return _retval; +} + +int CefContextMenuParamsCToCpp::GetYCoord() { + if (CEF_MEMBER_MISSING(struct_, get_ycoord)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_ycoord(struct_); + + // Return type: simple + return _retval; +} + +CefContextMenuParams::TypeFlags CefContextMenuParamsCToCpp::GetTypeFlags() { + if (CEF_MEMBER_MISSING(struct_, get_type_flags)) + return CM_TYPEFLAG_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_context_menu_type_flags_t _retval = struct_->get_type_flags(struct_); + + // Return type: simple + return _retval; +} + +CefString CefContextMenuParamsCToCpp::GetLinkUrl() { + if (CEF_MEMBER_MISSING(struct_, get_link_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_link_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefContextMenuParamsCToCpp::GetUnfilteredLinkUrl() { + if (CEF_MEMBER_MISSING(struct_, get_unfiltered_link_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_unfiltered_link_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefContextMenuParamsCToCpp::GetSourceUrl() { + if (CEF_MEMBER_MISSING(struct_, get_source_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_source_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefContextMenuParamsCToCpp::HasImageContents() { + if (CEF_MEMBER_MISSING(struct_, has_image_contents)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_image_contents(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefContextMenuParamsCToCpp::GetPageUrl() { + if (CEF_MEMBER_MISSING(struct_, get_page_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_page_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefContextMenuParamsCToCpp::GetFrameUrl() { + if (CEF_MEMBER_MISSING(struct_, get_frame_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_frame_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefContextMenuParamsCToCpp::GetFrameCharset() { + if (CEF_MEMBER_MISSING(struct_, get_frame_charset)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_frame_charset(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefContextMenuParams::MediaType CefContextMenuParamsCToCpp::GetMediaType() { + if (CEF_MEMBER_MISSING(struct_, get_media_type)) + return CM_MEDIATYPE_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_context_menu_media_type_t _retval = struct_->get_media_type(struct_); + + // Return type: simple + return _retval; +} + +CefContextMenuParams::MediaStateFlags CefContextMenuParamsCToCpp::GetMediaStateFlags( + ) { + if (CEF_MEMBER_MISSING(struct_, get_media_state_flags)) + return CM_MEDIAFLAG_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_context_menu_media_state_flags_t _retval = struct_->get_media_state_flags( + struct_); + + // Return type: simple + return _retval; +} + +CefString CefContextMenuParamsCToCpp::GetSelectionText() { + if (CEF_MEMBER_MISSING(struct_, get_selection_text)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_selection_text(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefContextMenuParamsCToCpp::GetMisspelledWord() { + if (CEF_MEMBER_MISSING(struct_, get_misspelled_word)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_misspelled_word(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int CefContextMenuParamsCToCpp::GetMisspellingHash() { + if (CEF_MEMBER_MISSING(struct_, get_misspelling_hash)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_misspelling_hash(struct_); + + // Return type: simple + return _retval; +} + +bool CefContextMenuParamsCToCpp::GetDictionarySuggestions( + std::vector& suggestions) { + if (CEF_MEMBER_MISSING(struct_, get_dictionary_suggestions)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: suggestions; type: string_vec_byref + cef_string_list_t suggestionsList = cef_string_list_alloc(); + DCHECK(suggestionsList); + if (suggestionsList) + transfer_string_list_contents(suggestions, suggestionsList); + + // Execute + int _retval = struct_->get_dictionary_suggestions(struct_, + suggestionsList); + + // Restore param:suggestions; type: string_vec_byref + if (suggestionsList) { + suggestions.clear(); + transfer_string_list_contents(suggestionsList, suggestions); + cef_string_list_free(suggestionsList); + } + + // Return type: bool + return _retval?true:false; +} + +bool CefContextMenuParamsCToCpp::IsEditable() { + if (CEF_MEMBER_MISSING(struct_, is_editable)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_editable(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefContextMenuParamsCToCpp::IsSpellCheckEnabled() { + if (CEF_MEMBER_MISSING(struct_, is_spell_check_enabled)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_spell_check_enabled(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefContextMenuParams::EditStateFlags CefContextMenuParamsCToCpp::GetEditStateFlags( + ) { + if (CEF_MEMBER_MISSING(struct_, get_edit_state_flags)) + return CM_EDITFLAG_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_context_menu_edit_state_flags_t _retval = struct_->get_edit_state_flags( + struct_); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/context_menu_params_ctocpp.h b/libcef_dll/ctocpp/context_menu_params_ctocpp.h new file mode 100644 index 000000000..0f615f4a2 --- /dev/null +++ b/libcef_dll/ctocpp/context_menu_params_ctocpp.h @@ -0,0 +1,61 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_CONTEXT_MENU_PARAMS_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_CONTEXT_MENU_PARAMS_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_context_menu_handler.h" +#include "include/capi/cef_context_menu_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefContextMenuParamsCToCpp + : public CefCToCpp { + public: + explicit CefContextMenuParamsCToCpp(cef_context_menu_params_t* str) + : CefCToCpp(str) {} + + // CefContextMenuParams methods + virtual int GetXCoord() OVERRIDE; + virtual int GetYCoord() OVERRIDE; + virtual TypeFlags GetTypeFlags() OVERRIDE; + virtual CefString GetLinkUrl() OVERRIDE; + virtual CefString GetUnfilteredLinkUrl() OVERRIDE; + virtual CefString GetSourceUrl() OVERRIDE; + virtual bool HasImageContents() OVERRIDE; + virtual CefString GetPageUrl() OVERRIDE; + virtual CefString GetFrameUrl() OVERRIDE; + virtual CefString GetFrameCharset() OVERRIDE; + virtual MediaType GetMediaType() OVERRIDE; + virtual MediaStateFlags GetMediaStateFlags() OVERRIDE; + virtual CefString GetSelectionText() OVERRIDE; + virtual CefString GetMisspelledWord() OVERRIDE; + virtual int GetMisspellingHash() OVERRIDE; + virtual bool GetDictionarySuggestions( + std::vector& suggestions) OVERRIDE; + virtual bool IsEditable() OVERRIDE; + virtual bool IsSpellCheckEnabled() OVERRIDE; + virtual EditStateFlags GetEditStateFlags() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_CONTEXT_MENU_PARAMS_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/cookie_manager_ctocpp.cc b/libcef_dll/ctocpp/cookie_manager_ctocpp.cc new file mode 100644 index 000000000..8953bf79c --- /dev/null +++ b/libcef_dll/ctocpp/cookie_manager_ctocpp.cc @@ -0,0 +1,199 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/completion_callback_cpptoc.h" +#include "libcef_dll/cpptoc/cookie_visitor_cpptoc.h" +#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefCookieManager::GetGlobalManager() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_cookie_manager_t* _retval = cef_cookie_manager_get_global_manager(); + + // Return type: refptr_same + return CefCookieManagerCToCpp::Wrap(_retval); +} + +CefRefPtr CefCookieManager::CreateManager( + const CefString& path, bool persist_session_cookies) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: path + + // Execute + cef_cookie_manager_t* _retval = cef_cookie_manager_create_manager( + path.GetStruct(), + persist_session_cookies); + + // Return type: refptr_same + return CefCookieManagerCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefCookieManagerCToCpp::SetSupportedSchemes( + const std::vector& schemes) { + if (CEF_MEMBER_MISSING(struct_, set_supported_schemes)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: schemes; type: string_vec_byref_const + cef_string_list_t schemesList = cef_string_list_alloc(); + DCHECK(schemesList); + if (schemesList) + transfer_string_list_contents(schemes, schemesList); + + // Execute + struct_->set_supported_schemes(struct_, + schemesList); + + // Restore param:schemes; type: string_vec_byref_const + if (schemesList) + cef_string_list_free(schemesList); +} + +bool CefCookieManagerCToCpp::VisitAllCookies( + CefRefPtr visitor) { + if (CEF_MEMBER_MISSING(struct_, visit_all_cookies)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return false; + + // Execute + int _retval = struct_->visit_all_cookies(struct_, + CefCookieVisitorCppToC::Wrap(visitor)); + + // Return type: bool + return _retval?true:false; +} + +bool CefCookieManagerCToCpp::VisitUrlCookies(const CefString& url, + bool includeHttpOnly, CefRefPtr visitor) { + if (CEF_MEMBER_MISSING(struct_, visit_url_cookies)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return false; + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return false; + + // Execute + int _retval = struct_->visit_url_cookies(struct_, + url.GetStruct(), + includeHttpOnly, + CefCookieVisitorCppToC::Wrap(visitor)); + + // Return type: bool + return _retval?true:false; +} + +bool CefCookieManagerCToCpp::SetCookie(const CefString& url, + const CefCookie& cookie) { + if (CEF_MEMBER_MISSING(struct_, set_cookie)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return false; + + // Execute + int _retval = struct_->set_cookie(struct_, + url.GetStruct(), + &cookie); + + // Return type: bool + return _retval?true:false; +} + +bool CefCookieManagerCToCpp::DeleteCookies(const CefString& url, + const CefString& cookie_name) { + if (CEF_MEMBER_MISSING(struct_, delete_cookies)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: url, cookie_name + + // Execute + int _retval = struct_->delete_cookies(struct_, + url.GetStruct(), + cookie_name.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefCookieManagerCToCpp::SetStoragePath(const CefString& path, + bool persist_session_cookies) { + if (CEF_MEMBER_MISSING(struct_, set_storage_path)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: path + + // Execute + int _retval = struct_->set_storage_path(struct_, + path.GetStruct(), + persist_session_cookies); + + // Return type: bool + return _retval?true:false; +} + +bool CefCookieManagerCToCpp::FlushStore( + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, flush_store)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->flush_store(struct_, + CefCompletionCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/cookie_manager_ctocpp.h b/libcef_dll/ctocpp/cookie_manager_ctocpp.h new file mode 100644 index 000000000..c96025a28 --- /dev/null +++ b/libcef_dll/ctocpp/cookie_manager_ctocpp.h @@ -0,0 +1,53 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_COOKIE_MANAGER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_COOKIE_MANAGER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_cookie.h" +#include "include/capi/cef_cookie_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefCookieManagerCToCpp + : public CefCToCpp { + public: + explicit CefCookieManagerCToCpp(cef_cookie_manager_t* str) + : CefCToCpp(str) {} + + // CefCookieManager methods + virtual void SetSupportedSchemes( + const std::vector& schemes) OVERRIDE; + virtual bool VisitAllCookies(CefRefPtr visitor) OVERRIDE; + virtual bool VisitUrlCookies(const CefString& url, bool includeHttpOnly, + CefRefPtr visitor) OVERRIDE; + virtual bool SetCookie(const CefString& url, + const CefCookie& cookie) OVERRIDE; + virtual bool DeleteCookies(const CefString& url, + const CefString& cookie_name) OVERRIDE; + virtual bool SetStoragePath(const CefString& path, + bool persist_session_cookies) OVERRIDE; + virtual bool FlushStore(CefRefPtr callback) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_COOKIE_MANAGER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/cookie_visitor_ctocpp.cc b/libcef_dll/ctocpp/cookie_visitor_ctocpp.cc new file mode 100644 index 000000000..c2cefbae6 --- /dev/null +++ b/libcef_dll/ctocpp/cookie_visitor_ctocpp.cc @@ -0,0 +1,47 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/cookie_visitor_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefCookieVisitorCToCpp::Visit(const CefCookie& cookie, int count, + int total, bool& deleteCookie) { + if (CEF_MEMBER_MISSING(struct_, visit)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: deleteCookie; type: bool_byref + int deleteCookieInt = deleteCookie; + + // Execute + int _retval = struct_->visit(struct_, + &cookie, + count, + total, + &deleteCookieInt); + + // Restore param:deleteCookie; type: bool_byref + deleteCookie = deleteCookieInt?true:false; + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/cookie_visitor_ctocpp.h b/libcef_dll/ctocpp/cookie_visitor_ctocpp.h new file mode 100644 index 000000000..d8a12968c --- /dev/null +++ b/libcef_dll/ctocpp/cookie_visitor_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_COOKIE_VISITOR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_COOKIE_VISITOR_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_cookie.h" +#include "include/capi/cef_cookie_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefCookieVisitorCToCpp + : public CefCToCpp { + public: + explicit CefCookieVisitorCToCpp(cef_cookie_visitor_t* str) + : CefCToCpp(str) {} + + // CefCookieVisitor methods + bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_COOKIE_VISITOR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/ctocpp.h b/libcef_dll/ctocpp/ctocpp.h new file mode 100644 index 000000000..063fe1cfd --- /dev/null +++ b/libcef_dll/ctocpp/ctocpp.h @@ -0,0 +1,117 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DLL_CTOCPP_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_CTOCPP_H_ +#pragma once + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_base.h" +#include "include/capi/cef_base_capi.h" + +// Wrap a C structure with a C++ class. This is used when the implementation +// exists on the other side of the DLL boundary but will have methods called on +// this side of the DLL boundary. +template +class CefCToCpp : public BaseName { + public: + // Use this method to create a wrapper class instance for a structure + // received from the other side. + static CefRefPtr Wrap(StructName* s) { + if (!s) + return NULL; + + // Wrap their structure with the CefCToCpp object. + ClassName* wrapper = new ClassName(s); + // Put the wrapper object in a smart pointer. + CefRefPtr wrapperPtr(wrapper); + // Release the reference that was added to the CefCppToC wrapper object on + // the other side before their structure was passed to us. + wrapper->UnderlyingRelease(); + // Return the smart pointer. + return wrapperPtr; + } + + // Use this method to retrieve the underlying structure from a wrapper class + // instance for return back to the other side. + static StructName* Unwrap(CefRefPtr c) { + if (!c.get()) + return NULL; + + // Cast the object to our wrapper class type. + ClassName* wrapper = static_cast(c.get()); + // Add a reference to the CefCppToC wrapper object on the other side that + // will be released once the structure is received. + wrapper->UnderlyingAddRef(); + // Return their original structure. + return wrapper->GetStruct(); + } + + explicit CefCToCpp(StructName* str) + : struct_(str) { + DCHECK(str); + +#ifndef NDEBUG + base::AtomicRefCountInc(&DebugObjCt); +#endif + } + virtual ~CefCToCpp() { +#ifndef NDEBUG + base::AtomicRefCountDec(&DebugObjCt); +#endif + } + + // If returning the structure across the DLL boundary you should call + // UnderlyingAddRef() on this wrapping CefCToCpp object. On the other side of + // the DLL boundary, call Release() on the CefCppToC object. + StructName* GetStruct() { return struct_; } + + // CefBase methods increment/decrement reference counts on both this object + // and the underlying wrapped structure. + void AddRef() const { + UnderlyingAddRef(); + ref_count_.AddRef(); + } + bool Release() const { + UnderlyingRelease(); + if (ref_count_.Release()) { + delete this; + return true; + } + return false; + } + bool HasOneRef() const { return ref_count_.HasOneRef(); } + + // Increment/decrement reference counts on only the underlying class. + void UnderlyingAddRef() const { + if (struct_->base.add_ref) + struct_->base.add_ref(&struct_->base); + } + bool UnderlyingRelease() const { + if (!struct_->base.release) + return false; + return struct_->base.release(&struct_->base) ? true : false; + } + bool UnderlyingHasOneRef() const { + if (!struct_->base.has_one_ref) + return false; + return struct_->base.has_one_ref(&struct_->base) ? true : false; + } + +#ifndef NDEBUG + // Simple tracking of allocated objects. + static base::AtomicRefCount DebugObjCt; // NOLINT(runtime/int) +#endif + + protected: + StructName* struct_; + + private: + CefRefCount ref_count_; + + DISALLOW_COPY_AND_ASSIGN(CefCToCpp); +}; + +#endif // CEF_LIBCEF_DLL_CTOCPP_CTOCPP_H_ diff --git a/libcef_dll/ctocpp/dialog_handler_ctocpp.cc b/libcef_dll/ctocpp/dialog_handler_ctocpp.cc new file mode 100644 index 000000000..d2a522dcd --- /dev/null +++ b/libcef_dll/ctocpp/dialog_handler_ctocpp.cc @@ -0,0 +1,74 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/file_dialog_callback_cpptoc.h" +#include "libcef_dll/ctocpp/dialog_handler_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefDialogHandlerCToCpp::OnFileDialog(CefRefPtr browser, + FileDialogMode mode, const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, int selected_accept_filter, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_file_dialog)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + // Unverified params: title, default_file_path, accept_filters + + // Translate param: accept_filters; type: string_vec_byref_const + cef_string_list_t accept_filtersList = cef_string_list_alloc(); + DCHECK(accept_filtersList); + if (accept_filtersList) + transfer_string_list_contents(accept_filters, accept_filtersList); + + // Execute + int _retval = struct_->on_file_dialog(struct_, + CefBrowserCppToC::Wrap(browser), + mode, + title.GetStruct(), + default_file_path.GetStruct(), + accept_filtersList, + selected_accept_filter, + CefFileDialogCallbackCppToC::Wrap(callback)); + + // Restore param:accept_filters; type: string_vec_byref_const + if (accept_filtersList) + cef_string_list_free(accept_filtersList); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/dialog_handler_ctocpp.h b/libcef_dll/ctocpp/dialog_handler_ctocpp.h new file mode 100644 index 000000000..665add1e6 --- /dev/null +++ b/libcef_dll/ctocpp/dialog_handler_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DIALOG_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DIALOG_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include +#include "include/cef_dialog_handler.h" +#include "include/capi/cef_dialog_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefDialogHandlerCToCpp + : public CefCToCpp { + public: + explicit CefDialogHandlerCToCpp(cef_dialog_handler_t* str) + : CefCToCpp(str) {} + + // CefDialogHandler methods + bool OnFileDialog(CefRefPtr browser, FileDialogMode mode, + const CefString& title, const CefString& default_file_path, + const std::vector& accept_filters, int selected_accept_filter, + CefRefPtr callback) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DIALOG_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/dictionary_value_ctocpp.cc b/libcef_dll/ctocpp/dictionary_value_ctocpp.cc new file mode 100644 index 000000000..0fce260fb --- /dev/null +++ b/libcef_dll/ctocpp/dictionary_value_ctocpp.cc @@ -0,0 +1,517 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/binary_value_ctocpp.h" +#include "libcef_dll/ctocpp/dictionary_value_ctocpp.h" +#include "libcef_dll/ctocpp/list_value_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefDictionaryValue::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dictionary_value_t* _retval = cef_dictionary_value_create(); + + // Return type: refptr_same + return CefDictionaryValueCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefDictionaryValueCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::IsOwned() { + if (CEF_MEMBER_MISSING(struct_, is_owned)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_owned(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefDictionaryValueCToCpp::Copy( + bool exclude_empty_children) { + if (CEF_MEMBER_MISSING(struct_, copy)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dictionary_value_t* _retval = struct_->copy(struct_, + exclude_empty_children); + + // Return type: refptr_same + return CefDictionaryValueCToCpp::Wrap(_retval); +} + +size_t CefDictionaryValueCToCpp::GetSize() { + if (CEF_MEMBER_MISSING(struct_, get_size)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_size(struct_); + + // Return type: simple + return _retval; +} + +bool CefDictionaryValueCToCpp::Clear() { + if (CEF_MEMBER_MISSING(struct_, clear)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->clear(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::HasKey(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, has_key)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->has_key(struct_, + key.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::GetKeys(KeyList& keys) { + if (CEF_MEMBER_MISSING(struct_, get_keys)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: keys; type: string_vec_byref + cef_string_list_t keysList = cef_string_list_alloc(); + DCHECK(keysList); + if (keysList) + transfer_string_list_contents(keys, keysList); + + // Execute + int _retval = struct_->get_keys(struct_, + keysList); + + // Restore param:keys; type: string_vec_byref + if (keysList) { + keys.clear(); + transfer_string_list_contents(keysList, keys); + cef_string_list_free(keysList); + } + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::Remove(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, remove)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->remove(struct_, + key.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefValueType CefDictionaryValueCToCpp::GetType(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return VTYPE_INVALID; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return VTYPE_INVALID; + + // Execute + cef_value_type_t _retval = struct_->get_type(struct_, + key.GetStruct()); + + // Return type: simple + return _retval; +} + +bool CefDictionaryValueCToCpp::GetBool(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_bool)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->get_bool(struct_, + key.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +int CefDictionaryValueCToCpp::GetInt(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_int)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return 0; + + // Execute + int _retval = struct_->get_int(struct_, + key.GetStruct()); + + // Return type: simple + return _retval; +} + +double CefDictionaryValueCToCpp::GetDouble(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_double)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return 0; + + // Execute + double _retval = struct_->get_double(struct_, + key.GetStruct()); + + // Return type: simple + return _retval; +} + +CefString CefDictionaryValueCToCpp::GetString(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_string)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_string(struct_, + key.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefDictionaryValueCToCpp::GetBinary( + const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_binary)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return NULL; + + // Execute + cef_binary_value_t* _retval = struct_->get_binary(struct_, + key.GetStruct()); + + // Return type: refptr_same + return CefBinaryValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefDictionaryValueCToCpp::GetDictionary( + const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_dictionary)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return NULL; + + // Execute + cef_dictionary_value_t* _retval = struct_->get_dictionary(struct_, + key.GetStruct()); + + // Return type: refptr_same + return CefDictionaryValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefDictionaryValueCToCpp::GetList( + const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_list)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return NULL; + + // Execute + cef_list_value_t* _retval = struct_->get_list(struct_, + key.GetStruct()); + + // Return type: refptr_same + return CefListValueCToCpp::Wrap(_retval); +} + +bool CefDictionaryValueCToCpp::SetNull(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, set_null)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->set_null(struct_, + key.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetBool(const CefString& key, bool value) { + if (CEF_MEMBER_MISSING(struct_, set_bool)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->set_bool(struct_, + key.GetStruct(), + value); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetInt(const CefString& key, int value) { + if (CEF_MEMBER_MISSING(struct_, set_int)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->set_int(struct_, + key.GetStruct(), + value); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetDouble(const CefString& key, double value) { + if (CEF_MEMBER_MISSING(struct_, set_double)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // Execute + int _retval = struct_->set_double(struct_, + key.GetStruct(), + value); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetString(const CefString& key, + const CefString& value) { + if (CEF_MEMBER_MISSING(struct_, set_string)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + // Unverified params: value + + // Execute + int _retval = struct_->set_string(struct_, + key.GetStruct(), + value.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetBinary(const CefString& key, + CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_binary)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_binary(struct_, + key.GetStruct(), + CefBinaryValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetDictionary(const CefString& key, + CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_dictionary)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_dictionary(struct_, + key.GetStruct(), + CefDictionaryValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + +bool CefDictionaryValueCToCpp::SetList(const CefString& key, + CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_list)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_list(struct_, + key.GetStruct(), + CefListValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/dictionary_value_ctocpp.h b/libcef_dll/ctocpp/dictionary_value_ctocpp.h new file mode 100644 index 000000000..8d1ef6610 --- /dev/null +++ b/libcef_dll/ctocpp/dictionary_value_ctocpp.h @@ -0,0 +1,70 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DICTIONARY_VALUE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DICTIONARY_VALUE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_values.h" +#include "include/capi/cef_values_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefDictionaryValueCToCpp + : public CefCToCpp { + public: + explicit CefDictionaryValueCToCpp(cef_dictionary_value_t* str) + : CefCToCpp(str) {} + + // CefDictionaryValue methods + virtual bool IsValid() OVERRIDE; + virtual bool IsOwned() OVERRIDE; + virtual bool IsReadOnly() OVERRIDE; + virtual CefRefPtr Copy( + bool exclude_empty_children) OVERRIDE; + virtual size_t GetSize() OVERRIDE; + virtual bool Clear() OVERRIDE; + virtual bool HasKey(const CefString& key) OVERRIDE; + virtual bool GetKeys(KeyList& keys) OVERRIDE; + virtual bool Remove(const CefString& key) OVERRIDE; + virtual CefValueType GetType(const CefString& key) OVERRIDE; + virtual bool GetBool(const CefString& key) OVERRIDE; + virtual int GetInt(const CefString& key) OVERRIDE; + virtual double GetDouble(const CefString& key) OVERRIDE; + virtual CefString GetString(const CefString& key) OVERRIDE; + virtual CefRefPtr GetBinary(const CefString& key) OVERRIDE; + virtual CefRefPtr GetDictionary( + const CefString& key) OVERRIDE; + virtual CefRefPtr GetList(const CefString& key) OVERRIDE; + virtual bool SetNull(const CefString& key) OVERRIDE; + virtual bool SetBool(const CefString& key, bool value) OVERRIDE; + virtual bool SetInt(const CefString& key, int value) OVERRIDE; + virtual bool SetDouble(const CefString& key, double value) OVERRIDE; + virtual bool SetString(const CefString& key, const CefString& value) OVERRIDE; + virtual bool SetBinary(const CefString& key, + CefRefPtr value) OVERRIDE; + virtual bool SetDictionary(const CefString& key, + CefRefPtr value) OVERRIDE; + virtual bool SetList(const CefString& key, + CefRefPtr value) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DICTIONARY_VALUE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/display_handler_ctocpp.cc b/libcef_dll/ctocpp/display_handler_ctocpp.cc new file mode 100644 index 000000000..51797aea2 --- /dev/null +++ b/libcef_dll/ctocpp/display_handler_ctocpp.cc @@ -0,0 +1,166 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/ctocpp/display_handler_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefDisplayHandlerCToCpp::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, on_address_change)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->on_address_change(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + url.GetStruct()); +} + +void CefDisplayHandlerCToCpp::OnTitleChange(CefRefPtr browser, + const CefString& title) { + if (CEF_MEMBER_MISSING(struct_, on_title_change)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Unverified params: title + + // Execute + struct_->on_title_change(struct_, + CefBrowserCppToC::Wrap(browser), + title.GetStruct()); +} + +void CefDisplayHandlerCToCpp::OnFaviconURLChange(CefRefPtr browser, + const std::vector& icon_urls) { + if (CEF_MEMBER_MISSING(struct_, on_favicon_urlchange)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Unverified params: icon_urls + + // Translate param: icon_urls; type: string_vec_byref_const + cef_string_list_t icon_urlsList = cef_string_list_alloc(); + DCHECK(icon_urlsList); + if (icon_urlsList) + transfer_string_list_contents(icon_urls, icon_urlsList); + + // Execute + struct_->on_favicon_urlchange(struct_, + CefBrowserCppToC::Wrap(browser), + icon_urlsList); + + // Restore param:icon_urls; type: string_vec_byref_const + if (icon_urlsList) + cef_string_list_free(icon_urlsList); +} + +bool CefDisplayHandlerCToCpp::OnTooltip(CefRefPtr browser, + CefString& text) { + if (CEF_MEMBER_MISSING(struct_, on_tooltip)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Unverified params: text + + // Execute + int _retval = struct_->on_tooltip(struct_, + CefBrowserCppToC::Wrap(browser), + text.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + +void CefDisplayHandlerCToCpp::OnStatusMessage(CefRefPtr browser, + const CefString& value) { + if (CEF_MEMBER_MISSING(struct_, on_status_message)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Unverified params: value + + // Execute + struct_->on_status_message(struct_, + CefBrowserCppToC::Wrap(browser), + value.GetStruct()); +} + +bool CefDisplayHandlerCToCpp::OnConsoleMessage(CefRefPtr browser, + const CefString& message, const CefString& source, int line) { + if (CEF_MEMBER_MISSING(struct_, on_console_message)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Unverified params: message, source + + // Execute + int _retval = struct_->on_console_message(struct_, + CefBrowserCppToC::Wrap(browser), + message.GetStruct(), + source.GetStruct(), + line); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/display_handler_ctocpp.h b/libcef_dll/ctocpp/display_handler_ctocpp.h new file mode 100644 index 000000000..f44651f58 --- /dev/null +++ b/libcef_dll/ctocpp/display_handler_ctocpp.h @@ -0,0 +1,52 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DISPLAY_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DISPLAY_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include +#include "include/cef_display_handler.h" +#include "include/capi/cef_display_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefDisplayHandlerCToCpp + : public CefCToCpp { + public: + explicit CefDisplayHandlerCToCpp(cef_display_handler_t* str) + : CefCToCpp(str) {} + + // CefDisplayHandler methods + void OnAddressChange(CefRefPtr browser, CefRefPtr frame, + const CefString& url) override; + void OnTitleChange(CefRefPtr browser, + const CefString& title) override; + void OnFaviconURLChange(CefRefPtr browser, + const std::vector& icon_urls) override; + bool OnTooltip(CefRefPtr browser, CefString& text) override; + void OnStatusMessage(CefRefPtr browser, + const CefString& value) override; + bool OnConsoleMessage(CefRefPtr browser, const CefString& message, + const CefString& source, int line) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DISPLAY_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/domdocument_ctocpp.cc b/libcef_dll/ctocpp/domdocument_ctocpp.cc new file mode 100644 index 000000000..e4965701c --- /dev/null +++ b/libcef_dll/ctocpp/domdocument_ctocpp.cc @@ -0,0 +1,229 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/domdocument_ctocpp.h" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefDOMDocument::Type CefDOMDocumentCToCpp::GetType() { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return DOM_DOCUMENT_TYPE_UNKNOWN; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dom_document_type_t _retval = struct_->get_type(struct_); + + // Return type: simple + return _retval; +} + +CefRefPtr CefDOMDocumentCToCpp::GetDocument() { + if (CEF_MEMBER_MISSING(struct_, get_document)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_document(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMDocumentCToCpp::GetBody() { + if (CEF_MEMBER_MISSING(struct_, get_body)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_body(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMDocumentCToCpp::GetHead() { + if (CEF_MEMBER_MISSING(struct_, get_head)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_head(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefString CefDOMDocumentCToCpp::GetTitle() { + if (CEF_MEMBER_MISSING(struct_, get_title)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_title(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefDOMDocumentCToCpp::GetElementById( + const CefString& id) { + if (CEF_MEMBER_MISSING(struct_, get_element_by_id)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: id; type: string_byref_const + DCHECK(!id.empty()); + if (id.empty()) + return NULL; + + // Execute + cef_domnode_t* _retval = struct_->get_element_by_id(struct_, + id.GetStruct()); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMDocumentCToCpp::GetFocusedNode() { + if (CEF_MEMBER_MISSING(struct_, get_focused_node)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_focused_node(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +bool CefDOMDocumentCToCpp::HasSelection() { + if (CEF_MEMBER_MISSING(struct_, has_selection)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_selection(struct_); + + // Return type: bool + return _retval?true:false; +} + +int CefDOMDocumentCToCpp::GetSelectionStartOffset() { + if (CEF_MEMBER_MISSING(struct_, get_selection_start_offset)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_selection_start_offset(struct_); + + // Return type: simple + return _retval; +} + +int CefDOMDocumentCToCpp::GetSelectionEndOffset() { + if (CEF_MEMBER_MISSING(struct_, get_selection_end_offset)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_selection_end_offset(struct_); + + // Return type: simple + return _retval; +} + +CefString CefDOMDocumentCToCpp::GetSelectionAsMarkup() { + if (CEF_MEMBER_MISSING(struct_, get_selection_as_markup)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_selection_as_markup(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDOMDocumentCToCpp::GetSelectionAsText() { + if (CEF_MEMBER_MISSING(struct_, get_selection_as_text)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_selection_as_text(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDOMDocumentCToCpp::GetBaseURL() { + if (CEF_MEMBER_MISSING(struct_, get_base_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_base_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDOMDocumentCToCpp::GetCompleteURL(const CefString& partialURL) { + if (CEF_MEMBER_MISSING(struct_, get_complete_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: partialURL; type: string_byref_const + DCHECK(!partialURL.empty()); + if (partialURL.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_complete_url(struct_, + partialURL.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/domdocument_ctocpp.h b/libcef_dll/ctocpp/domdocument_ctocpp.h new file mode 100644 index 000000000..32bb1a6c8 --- /dev/null +++ b/libcef_dll/ctocpp/domdocument_ctocpp.h @@ -0,0 +1,54 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DOMDOCUMENT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOMDOCUMENT_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_dom.h" +#include "include/capi/cef_dom_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefDOMDocumentCToCpp + : public CefCToCpp { + public: + explicit CefDOMDocumentCToCpp(cef_domdocument_t* str) + : CefCToCpp( + str) {} + + // CefDOMDocument methods + virtual Type GetType() OVERRIDE; + virtual CefRefPtr GetDocument() OVERRIDE; + virtual CefRefPtr GetBody() OVERRIDE; + virtual CefRefPtr GetHead() OVERRIDE; + virtual CefString GetTitle() OVERRIDE; + virtual CefRefPtr GetElementById(const CefString& id) OVERRIDE; + virtual CefRefPtr GetFocusedNode() OVERRIDE; + virtual bool HasSelection() OVERRIDE; + virtual int GetSelectionStartOffset() OVERRIDE; + virtual int GetSelectionEndOffset() OVERRIDE; + virtual CefString GetSelectionAsMarkup() OVERRIDE; + virtual CefString GetSelectionAsText() OVERRIDE; + virtual CefString GetBaseURL() OVERRIDE; + virtual CefString GetCompleteURL(const CefString& partialURL) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOMDOCUMENT_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/domnode_ctocpp.cc b/libcef_dll/ctocpp/domnode_ctocpp.cc new file mode 100644 index 000000000..05306b72d --- /dev/null +++ b/libcef_dll/ctocpp/domnode_ctocpp.cc @@ -0,0 +1,412 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/domdocument_ctocpp.h" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefDOMNode::Type CefDOMNodeCToCpp::GetType() { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return DOM_NODE_TYPE_UNSUPPORTED; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dom_node_type_t _retval = struct_->get_type(struct_); + + // Return type: simple + return _retval; +} + +bool CefDOMNodeCToCpp::IsText() { + if (CEF_MEMBER_MISSING(struct_, is_text)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_text(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDOMNodeCToCpp::IsElement() { + if (CEF_MEMBER_MISSING(struct_, is_element)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_element(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDOMNodeCToCpp::IsEditable() { + if (CEF_MEMBER_MISSING(struct_, is_editable)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_editable(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDOMNodeCToCpp::IsFormControlElement() { + if (CEF_MEMBER_MISSING(struct_, is_form_control_element)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_form_control_element(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefDOMNodeCToCpp::GetFormControlElementType() { + if (CEF_MEMBER_MISSING(struct_, get_form_control_element_type)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_form_control_element_type( + struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefDOMNodeCToCpp::IsSame(CefRefPtr that) { + if (CEF_MEMBER_MISSING(struct_, is_same)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: that; type: refptr_same + DCHECK(that.get()); + if (!that.get()) + return false; + + // Execute + int _retval = struct_->is_same(struct_, + CefDOMNodeCToCpp::Unwrap(that)); + + // Return type: bool + return _retval?true:false; +} + +CefString CefDOMNodeCToCpp::GetName() { + if (CEF_MEMBER_MISSING(struct_, get_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDOMNodeCToCpp::GetValue() { + if (CEF_MEMBER_MISSING(struct_, get_value)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_value(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefDOMNodeCToCpp::SetValue(const CefString& value) { + if (CEF_MEMBER_MISSING(struct_, set_value)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: value; type: string_byref_const + DCHECK(!value.empty()); + if (value.empty()) + return false; + + // Execute + int _retval = struct_->set_value(struct_, + value.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefString CefDOMNodeCToCpp::GetAsMarkup() { + if (CEF_MEMBER_MISSING(struct_, get_as_markup)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_as_markup(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefDOMNodeCToCpp::GetDocument() { + if (CEF_MEMBER_MISSING(struct_, get_document)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domdocument_t* _retval = struct_->get_document(struct_); + + // Return type: refptr_same + return CefDOMDocumentCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMNodeCToCpp::GetParent() { + if (CEF_MEMBER_MISSING(struct_, get_parent)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_parent(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMNodeCToCpp::GetPreviousSibling() { + if (CEF_MEMBER_MISSING(struct_, get_previous_sibling)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_previous_sibling(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMNodeCToCpp::GetNextSibling() { + if (CEF_MEMBER_MISSING(struct_, get_next_sibling)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_next_sibling(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +bool CefDOMNodeCToCpp::HasChildren() { + if (CEF_MEMBER_MISSING(struct_, has_children)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_children(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefDOMNodeCToCpp::GetFirstChild() { + if (CEF_MEMBER_MISSING(struct_, get_first_child)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_first_child(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMNodeCToCpp::GetLastChild() { + if (CEF_MEMBER_MISSING(struct_, get_last_child)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_last_child(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefString CefDOMNodeCToCpp::GetElementTagName() { + if (CEF_MEMBER_MISSING(struct_, get_element_tag_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_element_tag_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefDOMNodeCToCpp::HasElementAttributes() { + if (CEF_MEMBER_MISSING(struct_, has_element_attributes)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_element_attributes(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDOMNodeCToCpp::HasElementAttribute(const CefString& attrName) { + if (CEF_MEMBER_MISSING(struct_, has_element_attribute)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: attrName; type: string_byref_const + DCHECK(!attrName.empty()); + if (attrName.empty()) + return false; + + // Execute + int _retval = struct_->has_element_attribute(struct_, + attrName.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefString CefDOMNodeCToCpp::GetElementAttribute(const CefString& attrName) { + if (CEF_MEMBER_MISSING(struct_, get_element_attribute)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: attrName; type: string_byref_const + DCHECK(!attrName.empty()); + if (attrName.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_element_attribute(struct_, + attrName.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefDOMNodeCToCpp::GetElementAttributes(AttributeMap& attrMap) { + if (CEF_MEMBER_MISSING(struct_, get_element_attributes)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: attrMap; type: string_map_single_byref + cef_string_map_t attrMapMap = cef_string_map_alloc(); + DCHECK(attrMapMap); + if (attrMapMap) + transfer_string_map_contents(attrMap, attrMapMap); + + // Execute + struct_->get_element_attributes(struct_, + attrMapMap); + + // Restore param:attrMap; type: string_map_single_byref + if (attrMapMap) { + attrMap.clear(); + transfer_string_map_contents(attrMapMap, attrMap); + cef_string_map_free(attrMapMap); + } +} + +bool CefDOMNodeCToCpp::SetElementAttribute(const CefString& attrName, + const CefString& value) { + if (CEF_MEMBER_MISSING(struct_, set_element_attribute)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: attrName; type: string_byref_const + DCHECK(!attrName.empty()); + if (attrName.empty()) + return false; + // Verify param: value; type: string_byref_const + DCHECK(!value.empty()); + if (value.empty()) + return false; + + // Execute + int _retval = struct_->set_element_attribute(struct_, + attrName.GetStruct(), + value.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefString CefDOMNodeCToCpp::GetElementInnerText() { + if (CEF_MEMBER_MISSING(struct_, get_element_inner_text)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_element_inner_text(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/domnode_ctocpp.h b/libcef_dll/ctocpp/domnode_ctocpp.h new file mode 100644 index 000000000..24b42e67a --- /dev/null +++ b/libcef_dll/ctocpp/domnode_ctocpp.h @@ -0,0 +1,64 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_dom.h" +#include "include/capi/cef_dom_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefDOMNodeCToCpp + : public CefCToCpp { + public: + explicit CefDOMNodeCToCpp(cef_domnode_t* str) + : CefCToCpp(str) {} + + // CefDOMNode methods + virtual Type GetType() OVERRIDE; + virtual bool IsText() OVERRIDE; + virtual bool IsElement() OVERRIDE; + virtual bool IsEditable() OVERRIDE; + virtual bool IsFormControlElement() OVERRIDE; + virtual CefString GetFormControlElementType() OVERRIDE; + virtual bool IsSame(CefRefPtr that) OVERRIDE; + virtual CefString GetName() OVERRIDE; + virtual CefString GetValue() OVERRIDE; + virtual bool SetValue(const CefString& value) OVERRIDE; + virtual CefString GetAsMarkup() OVERRIDE; + virtual CefRefPtr GetDocument() OVERRIDE; + virtual CefRefPtr GetParent() OVERRIDE; + virtual CefRefPtr GetPreviousSibling() OVERRIDE; + virtual CefRefPtr GetNextSibling() OVERRIDE; + virtual bool HasChildren() OVERRIDE; + virtual CefRefPtr GetFirstChild() OVERRIDE; + virtual CefRefPtr GetLastChild() OVERRIDE; + virtual CefString GetElementTagName() OVERRIDE; + virtual bool HasElementAttributes() OVERRIDE; + virtual bool HasElementAttribute(const CefString& attrName) OVERRIDE; + virtual CefString GetElementAttribute(const CefString& attrName) OVERRIDE; + virtual void GetElementAttributes(AttributeMap& attrMap) OVERRIDE; + virtual bool SetElementAttribute(const CefString& attrName, + const CefString& value) OVERRIDE; + virtual CefString GetElementInnerText() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOMNODE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/domvisitor_ctocpp.cc b/libcef_dll/ctocpp/domvisitor_ctocpp.cc new file mode 100644 index 000000000..51db2b04f --- /dev/null +++ b/libcef_dll/ctocpp/domvisitor_ctocpp.cc @@ -0,0 +1,40 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/domdocument_cpptoc.h" +#include "libcef_dll/ctocpp/domvisitor_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefDOMVisitorCToCpp::Visit(CefRefPtr document) { + if (CEF_MEMBER_MISSING(struct_, visit)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: document; type: refptr_diff + DCHECK(document.get()); + if (!document.get()) + return; + + // Execute + struct_->visit(struct_, + CefDOMDocumentCppToC::Wrap(document)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/domvisitor_ctocpp.h b/libcef_dll/ctocpp/domvisitor_ctocpp.h new file mode 100644 index 000000000..eb5b8062d --- /dev/null +++ b/libcef_dll/ctocpp/domvisitor_ctocpp.h @@ -0,0 +1,39 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DOMVISITOR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOMVISITOR_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_dom.h" +#include "include/capi/cef_dom_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefDOMVisitorCToCpp + : public CefCToCpp { + public: + explicit CefDOMVisitorCToCpp(cef_domvisitor_t* str) + : CefCToCpp(str) {} + + // CefDOMVisitor methods + void Visit(CefRefPtr document) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOMVISITOR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/download_handler_ctocpp.cc b/libcef_dll/ctocpp/download_handler_ctocpp.cc new file mode 100644 index 000000000..e1c1475c8 --- /dev/null +++ b/libcef_dll/ctocpp/download_handler_ctocpp.cc @@ -0,0 +1,88 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/before_download_callback_cpptoc.h" +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/download_item_cpptoc.h" +#include "libcef_dll/cpptoc/download_item_callback_cpptoc.h" +#include "libcef_dll/ctocpp/download_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefDownloadHandlerCToCpp::OnBeforeDownload(CefRefPtr browser, + CefRefPtr download_item, const CefString& suggested_name, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_before_download)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: download_item; type: refptr_diff + DCHECK(download_item.get()); + if (!download_item.get()) + return; + // Verify param: suggested_name; type: string_byref_const + DCHECK(!suggested_name.empty()); + if (suggested_name.empty()) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return; + + // Execute + struct_->on_before_download(struct_, + CefBrowserCppToC::Wrap(browser), + CefDownloadItemCppToC::Wrap(download_item), + suggested_name.GetStruct(), + CefBeforeDownloadCallbackCppToC::Wrap(callback)); +} + +void CefDownloadHandlerCToCpp::OnDownloadUpdated(CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_download_updated)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: download_item; type: refptr_diff + DCHECK(download_item.get()); + if (!download_item.get()) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return; + + // Execute + struct_->on_download_updated(struct_, + CefBrowserCppToC::Wrap(browser), + CefDownloadItemCppToC::Wrap(download_item), + CefDownloadItemCallbackCppToC::Wrap(callback)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/download_handler_ctocpp.h b/libcef_dll/ctocpp/download_handler_ctocpp.h new file mode 100644 index 000000000..9796d36b9 --- /dev/null +++ b/libcef_dll/ctocpp/download_handler_ctocpp.h @@ -0,0 +1,47 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_download_handler.h" +#include "include/capi/cef_download_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefDownloadHandlerCToCpp + : public CefCToCpp { + public: + explicit CefDownloadHandlerCToCpp(cef_download_handler_t* str) + : CefCToCpp(str) {} + + // CefDownloadHandler methods + void OnBeforeDownload(CefRefPtr browser, + CefRefPtr download_item, + const CefString& suggested_name, + CefRefPtr callback) override; + void OnDownloadUpdated(CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/download_item_callback_ctocpp.cc b/libcef_dll/ctocpp/download_item_callback_ctocpp.cc new file mode 100644 index 000000000..e219bbee1 --- /dev/null +++ b/libcef_dll/ctocpp/download_item_callback_ctocpp.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/download_item_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefDownloadItemCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + +void CefDownloadItemCallbackCToCpp::Pause() { + if (CEF_MEMBER_MISSING(struct_, pause)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->pause(struct_); +} + +void CefDownloadItemCallbackCToCpp::Resume() { + if (CEF_MEMBER_MISSING(struct_, resume)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->resume(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/download_item_callback_ctocpp.h b/libcef_dll/ctocpp/download_item_callback_ctocpp.h new file mode 100644 index 000000000..c59ded45d --- /dev/null +++ b/libcef_dll/ctocpp/download_item_callback_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_ITEM_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_ITEM_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_download_handler.h" +#include "include/capi/cef_download_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefDownloadItemCallbackCToCpp + : public CefCToCpp { + public: + explicit CefDownloadItemCallbackCToCpp(cef_download_item_callback_t* str) + : CefCToCpp(str) {} + + // CefDownloadItemCallback methods + virtual void Cancel() OVERRIDE; + virtual void Pause() OVERRIDE; + virtual void Resume() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_ITEM_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/download_item_ctocpp.cc b/libcef_dll/ctocpp/download_item_ctocpp.cc new file mode 100644 index 000000000..908739a89 --- /dev/null +++ b/libcef_dll/ctocpp/download_item_ctocpp.cc @@ -0,0 +1,256 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/download_item_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefDownloadItemCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDownloadItemCToCpp::IsInProgress() { + if (CEF_MEMBER_MISSING(struct_, is_in_progress)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_in_progress(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDownloadItemCToCpp::IsComplete() { + if (CEF_MEMBER_MISSING(struct_, is_complete)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_complete(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDownloadItemCToCpp::IsCanceled() { + if (CEF_MEMBER_MISSING(struct_, is_canceled)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_canceled(struct_); + + // Return type: bool + return _retval?true:false; +} + +int64 CefDownloadItemCToCpp::GetCurrentSpeed() { + if (CEF_MEMBER_MISSING(struct_, get_current_speed)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->get_current_speed(struct_); + + // Return type: simple + return _retval; +} + +int CefDownloadItemCToCpp::GetPercentComplete() { + if (CEF_MEMBER_MISSING(struct_, get_percent_complete)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_percent_complete(struct_); + + // Return type: simple + return _retval; +} + +int64 CefDownloadItemCToCpp::GetTotalBytes() { + if (CEF_MEMBER_MISSING(struct_, get_total_bytes)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->get_total_bytes(struct_); + + // Return type: simple + return _retval; +} + +int64 CefDownloadItemCToCpp::GetReceivedBytes() { + if (CEF_MEMBER_MISSING(struct_, get_received_bytes)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->get_received_bytes(struct_); + + // Return type: simple + return _retval; +} + +CefTime CefDownloadItemCToCpp::GetStartTime() { + if (CEF_MEMBER_MISSING(struct_, get_start_time)) + return CefTime(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_time_t _retval = struct_->get_start_time(struct_); + + // Return type: simple + return _retval; +} + +CefTime CefDownloadItemCToCpp::GetEndTime() { + if (CEF_MEMBER_MISSING(struct_, get_end_time)) + return CefTime(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_time_t _retval = struct_->get_end_time(struct_); + + // Return type: simple + return _retval; +} + +CefString CefDownloadItemCToCpp::GetFullPath() { + if (CEF_MEMBER_MISSING(struct_, get_full_path)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_full_path(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +uint32 CefDownloadItemCToCpp::GetId() { + if (CEF_MEMBER_MISSING(struct_, get_id)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + uint32 _retval = struct_->get_id(struct_); + + // Return type: simple + return _retval; +} + +CefString CefDownloadItemCToCpp::GetURL() { + if (CEF_MEMBER_MISSING(struct_, get_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDownloadItemCToCpp::GetOriginalUrl() { + if (CEF_MEMBER_MISSING(struct_, get_original_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_original_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDownloadItemCToCpp::GetSuggestedFileName() { + if (CEF_MEMBER_MISSING(struct_, get_suggested_file_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_suggested_file_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDownloadItemCToCpp::GetContentDisposition() { + if (CEF_MEMBER_MISSING(struct_, get_content_disposition)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_content_disposition(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDownloadItemCToCpp::GetMimeType() { + if (CEF_MEMBER_MISSING(struct_, get_mime_type)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_mime_type(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/download_item_ctocpp.h b/libcef_dll/ctocpp/download_item_ctocpp.h new file mode 100644 index 000000000..af0cb5f05 --- /dev/null +++ b/libcef_dll/ctocpp/download_item_ctocpp.h @@ -0,0 +1,57 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_ITEM_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_ITEM_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_download_item.h" +#include "include/capi/cef_download_item_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefDownloadItemCToCpp + : public CefCToCpp { + public: + explicit CefDownloadItemCToCpp(cef_download_item_t* str) + : CefCToCpp( + str) {} + + // CefDownloadItem methods + virtual bool IsValid() OVERRIDE; + virtual bool IsInProgress() OVERRIDE; + virtual bool IsComplete() OVERRIDE; + virtual bool IsCanceled() OVERRIDE; + virtual int64 GetCurrentSpeed() OVERRIDE; + virtual int GetPercentComplete() OVERRIDE; + virtual int64 GetTotalBytes() OVERRIDE; + virtual int64 GetReceivedBytes() OVERRIDE; + virtual CefTime GetStartTime() OVERRIDE; + virtual CefTime GetEndTime() OVERRIDE; + virtual CefString GetFullPath() OVERRIDE; + virtual uint32 GetId() OVERRIDE; + virtual CefString GetURL() OVERRIDE; + virtual CefString GetOriginalUrl() OVERRIDE; + virtual CefString GetSuggestedFileName() OVERRIDE; + virtual CefString GetContentDisposition() OVERRIDE; + virtual CefString GetMimeType() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_ITEM_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/drag_data_ctocpp.cc b/libcef_dll/ctocpp/drag_data_ctocpp.cc new file mode 100644 index 000000000..a9c84563f --- /dev/null +++ b/libcef_dll/ctocpp/drag_data_ctocpp.cc @@ -0,0 +1,358 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/drag_data_ctocpp.h" +#include "libcef_dll/ctocpp/stream_writer_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefDragData::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_drag_data_t* _retval = cef_drag_data_create(); + + // Return type: refptr_same + return CefDragDataCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefDragDataCToCpp::Clone() { + if (CEF_MEMBER_MISSING(struct_, clone)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_drag_data_t* _retval = struct_->clone(struct_); + + // Return type: refptr_same + return CefDragDataCToCpp::Wrap(_retval); +} + +bool CefDragDataCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDragDataCToCpp::IsLink() { + if (CEF_MEMBER_MISSING(struct_, is_link)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_link(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDragDataCToCpp::IsFragment() { + if (CEF_MEMBER_MISSING(struct_, is_fragment)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_fragment(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDragDataCToCpp::IsFile() { + if (CEF_MEMBER_MISSING(struct_, is_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefDragDataCToCpp::GetLinkURL() { + if (CEF_MEMBER_MISSING(struct_, get_link_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_link_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDragDataCToCpp::GetLinkTitle() { + if (CEF_MEMBER_MISSING(struct_, get_link_title)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_link_title(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDragDataCToCpp::GetLinkMetadata() { + if (CEF_MEMBER_MISSING(struct_, get_link_metadata)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_link_metadata(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDragDataCToCpp::GetFragmentText() { + if (CEF_MEMBER_MISSING(struct_, get_fragment_text)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_fragment_text(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDragDataCToCpp::GetFragmentHtml() { + if (CEF_MEMBER_MISSING(struct_, get_fragment_html)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_fragment_html(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDragDataCToCpp::GetFragmentBaseURL() { + if (CEF_MEMBER_MISSING(struct_, get_fragment_base_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_fragment_base_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefDragDataCToCpp::GetFileName() { + if (CEF_MEMBER_MISSING(struct_, get_file_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_file_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +size_t CefDragDataCToCpp::GetFileContents(CefRefPtr writer) { + if (CEF_MEMBER_MISSING(struct_, get_file_contents)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: writer + + // Execute + size_t _retval = struct_->get_file_contents(struct_, + CefStreamWriterCToCpp::Unwrap(writer)); + + // Return type: simple + return _retval; +} + +bool CefDragDataCToCpp::GetFileNames(std::vector& names) { + if (CEF_MEMBER_MISSING(struct_, get_file_names)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: names; type: string_vec_byref + cef_string_list_t namesList = cef_string_list_alloc(); + DCHECK(namesList); + if (namesList) + transfer_string_list_contents(names, namesList); + + // Execute + int _retval = struct_->get_file_names(struct_, + namesList); + + // Restore param:names; type: string_vec_byref + if (namesList) { + names.clear(); + transfer_string_list_contents(namesList, names); + cef_string_list_free(namesList); + } + + // Return type: bool + return _retval?true:false; +} + +void CefDragDataCToCpp::SetLinkURL(const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, set_link_url)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: url + + // Execute + struct_->set_link_url(struct_, + url.GetStruct()); +} + +void CefDragDataCToCpp::SetLinkTitle(const CefString& title) { + if (CEF_MEMBER_MISSING(struct_, set_link_title)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: title + + // Execute + struct_->set_link_title(struct_, + title.GetStruct()); +} + +void CefDragDataCToCpp::SetLinkMetadata(const CefString& data) { + if (CEF_MEMBER_MISSING(struct_, set_link_metadata)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: data + + // Execute + struct_->set_link_metadata(struct_, + data.GetStruct()); +} + +void CefDragDataCToCpp::SetFragmentText(const CefString& text) { + if (CEF_MEMBER_MISSING(struct_, set_fragment_text)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: text + + // Execute + struct_->set_fragment_text(struct_, + text.GetStruct()); +} + +void CefDragDataCToCpp::SetFragmentHtml(const CefString& html) { + if (CEF_MEMBER_MISSING(struct_, set_fragment_html)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: html + + // Execute + struct_->set_fragment_html(struct_, + html.GetStruct()); +} + +void CefDragDataCToCpp::SetFragmentBaseURL(const CefString& base_url) { + if (CEF_MEMBER_MISSING(struct_, set_fragment_base_url)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: base_url + + // Execute + struct_->set_fragment_base_url(struct_, + base_url.GetStruct()); +} + +void CefDragDataCToCpp::ResetFileContents() { + if (CEF_MEMBER_MISSING(struct_, reset_file_contents)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->reset_file_contents(struct_); +} + +void CefDragDataCToCpp::AddFile(const CefString& path, + const CefString& display_name) { + if (CEF_MEMBER_MISSING(struct_, add_file)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + // Unverified params: display_name + + // Execute + struct_->add_file(struct_, + path.GetStruct(), + display_name.GetStruct()); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/drag_data_ctocpp.h b/libcef_dll/ctocpp/drag_data_ctocpp.h new file mode 100644 index 000000000..e7c3038f6 --- /dev/null +++ b/libcef_dll/ctocpp/drag_data_ctocpp.h @@ -0,0 +1,62 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DRAG_DATA_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DRAG_DATA_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_drag_data.h" +#include "include/capi/cef_drag_data_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefDragDataCToCpp + : public CefCToCpp { + public: + explicit CefDragDataCToCpp(cef_drag_data_t* str) + : CefCToCpp(str) {} + + // CefDragData methods + virtual CefRefPtr Clone() OVERRIDE; + virtual bool IsReadOnly() OVERRIDE; + virtual bool IsLink() OVERRIDE; + virtual bool IsFragment() OVERRIDE; + virtual bool IsFile() OVERRIDE; + virtual CefString GetLinkURL() OVERRIDE; + virtual CefString GetLinkTitle() OVERRIDE; + virtual CefString GetLinkMetadata() OVERRIDE; + virtual CefString GetFragmentText() OVERRIDE; + virtual CefString GetFragmentHtml() OVERRIDE; + virtual CefString GetFragmentBaseURL() OVERRIDE; + virtual CefString GetFileName() OVERRIDE; + virtual size_t GetFileContents(CefRefPtr writer) OVERRIDE; + virtual bool GetFileNames(std::vector& names) OVERRIDE; + virtual void SetLinkURL(const CefString& url) OVERRIDE; + virtual void SetLinkTitle(const CefString& title) OVERRIDE; + virtual void SetLinkMetadata(const CefString& data) OVERRIDE; + virtual void SetFragmentText(const CefString& text) OVERRIDE; + virtual void SetFragmentHtml(const CefString& html) OVERRIDE; + virtual void SetFragmentBaseURL(const CefString& base_url) OVERRIDE; + virtual void ResetFileContents() OVERRIDE; + virtual void AddFile(const CefString& path, + const CefString& display_name) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DRAG_DATA_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/drag_handler_ctocpp.cc b/libcef_dll/ctocpp/drag_handler_ctocpp.cc new file mode 100644 index 000000000..52e781900 --- /dev/null +++ b/libcef_dll/ctocpp/drag_handler_ctocpp.cc @@ -0,0 +1,51 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/ctocpp/drag_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefDragHandlerCToCpp::OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, DragOperationsMask mask) { + if (CEF_MEMBER_MISSING(struct_, on_drag_enter)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: dragData; type: refptr_diff + DCHECK(dragData.get()); + if (!dragData.get()) + return false; + + // Execute + int _retval = struct_->on_drag_enter(struct_, + CefBrowserCppToC::Wrap(browser), + CefDragDataCppToC::Wrap(dragData), + mask); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/drag_handler_ctocpp.h b/libcef_dll/ctocpp/drag_handler_ctocpp.h new file mode 100644 index 000000000..b342ab895 --- /dev/null +++ b/libcef_dll/ctocpp/drag_handler_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_DRAG_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DRAG_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_drag_handler.h" +#include "include/capi/cef_drag_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefDragHandlerCToCpp + : public CefCToCpp { + public: + explicit CefDragHandlerCToCpp(cef_drag_handler_t* str) + : CefCToCpp( + str) {} + + // CefDragHandler methods + bool OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, DragOperationsMask mask) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DRAG_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/end_tracing_callback_ctocpp.cc b/libcef_dll/ctocpp/end_tracing_callback_ctocpp.cc new file mode 100644 index 000000000..9f88e054b --- /dev/null +++ b/libcef_dll/ctocpp/end_tracing_callback_ctocpp.cc @@ -0,0 +1,40 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/end_tracing_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefEndTracingCallbackCToCpp::OnEndTracingComplete( + const CefString& tracing_file) { + if (CEF_MEMBER_MISSING(struct_, on_end_tracing_complete)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: tracing_file; type: string_byref_const + DCHECK(!tracing_file.empty()); + if (tracing_file.empty()) + return; + + // Execute + struct_->on_end_tracing_complete(struct_, + tracing_file.GetStruct()); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/end_tracing_callback_ctocpp.h b/libcef_dll/ctocpp/end_tracing_callback_ctocpp.h new file mode 100644 index 000000000..dedba2766 --- /dev/null +++ b/libcef_dll/ctocpp/end_tracing_callback_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_END_TRACING_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_END_TRACING_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_trace.h" +#include "include/capi/cef_trace_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefEndTracingCallbackCToCpp + : public CefCToCpp { + public: + explicit CefEndTracingCallbackCToCpp(cef_end_tracing_callback_t* str) + : CefCToCpp(str) {} + + // CefEndTracingCallback methods + void OnEndTracingComplete(const CefString& tracing_file) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_END_TRACING_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/file_dialog_callback_ctocpp.cc b/libcef_dll/ctocpp/file_dialog_callback_ctocpp.cc new file mode 100644 index 000000000..df8324c5d --- /dev/null +++ b/libcef_dll/ctocpp/file_dialog_callback_ctocpp.cc @@ -0,0 +1,63 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/file_dialog_callback_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefFileDialogCallbackCToCpp::Continue(int selected_accept_filter, + const std::vector& file_paths) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return; + // Unverified params: file_paths + + // Translate param: file_paths; type: string_vec_byref_const + cef_string_list_t file_pathsList = cef_string_list_alloc(); + DCHECK(file_pathsList); + if (file_pathsList) + transfer_string_list_contents(file_paths, file_pathsList); + + // Execute + struct_->cont(struct_, + selected_accept_filter, + file_pathsList); + + // Restore param:file_paths; type: string_vec_byref_const + if (file_pathsList) + cef_string_list_free(file_pathsList); +} + +void CefFileDialogCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/file_dialog_callback_ctocpp.h b/libcef_dll/ctocpp/file_dialog_callback_ctocpp.h new file mode 100644 index 000000000..92a329e41 --- /dev/null +++ b/libcef_dll/ctocpp/file_dialog_callback_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_FILE_DIALOG_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_FILE_DIALOG_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_dialog_handler.h" +#include "include/capi/cef_dialog_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefFileDialogCallbackCToCpp + : public CefCToCpp { + public: + explicit CefFileDialogCallbackCToCpp(cef_file_dialog_callback_t* str) + : CefCToCpp(str) {} + + // CefFileDialogCallback methods + virtual void Continue(int selected_accept_filter, + const std::vector& file_paths) OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_FILE_DIALOG_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/find_handler_ctocpp.cc b/libcef_dll/ctocpp/find_handler_ctocpp.cc new file mode 100644 index 000000000..55c6641de --- /dev/null +++ b/libcef_dll/ctocpp/find_handler_ctocpp.cc @@ -0,0 +1,47 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/ctocpp/find_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefFindHandlerCToCpp::OnFindResult(CefRefPtr browser, + int identifier, int count, const CefRect& selectionRect, + int activeMatchOrdinal, bool finalUpdate) { + if (CEF_MEMBER_MISSING(struct_, on_find_result)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_find_result(struct_, + CefBrowserCppToC::Wrap(browser), + identifier, + count, + &selectionRect, + activeMatchOrdinal, + finalUpdate); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/find_handler_ctocpp.h b/libcef_dll/ctocpp/find_handler_ctocpp.h new file mode 100644 index 000000000..401473625 --- /dev/null +++ b/libcef_dll/ctocpp/find_handler_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_FIND_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_FIND_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_find_handler.h" +#include "include/capi/cef_find_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefFindHandlerCToCpp + : public CefCToCpp { + public: + explicit CefFindHandlerCToCpp(cef_find_handler_t* str) + : CefCToCpp( + str) {} + + // CefFindHandler methods + void OnFindResult(CefRefPtr browser, int identifier, int count, + const CefRect& selectionRect, int activeMatchOrdinal, + bool finalUpdate) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_FIND_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/focus_handler_ctocpp.cc b/libcef_dll/ctocpp/focus_handler_ctocpp.cc new file mode 100644 index 000000000..ee1c9eed5 --- /dev/null +++ b/libcef_dll/ctocpp/focus_handler_ctocpp.cc @@ -0,0 +1,79 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/ctocpp/focus_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefFocusHandlerCToCpp::OnTakeFocus(CefRefPtr browser, + bool next) { + if (CEF_MEMBER_MISSING(struct_, on_take_focus)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_take_focus(struct_, + CefBrowserCppToC::Wrap(browser), + next); +} + +bool CefFocusHandlerCToCpp::OnSetFocus(CefRefPtr browser, + FocusSource source) { + if (CEF_MEMBER_MISSING(struct_, on_set_focus)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->on_set_focus(struct_, + CefBrowserCppToC::Wrap(browser), + source); + + // Return type: bool + return _retval?true:false; +} + +void CefFocusHandlerCToCpp::OnGotFocus(CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_got_focus)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_got_focus(struct_, + CefBrowserCppToC::Wrap(browser)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/focus_handler_ctocpp.h b/libcef_dll/ctocpp/focus_handler_ctocpp.h new file mode 100644 index 000000000..594e2a682 --- /dev/null +++ b/libcef_dll/ctocpp/focus_handler_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_FOCUS_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_FOCUS_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_focus_handler.h" +#include "include/capi/cef_focus_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefFocusHandlerCToCpp + : public CefCToCpp { + public: + explicit CefFocusHandlerCToCpp(cef_focus_handler_t* str) + : CefCToCpp( + str) {} + + // CefFocusHandler methods + void OnTakeFocus(CefRefPtr browser, bool next) override; + bool OnSetFocus(CefRefPtr browser, FocusSource source) override; + void OnGotFocus(CefRefPtr browser) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_FOCUS_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/frame_ctocpp.cc b/libcef_dll/ctocpp/frame_ctocpp.cc new file mode 100644 index 000000000..63c2c0c63 --- /dev/null +++ b/libcef_dll/ctocpp/frame_ctocpp.cc @@ -0,0 +1,351 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/domvisitor_cpptoc.h" +#include "libcef_dll/cpptoc/string_visitor_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefFrameCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefFrameCToCpp::Undo() { + if (CEF_MEMBER_MISSING(struct_, undo)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->undo(struct_); +} + +void CefFrameCToCpp::Redo() { + if (CEF_MEMBER_MISSING(struct_, redo)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->redo(struct_); +} + +void CefFrameCToCpp::Cut() { + if (CEF_MEMBER_MISSING(struct_, cut)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cut(struct_); +} + +void CefFrameCToCpp::Copy() { + if (CEF_MEMBER_MISSING(struct_, copy)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->copy(struct_); +} + +void CefFrameCToCpp::Paste() { + if (CEF_MEMBER_MISSING(struct_, paste)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->paste(struct_); +} + +void CefFrameCToCpp::Delete() { + if (CEF_MEMBER_MISSING(struct_, del)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->del(struct_); +} + +void CefFrameCToCpp::SelectAll() { + if (CEF_MEMBER_MISSING(struct_, select_all)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->select_all(struct_); +} + +void CefFrameCToCpp::ViewSource() { + if (CEF_MEMBER_MISSING(struct_, view_source)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->view_source(struct_); +} + +void CefFrameCToCpp::GetSource(CefRefPtr visitor) { + if (CEF_MEMBER_MISSING(struct_, get_source)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return; + + // Execute + struct_->get_source(struct_, + CefStringVisitorCppToC::Wrap(visitor)); +} + +void CefFrameCToCpp::GetText(CefRefPtr visitor) { + if (CEF_MEMBER_MISSING(struct_, get_text)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return; + + // Execute + struct_->get_text(struct_, + CefStringVisitorCppToC::Wrap(visitor)); +} + +void CefFrameCToCpp::LoadRequest(CefRefPtr request) { + if (CEF_MEMBER_MISSING(struct_, load_request)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_same + DCHECK(request.get()); + if (!request.get()) + return; + + // Execute + struct_->load_request(struct_, + CefRequestCToCpp::Unwrap(request)); +} + +void CefFrameCToCpp::LoadURL(const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, load_url)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->load_url(struct_, + url.GetStruct()); +} + +void CefFrameCToCpp::LoadString(const CefString& string_val, + const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, load_string)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: string_val; type: string_byref_const + DCHECK(!string_val.empty()); + if (string_val.empty()) + return; + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->load_string(struct_, + string_val.GetStruct(), + url.GetStruct()); +} + +void CefFrameCToCpp::ExecuteJavaScript(const CefString& code, + const CefString& script_url, int start_line) { + if (CEF_MEMBER_MISSING(struct_, execute_java_script)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: code; type: string_byref_const + DCHECK(!code.empty()); + if (code.empty()) + return; + // Unverified params: script_url + + // Execute + struct_->execute_java_script(struct_, + code.GetStruct(), + script_url.GetStruct(), + start_line); +} + +bool CefFrameCToCpp::IsMain() { + if (CEF_MEMBER_MISSING(struct_, is_main)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_main(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefFrameCToCpp::IsFocused() { + if (CEF_MEMBER_MISSING(struct_, is_focused)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_focused(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefFrameCToCpp::GetName() { + if (CEF_MEMBER_MISSING(struct_, get_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int64 CefFrameCToCpp::GetIdentifier() { + if (CEF_MEMBER_MISSING(struct_, get_identifier)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->get_identifier(struct_); + + // Return type: simple + return _retval; +} + +CefRefPtr CefFrameCToCpp::GetParent() { + if (CEF_MEMBER_MISSING(struct_, get_parent)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_frame_t* _retval = struct_->get_parent(struct_); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +CefString CefFrameCToCpp::GetURL() { + if (CEF_MEMBER_MISSING(struct_, get_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefFrameCToCpp::GetBrowser() { + if (CEF_MEMBER_MISSING(struct_, get_browser)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_browser_t* _retval = struct_->get_browser(struct_); + + // Return type: refptr_same + return CefBrowserCToCpp::Wrap(_retval); +} + +CefRefPtr CefFrameCToCpp::GetV8Context() { + if (CEF_MEMBER_MISSING(struct_, get_v8context)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8context_t* _retval = struct_->get_v8context(struct_); + + // Return type: refptr_same + return CefV8ContextCToCpp::Wrap(_retval); +} + +void CefFrameCToCpp::VisitDOM(CefRefPtr visitor) { + if (CEF_MEMBER_MISSING(struct_, visit_dom)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return; + + // Execute + struct_->visit_dom(struct_, + CefDOMVisitorCppToC::Wrap(visitor)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/frame_ctocpp.h b/libcef_dll/ctocpp/frame_ctocpp.h new file mode 100644 index 000000000..c2c2720d1 --- /dev/null +++ b/libcef_dll/ctocpp/frame_ctocpp.h @@ -0,0 +1,68 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_FRAME_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_FRAME_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_frame.h" +#include "include/capi/cef_frame_capi.h" +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefFrameCToCpp + : public CefCToCpp { + public: + explicit CefFrameCToCpp(cef_frame_t* str) + : CefCToCpp(str) {} + + // CefFrame methods + virtual bool IsValid() OVERRIDE; + virtual void Undo() OVERRIDE; + virtual void Redo() OVERRIDE; + virtual void Cut() OVERRIDE; + virtual void Copy() OVERRIDE; + virtual void Paste() OVERRIDE; + virtual void Delete() OVERRIDE; + virtual void SelectAll() OVERRIDE; + virtual void ViewSource() OVERRIDE; + virtual void GetSource(CefRefPtr visitor) OVERRIDE; + virtual void GetText(CefRefPtr visitor) OVERRIDE; + virtual void LoadRequest(CefRefPtr request) OVERRIDE; + virtual void LoadURL(const CefString& url) OVERRIDE; + virtual void LoadString(const CefString& string_val, + const CefString& url) OVERRIDE; + virtual void ExecuteJavaScript(const CefString& code, + const CefString& script_url, int start_line) OVERRIDE; + virtual bool IsMain() OVERRIDE; + virtual bool IsFocused() OVERRIDE; + virtual CefString GetName() OVERRIDE; + virtual int64 GetIdentifier() OVERRIDE; + virtual CefRefPtr GetParent() OVERRIDE; + virtual CefString GetURL() OVERRIDE; + virtual CefRefPtr GetBrowser() OVERRIDE; + virtual CefRefPtr GetV8Context() OVERRIDE; + virtual void VisitDOM(CefRefPtr visitor) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_FRAME_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/geolocation_callback_ctocpp.cc b/libcef_dll/ctocpp/geolocation_callback_ctocpp.cc new file mode 100644 index 000000000..f8ef28371 --- /dev/null +++ b/libcef_dll/ctocpp/geolocation_callback_ctocpp.cc @@ -0,0 +1,34 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/geolocation_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefGeolocationCallbackCToCpp::Continue(bool allow) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cont(struct_, + allow); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/geolocation_callback_ctocpp.h b/libcef_dll/ctocpp/geolocation_callback_ctocpp.h new file mode 100644 index 000000000..f71fc49e3 --- /dev/null +++ b/libcef_dll/ctocpp/geolocation_callback_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_GEOLOCATION_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_GEOLOCATION_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_geolocation_handler.h" +#include "include/capi/cef_geolocation_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefGeolocationCallbackCToCpp + : public CefCToCpp { + public: + explicit CefGeolocationCallbackCToCpp(cef_geolocation_callback_t* str) + : CefCToCpp(str) {} + + // CefGeolocationCallback methods + virtual void Continue(bool allow) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_GEOLOCATION_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/geolocation_handler_ctocpp.cc b/libcef_dll/ctocpp/geolocation_handler_ctocpp.cc new file mode 100644 index 000000000..47835d7dd --- /dev/null +++ b/libcef_dll/ctocpp/geolocation_handler_ctocpp.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/geolocation_callback_cpptoc.h" +#include "libcef_dll/ctocpp/geolocation_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefGeolocationHandlerCToCpp::OnRequestGeolocationPermission( + CefRefPtr browser, const CefString& requesting_url, + int request_id, CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_request_geolocation_permission)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: requesting_url; type: string_byref_const + DCHECK(!requesting_url.empty()); + if (requesting_url.empty()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->on_request_geolocation_permission(struct_, + CefBrowserCppToC::Wrap(browser), + requesting_url.GetStruct(), + request_id, + CefGeolocationCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefGeolocationHandlerCToCpp::OnCancelGeolocationPermission( + CefRefPtr browser, const CefString& requesting_url, + int request_id) { + if (CEF_MEMBER_MISSING(struct_, on_cancel_geolocation_permission)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: requesting_url; type: string_byref_const + DCHECK(!requesting_url.empty()); + if (requesting_url.empty()) + return; + + // Execute + struct_->on_cancel_geolocation_permission(struct_, + CefBrowserCppToC::Wrap(browser), + requesting_url.GetStruct(), + request_id); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/geolocation_handler_ctocpp.h b/libcef_dll/ctocpp/geolocation_handler_ctocpp.h new file mode 100644 index 000000000..7e1224e6e --- /dev/null +++ b/libcef_dll/ctocpp/geolocation_handler_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_GEOLOCATION_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_GEOLOCATION_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_geolocation_handler.h" +#include "include/capi/cef_geolocation_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefGeolocationHandlerCToCpp + : public CefCToCpp { + public: + explicit CefGeolocationHandlerCToCpp(cef_geolocation_handler_t* str) + : CefCToCpp(str) {} + + // CefGeolocationHandler methods + bool OnRequestGeolocationPermission(CefRefPtr browser, + const CefString& requesting_url, int request_id, + CefRefPtr callback) override; + void OnCancelGeolocationPermission(CefRefPtr browser, + const CefString& requesting_url, int request_id) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_GEOLOCATION_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/get_geolocation_callback_ctocpp.cc b/libcef_dll/ctocpp/get_geolocation_callback_ctocpp.cc new file mode 100644 index 000000000..066dcf64b --- /dev/null +++ b/libcef_dll/ctocpp/get_geolocation_callback_ctocpp.cc @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/get_geolocation_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefGetGeolocationCallbackCToCpp::OnLocationUpdate( + const CefGeoposition& position) { + if (CEF_MEMBER_MISSING(struct_, on_location_update)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->on_location_update(struct_, + &position); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/ctocpp/get_geolocation_callback_ctocpp.h b/libcef_dll/ctocpp/get_geolocation_callback_ctocpp.h new file mode 100644 index 000000000..47319ac47 --- /dev/null +++ b/libcef_dll/ctocpp/get_geolocation_callback_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_GET_GEOLOCATION_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_GET_GEOLOCATION_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_geolocation.h" +#include "include/capi/cef_geolocation_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefGetGeolocationCallbackCToCpp + : public CefCToCpp { + public: + explicit CefGetGeolocationCallbackCToCpp(cef_get_geolocation_callback_t* str) + : CefCToCpp(str) {} + + // CefGetGeolocationCallback methods + void OnLocationUpdate(const CefGeoposition& position) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_GET_GEOLOCATION_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/jsdialog_callback_ctocpp.cc b/libcef_dll/ctocpp/jsdialog_callback_ctocpp.cc new file mode 100644 index 000000000..60480dec9 --- /dev/null +++ b/libcef_dll/ctocpp/jsdialog_callback_ctocpp.cc @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/jsdialog_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefJSDialogCallbackCToCpp::Continue(bool success, + const CefString& user_input) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: user_input + + // Execute + struct_->cont(struct_, + success, + user_input.GetStruct()); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/jsdialog_callback_ctocpp.h b/libcef_dll/ctocpp/jsdialog_callback_ctocpp.h new file mode 100644 index 000000000..1461424da --- /dev/null +++ b/libcef_dll/ctocpp/jsdialog_callback_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_jsdialog_handler.h" +#include "include/capi/cef_jsdialog_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefJSDialogCallbackCToCpp + : public CefCToCpp { + public: + explicit CefJSDialogCallbackCToCpp(cef_jsdialog_callback_t* str) + : CefCToCpp(str) {} + + // CefJSDialogCallback methods + virtual void Continue(bool success, const CefString& user_input) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc b/libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc new file mode 100644 index 000000000..182902ace --- /dev/null +++ b/libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc @@ -0,0 +1,129 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/jsdialog_callback_cpptoc.h" +#include "libcef_dll/ctocpp/jsdialog_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefJSDialogHandlerCToCpp::OnJSDialog(CefRefPtr browser, + const CefString& origin_url, const CefString& accept_lang, + JSDialogType dialog_type, const CefString& message_text, + const CefString& default_prompt_text, + CefRefPtr callback, bool& suppress_message) { + if (CEF_MEMBER_MISSING(struct_, on_jsdialog)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + // Unverified params: origin_url, accept_lang, message_text, + // default_prompt_text + + // Translate param: suppress_message; type: bool_byref + int suppress_messageInt = suppress_message; + + // Execute + int _retval = struct_->on_jsdialog(struct_, + CefBrowserCppToC::Wrap(browser), + origin_url.GetStruct(), + accept_lang.GetStruct(), + dialog_type, + message_text.GetStruct(), + default_prompt_text.GetStruct(), + CefJSDialogCallbackCppToC::Wrap(callback), + &suppress_messageInt); + + // Restore param:suppress_message; type: bool_byref + suppress_message = suppress_messageInt?true:false; + + // Return type: bool + return _retval?true:false; +} + +bool CefJSDialogHandlerCToCpp::OnBeforeUnloadDialog( + CefRefPtr browser, const CefString& message_text, + bool is_reload, CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_before_unload_dialog)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + // Unverified params: message_text + + // Execute + int _retval = struct_->on_before_unload_dialog(struct_, + CefBrowserCppToC::Wrap(browser), + message_text.GetStruct(), + is_reload, + CefJSDialogCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefJSDialogHandlerCToCpp::OnResetDialogState( + CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_reset_dialog_state)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_reset_dialog_state(struct_, + CefBrowserCppToC::Wrap(browser)); +} + +void CefJSDialogHandlerCToCpp::OnDialogClosed(CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_dialog_closed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_dialog_closed(struct_, + CefBrowserCppToC::Wrap(browser)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/jsdialog_handler_ctocpp.h b/libcef_dll/ctocpp/jsdialog_handler_ctocpp.h new file mode 100644 index 000000000..558ee0cbb --- /dev/null +++ b/libcef_dll/ctocpp/jsdialog_handler_ctocpp.h @@ -0,0 +1,50 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_jsdialog_handler.h" +#include "include/capi/cef_jsdialog_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefJSDialogHandlerCToCpp + : public CefCToCpp { + public: + explicit CefJSDialogHandlerCToCpp(cef_jsdialog_handler_t* str) + : CefCToCpp(str) {} + + // CefJSDialogHandler methods + bool OnJSDialog(CefRefPtr browser, const CefString& origin_url, + const CefString& accept_lang, JSDialogType dialog_type, + const CefString& message_text, const CefString& default_prompt_text, + CefRefPtr callback, + bool& suppress_message) override; + bool OnBeforeUnloadDialog(CefRefPtr browser, + const CefString& message_text, bool is_reload, + CefRefPtr callback) override; + void OnResetDialogState(CefRefPtr browser) override; + void OnDialogClosed(CefRefPtr browser) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/keyboard_handler_ctocpp.cc b/libcef_dll/ctocpp/keyboard_handler_ctocpp.cc new file mode 100644 index 000000000..ed708453b --- /dev/null +++ b/libcef_dll/ctocpp/keyboard_handler_ctocpp.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/ctocpp/keyboard_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefKeyboardHandlerCToCpp::OnPreKeyEvent(CefRefPtr browser, + const CefKeyEvent& event, CefEventHandle os_event, + bool* is_keyboard_shortcut) { + if (CEF_MEMBER_MISSING(struct_, on_pre_key_event)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: is_keyboard_shortcut; type: bool_byaddr + DCHECK(is_keyboard_shortcut); + if (!is_keyboard_shortcut) + return false; + + // Translate param: is_keyboard_shortcut; type: bool_byaddr + int is_keyboard_shortcutInt = is_keyboard_shortcut?*is_keyboard_shortcut:0; + + // Execute + int _retval = struct_->on_pre_key_event(struct_, + CefBrowserCppToC::Wrap(browser), + &event, + os_event, + &is_keyboard_shortcutInt); + + // Restore param:is_keyboard_shortcut; type: bool_byaddr + if (is_keyboard_shortcut) + *is_keyboard_shortcut = is_keyboard_shortcutInt?true:false; + + // Return type: bool + return _retval?true:false; +} + +bool CefKeyboardHandlerCToCpp::OnKeyEvent(CefRefPtr browser, + const CefKeyEvent& event, CefEventHandle os_event) { + if (CEF_MEMBER_MISSING(struct_, on_key_event)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->on_key_event(struct_, + CefBrowserCppToC::Wrap(browser), + &event, + os_event); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/keyboard_handler_ctocpp.h b/libcef_dll/ctocpp/keyboard_handler_ctocpp.h new file mode 100644 index 000000000..88ad45d4f --- /dev/null +++ b/libcef_dll/ctocpp/keyboard_handler_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_KEYBOARD_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_KEYBOARD_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_keyboard_handler.h" +#include "include/capi/cef_keyboard_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefKeyboardHandlerCToCpp + : public CefCToCpp { + public: + explicit CefKeyboardHandlerCToCpp(cef_keyboard_handler_t* str) + : CefCToCpp(str) {} + + // CefKeyboardHandler methods + bool OnPreKeyEvent(CefRefPtr browser, const CefKeyEvent& event, + CefEventHandle os_event, bool* is_keyboard_shortcut) override; + bool OnKeyEvent(CefRefPtr browser, const CefKeyEvent& event, + CefEventHandle os_event) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_KEYBOARD_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/life_span_handler_ctocpp.cc b/libcef_dll/ctocpp/life_span_handler_ctocpp.cc new file mode 100644 index 000000000..33fcffd5f --- /dev/null +++ b/libcef_dll/ctocpp/life_span_handler_ctocpp.cc @@ -0,0 +1,156 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/ctocpp/client_ctocpp.h" +#include "libcef_dll/ctocpp/life_span_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefLifeSpanHandlerCToCpp::OnBeforePopup(CefRefPtr browser, + CefRefPtr frame, const CefString& target_url, + const CefString& target_frame_name, const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, CefRefPtr& client, + CefBrowserSettings& settings, bool* no_javascript_access) { + if (CEF_MEMBER_MISSING(struct_, on_before_popup)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: no_javascript_access; type: bool_byaddr + DCHECK(no_javascript_access); + if (!no_javascript_access) + return false; + // Unverified params: target_url, target_frame_name + + // Translate param: client; type: refptr_same_byref + cef_client_t* clientStruct = NULL; + if (client.get()) + clientStruct = CefClientCToCpp::Unwrap(client); + cef_client_t* clientOrig = clientStruct; + // Translate param: no_javascript_access; type: bool_byaddr + int no_javascript_accessInt = no_javascript_access?*no_javascript_access:0; + + // Execute + int _retval = struct_->on_before_popup(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + target_url.GetStruct(), + target_frame_name.GetStruct(), + &popupFeatures, + &windowInfo, + &clientStruct, + &settings, + &no_javascript_accessInt); + + // Restore param:client; type: refptr_same_byref + if (clientStruct) { + if (clientStruct != clientOrig) { + client = CefClientCToCpp::Wrap(clientStruct); + } + } else { + client = NULL; + } + // Restore param:no_javascript_access; type: bool_byaddr + if (no_javascript_access) + *no_javascript_access = no_javascript_accessInt?true:false; + + // Return type: bool + return _retval?true:false; +} + +void CefLifeSpanHandlerCToCpp::OnAfterCreated(CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_after_created)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_after_created(struct_, + CefBrowserCppToC::Wrap(browser)); +} + +bool CefLifeSpanHandlerCToCpp::RunModal(CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, run_modal)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->run_modal(struct_, + CefBrowserCppToC::Wrap(browser)); + + // Return type: bool + return _retval?true:false; +} + +bool CefLifeSpanHandlerCToCpp::DoClose(CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, do_close)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->do_close(struct_, + CefBrowserCppToC::Wrap(browser)); + + // Return type: bool + return _retval?true:false; +} + +void CefLifeSpanHandlerCToCpp::OnBeforeClose(CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_before_close)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_before_close(struct_, + CefBrowserCppToC::Wrap(browser)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/life_span_handler_ctocpp.h b/libcef_dll/ctocpp/life_span_handler_ctocpp.h new file mode 100644 index 000000000..4129abe74 --- /dev/null +++ b/libcef_dll/ctocpp/life_span_handler_ctocpp.h @@ -0,0 +1,51 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_life_span_handler.h" +#include "include/capi/cef_life_span_handler_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefLifeSpanHandlerCToCpp + : public CefCToCpp { + public: + explicit CefLifeSpanHandlerCToCpp(cef_life_span_handler_t* str) + : CefCToCpp(str) {} + + // CefLifeSpanHandler methods + bool OnBeforePopup(CefRefPtr browser, CefRefPtr frame, + const CefString& target_url, const CefString& target_frame_name, + const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, + CefRefPtr& client, CefBrowserSettings& settings, + bool* no_javascript_access) override; + void OnAfterCreated(CefRefPtr browser) override; + bool RunModal(CefRefPtr browser) override; + bool DoClose(CefRefPtr browser) override; + void OnBeforeClose(CefRefPtr browser) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/list_value_ctocpp.cc b/libcef_dll/ctocpp/list_value_ctocpp.cc new file mode 100644 index 000000000..2b2ee414e --- /dev/null +++ b/libcef_dll/ctocpp/list_value_ctocpp.cc @@ -0,0 +1,476 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/binary_value_ctocpp.h" +#include "libcef_dll/ctocpp/dictionary_value_ctocpp.h" +#include "libcef_dll/ctocpp/list_value_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefListValue::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_list_value_t* _retval = cef_list_value_create(); + + // Return type: refptr_same + return CefListValueCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefListValueCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::IsOwned() { + if (CEF_MEMBER_MISSING(struct_, is_owned)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_owned(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefListValueCToCpp::Copy() { + if (CEF_MEMBER_MISSING(struct_, copy)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_list_value_t* _retval = struct_->copy(struct_); + + // Return type: refptr_same + return CefListValueCToCpp::Wrap(_retval); +} + +bool CefListValueCToCpp::SetSize(size_t size) { + if (CEF_MEMBER_MISSING(struct_, set_size)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_size(struct_, + size); + + // Return type: bool + return _retval?true:false; +} + +size_t CefListValueCToCpp::GetSize() { + if (CEF_MEMBER_MISSING(struct_, get_size)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_size(struct_); + + // Return type: simple + return _retval; +} + +bool CefListValueCToCpp::Clear() { + if (CEF_MEMBER_MISSING(struct_, clear)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->clear(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::Remove(int index) { + if (CEF_MEMBER_MISSING(struct_, remove)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->remove(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +CefValueType CefListValueCToCpp::GetType(int index) { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return VTYPE_INVALID; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return VTYPE_INVALID; + + // Execute + cef_value_type_t _retval = struct_->get_type(struct_, + index); + + // Return type: simple + return _retval; +} + +bool CefListValueCToCpp::GetBool(int index) { + if (CEF_MEMBER_MISSING(struct_, get_bool)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->get_bool(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +int CefListValueCToCpp::GetInt(int index) { + if (CEF_MEMBER_MISSING(struct_, get_int)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + int _retval = struct_->get_int(struct_, + index); + + // Return type: simple + return _retval; +} + +double CefListValueCToCpp::GetDouble(int index) { + if (CEF_MEMBER_MISSING(struct_, get_double)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return 0; + + // Execute + double _retval = struct_->get_double(struct_, + index); + + // Return type: simple + return _retval; +} + +CefString CefListValueCToCpp::GetString(int index) { + if (CEF_MEMBER_MISSING(struct_, get_string)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_string(struct_, + index); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefListValueCToCpp::GetBinary(int index) { + if (CEF_MEMBER_MISSING(struct_, get_binary)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + cef_binary_value_t* _retval = struct_->get_binary(struct_, + index); + + // Return type: refptr_same + return CefBinaryValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefListValueCToCpp::GetDictionary(int index) { + if (CEF_MEMBER_MISSING(struct_, get_dictionary)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + cef_dictionary_value_t* _retval = struct_->get_dictionary(struct_, + index); + + // Return type: refptr_same + return CefDictionaryValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefListValueCToCpp::GetList(int index) { + if (CEF_MEMBER_MISSING(struct_, get_list)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + cef_list_value_t* _retval = struct_->get_list(struct_, + index); + + // Return type: refptr_same + return CefListValueCToCpp::Wrap(_retval); +} + +bool CefListValueCToCpp::SetNull(int index) { + if (CEF_MEMBER_MISSING(struct_, set_null)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->set_null(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetBool(int index, bool value) { + if (CEF_MEMBER_MISSING(struct_, set_bool)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->set_bool(struct_, + index, + value); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetInt(int index, int value) { + if (CEF_MEMBER_MISSING(struct_, set_int)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->set_int(struct_, + index, + value); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetDouble(int index, double value) { + if (CEF_MEMBER_MISSING(struct_, set_double)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->set_double(struct_, + index, + value); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetString(int index, const CefString& value) { + if (CEF_MEMBER_MISSING(struct_, set_string)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + // Unverified params: value + + // Execute + int _retval = struct_->set_string(struct_, + index, + value.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetBinary(int index, CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_binary)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_binary(struct_, + index, + CefBinaryValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetDictionary(int index, + CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_dictionary)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_dictionary(struct_, + index, + CefDictionaryValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + +bool CefListValueCToCpp::SetList(int index, CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_list)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_list(struct_, + index, + CefListValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/list_value_ctocpp.h b/libcef_dll/ctocpp/list_value_ctocpp.h new file mode 100644 index 000000000..bee70dd2e --- /dev/null +++ b/libcef_dll/ctocpp/list_value_ctocpp.h @@ -0,0 +1,63 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_LIST_VALUE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_LIST_VALUE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_values.h" +#include "include/capi/cef_values_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefListValueCToCpp + : public CefCToCpp { + public: + explicit CefListValueCToCpp(cef_list_value_t* str) + : CefCToCpp(str) {} + + // CefListValue methods + virtual bool IsValid() OVERRIDE; + virtual bool IsOwned() OVERRIDE; + virtual bool IsReadOnly() OVERRIDE; + virtual CefRefPtr Copy() OVERRIDE; + virtual bool SetSize(size_t size) OVERRIDE; + virtual size_t GetSize() OVERRIDE; + virtual bool Clear() OVERRIDE; + virtual bool Remove(int index) OVERRIDE; + virtual CefValueType GetType(int index) OVERRIDE; + virtual bool GetBool(int index) OVERRIDE; + virtual int GetInt(int index) OVERRIDE; + virtual double GetDouble(int index) OVERRIDE; + virtual CefString GetString(int index) OVERRIDE; + virtual CefRefPtr GetBinary(int index) OVERRIDE; + virtual CefRefPtr GetDictionary(int index) OVERRIDE; + virtual CefRefPtr GetList(int index) OVERRIDE; + virtual bool SetNull(int index) OVERRIDE; + virtual bool SetBool(int index, bool value) OVERRIDE; + virtual bool SetInt(int index, int value) OVERRIDE; + virtual bool SetDouble(int index, double value) OVERRIDE; + virtual bool SetString(int index, const CefString& value) OVERRIDE; + virtual bool SetBinary(int index, CefRefPtr value) OVERRIDE; + virtual bool SetDictionary(int index, + CefRefPtr value) OVERRIDE; + virtual bool SetList(int index, CefRefPtr value) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_LIST_VALUE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/load_handler_ctocpp.cc b/libcef_dll/ctocpp/load_handler_ctocpp.cc new file mode 100644 index 000000000..4b35870fe --- /dev/null +++ b/libcef_dll/ctocpp/load_handler_ctocpp.cc @@ -0,0 +1,121 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/ctocpp/load_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefLoadHandlerCToCpp::OnLoadingStateChange(CefRefPtr browser, + bool isLoading, bool canGoBack, bool canGoForward) { + if (CEF_MEMBER_MISSING(struct_, on_loading_state_change)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_loading_state_change(struct_, + CefBrowserCppToC::Wrap(browser), + isLoading, + canGoBack, + canGoForward); +} + +void CefLoadHandlerCToCpp::OnLoadStart(CefRefPtr browser, + CefRefPtr frame) { + if (CEF_MEMBER_MISSING(struct_, on_load_start)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + + // Execute + struct_->on_load_start(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame)); +} + +void CefLoadHandlerCToCpp::OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, int httpStatusCode) { + if (CEF_MEMBER_MISSING(struct_, on_load_end)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + + // Execute + struct_->on_load_end(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + httpStatusCode); +} + +void CefLoadHandlerCToCpp::OnLoadError(CefRefPtr browser, + CefRefPtr frame, ErrorCode errorCode, const CefString& errorText, + const CefString& failedUrl) { + if (CEF_MEMBER_MISSING(struct_, on_load_error)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: failedUrl; type: string_byref_const + DCHECK(!failedUrl.empty()); + if (failedUrl.empty()) + return; + // Unverified params: errorText + + // Execute + struct_->on_load_error(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + errorCode, + errorText.GetStruct(), + failedUrl.GetStruct()); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/load_handler_ctocpp.h b/libcef_dll/ctocpp/load_handler_ctocpp.h new file mode 100644 index 000000000..48ed8d85b --- /dev/null +++ b/libcef_dll/ctocpp/load_handler_ctocpp.h @@ -0,0 +1,49 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_LOAD_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_LOAD_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_load_handler.h" +#include "include/capi/cef_load_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefLoadHandlerCToCpp + : public CefCToCpp { + public: + explicit CefLoadHandlerCToCpp(cef_load_handler_t* str) + : CefCToCpp( + str) {} + + // CefLoadHandler methods + void OnLoadingStateChange(CefRefPtr browser, bool isLoading, + bool canGoBack, bool canGoForward) override; + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override; + void OnLoadEnd(CefRefPtr browser, CefRefPtr frame, + int httpStatusCode) override; + void OnLoadError(CefRefPtr browser, CefRefPtr frame, + ErrorCode errorCode, const CefString& errorText, + const CefString& failedUrl) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_LOAD_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/menu_model_ctocpp.cc b/libcef_dll/ctocpp/menu_model_ctocpp.cc new file mode 100644 index 000000000..a9bbcac39 --- /dev/null +++ b/libcef_dll/ctocpp/menu_model_ctocpp.cc @@ -0,0 +1,839 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/menu_model_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefMenuModelCToCpp::Clear() { + if (CEF_MEMBER_MISSING(struct_, clear)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->clear(struct_); + + // Return type: bool + return _retval?true:false; +} + +int CefMenuModelCToCpp::GetCount() { + if (CEF_MEMBER_MISSING(struct_, get_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_count(struct_); + + // Return type: simple + return _retval; +} + +bool CefMenuModelCToCpp::AddSeparator() { + if (CEF_MEMBER_MISSING(struct_, add_separator)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->add_separator(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::AddItem(int command_id, const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, add_item)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->add_item(struct_, + command_id, + label.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::AddCheckItem(int command_id, const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, add_check_item)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->add_check_item(struct_, + command_id, + label.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::AddRadioItem(int command_id, const CefString& label, + int group_id) { + if (CEF_MEMBER_MISSING(struct_, add_radio_item)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->add_radio_item(struct_, + command_id, + label.GetStruct(), + group_id); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefMenuModelCToCpp::AddSubMenu(int command_id, + const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, add_sub_menu)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return NULL; + + // Execute + cef_menu_model_t* _retval = struct_->add_sub_menu(struct_, + command_id, + label.GetStruct()); + + // Return type: refptr_same + return CefMenuModelCToCpp::Wrap(_retval); +} + +bool CefMenuModelCToCpp::InsertSeparatorAt(int index) { + if (CEF_MEMBER_MISSING(struct_, insert_separator_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->insert_separator_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::InsertItemAt(int index, int command_id, + const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, insert_item_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->insert_item_at(struct_, + index, + command_id, + label.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::InsertCheckItemAt(int index, int command_id, + const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, insert_check_item_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->insert_check_item_at(struct_, + index, + command_id, + label.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::InsertRadioItemAt(int index, int command_id, + const CefString& label, int group_id) { + if (CEF_MEMBER_MISSING(struct_, insert_radio_item_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->insert_radio_item_at(struct_, + index, + command_id, + label.GetStruct(), + group_id); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefMenuModelCToCpp::InsertSubMenuAt(int index, + int command_id, const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, insert_sub_menu_at)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return NULL; + + // Execute + cef_menu_model_t* _retval = struct_->insert_sub_menu_at(struct_, + index, + command_id, + label.GetStruct()); + + // Return type: refptr_same + return CefMenuModelCToCpp::Wrap(_retval); +} + +bool CefMenuModelCToCpp::Remove(int command_id) { + if (CEF_MEMBER_MISSING(struct_, remove)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->remove(struct_, + command_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::RemoveAt(int index) { + if (CEF_MEMBER_MISSING(struct_, remove_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->remove_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +int CefMenuModelCToCpp::GetIndexOf(int command_id) { + if (CEF_MEMBER_MISSING(struct_, get_index_of)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_index_of(struct_, + command_id); + + // Return type: simple + return _retval; +} + +int CefMenuModelCToCpp::GetCommandIdAt(int index) { + if (CEF_MEMBER_MISSING(struct_, get_command_id_at)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_command_id_at(struct_, + index); + + // Return type: simple + return _retval; +} + +bool CefMenuModelCToCpp::SetCommandIdAt(int index, int command_id) { + if (CEF_MEMBER_MISSING(struct_, set_command_id_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_command_id_at(struct_, + index, + command_id); + + // Return type: bool + return _retval?true:false; +} + +CefString CefMenuModelCToCpp::GetLabel(int command_id) { + if (CEF_MEMBER_MISSING(struct_, get_label)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_label(struct_, + command_id); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefMenuModelCToCpp::GetLabelAt(int index) { + if (CEF_MEMBER_MISSING(struct_, get_label_at)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_label_at(struct_, + index); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefMenuModelCToCpp::SetLabel(int command_id, const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, set_label)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->set_label(struct_, + command_id, + label.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetLabelAt(int index, const CefString& label) { + if (CEF_MEMBER_MISSING(struct_, set_label_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: label; type: string_byref_const + DCHECK(!label.empty()); + if (label.empty()) + return false; + + // Execute + int _retval = struct_->set_label_at(struct_, + index, + label.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefMenuModel::MenuItemType CefMenuModelCToCpp::GetType(int command_id) { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return MENUITEMTYPE_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_menu_item_type_t _retval = struct_->get_type(struct_, + command_id); + + // Return type: simple + return _retval; +} + +CefMenuModel::MenuItemType CefMenuModelCToCpp::GetTypeAt(int index) { + if (CEF_MEMBER_MISSING(struct_, get_type_at)) + return MENUITEMTYPE_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_menu_item_type_t _retval = struct_->get_type_at(struct_, + index); + + // Return type: simple + return _retval; +} + +int CefMenuModelCToCpp::GetGroupId(int command_id) { + if (CEF_MEMBER_MISSING(struct_, get_group_id)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_group_id(struct_, + command_id); + + // Return type: simple + return _retval; +} + +int CefMenuModelCToCpp::GetGroupIdAt(int index) { + if (CEF_MEMBER_MISSING(struct_, get_group_id_at)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_group_id_at(struct_, + index); + + // Return type: simple + return _retval; +} + +bool CefMenuModelCToCpp::SetGroupId(int command_id, int group_id) { + if (CEF_MEMBER_MISSING(struct_, set_group_id)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_group_id(struct_, + command_id, + group_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetGroupIdAt(int index, int group_id) { + if (CEF_MEMBER_MISSING(struct_, set_group_id_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_group_id_at(struct_, + index, + group_id); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefMenuModelCToCpp::GetSubMenu(int command_id) { + if (CEF_MEMBER_MISSING(struct_, get_sub_menu)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_menu_model_t* _retval = struct_->get_sub_menu(struct_, + command_id); + + // Return type: refptr_same + return CefMenuModelCToCpp::Wrap(_retval); +} + +CefRefPtr CefMenuModelCToCpp::GetSubMenuAt(int index) { + if (CEF_MEMBER_MISSING(struct_, get_sub_menu_at)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_menu_model_t* _retval = struct_->get_sub_menu_at(struct_, + index); + + // Return type: refptr_same + return CefMenuModelCToCpp::Wrap(_retval); +} + +bool CefMenuModelCToCpp::IsVisible(int command_id) { + if (CEF_MEMBER_MISSING(struct_, is_visible)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_visible(struct_, + command_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::IsVisibleAt(int index) { + if (CEF_MEMBER_MISSING(struct_, is_visible_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_visible_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetVisible(int command_id, bool visible) { + if (CEF_MEMBER_MISSING(struct_, set_visible)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_visible(struct_, + command_id, + visible); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetVisibleAt(int index, bool visible) { + if (CEF_MEMBER_MISSING(struct_, set_visible_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_visible_at(struct_, + index, + visible); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::IsEnabled(int command_id) { + if (CEF_MEMBER_MISSING(struct_, is_enabled)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_enabled(struct_, + command_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::IsEnabledAt(int index) { + if (CEF_MEMBER_MISSING(struct_, is_enabled_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_enabled_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetEnabled(int command_id, bool enabled) { + if (CEF_MEMBER_MISSING(struct_, set_enabled)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_enabled(struct_, + command_id, + enabled); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetEnabledAt(int index, bool enabled) { + if (CEF_MEMBER_MISSING(struct_, set_enabled_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_enabled_at(struct_, + index, + enabled); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::IsChecked(int command_id) { + if (CEF_MEMBER_MISSING(struct_, is_checked)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_checked(struct_, + command_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::IsCheckedAt(int index) { + if (CEF_MEMBER_MISSING(struct_, is_checked_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_checked_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetChecked(int command_id, bool checked) { + if (CEF_MEMBER_MISSING(struct_, set_checked)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_checked(struct_, + command_id, + checked); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetCheckedAt(int index, bool checked) { + if (CEF_MEMBER_MISSING(struct_, set_checked_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_checked_at(struct_, + index, + checked); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::HasAccelerator(int command_id) { + if (CEF_MEMBER_MISSING(struct_, has_accelerator)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_accelerator(struct_, + command_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::HasAcceleratorAt(int index) { + if (CEF_MEMBER_MISSING(struct_, has_accelerator_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_accelerator_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetAccelerator(int command_id, int key_code, + bool shift_pressed, bool ctrl_pressed, bool alt_pressed) { + if (CEF_MEMBER_MISSING(struct_, set_accelerator)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_accelerator(struct_, + command_id, + key_code, + shift_pressed, + ctrl_pressed, + alt_pressed); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::SetAcceleratorAt(int index, int key_code, + bool shift_pressed, bool ctrl_pressed, bool alt_pressed) { + if (CEF_MEMBER_MISSING(struct_, set_accelerator_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_accelerator_at(struct_, + index, + key_code, + shift_pressed, + ctrl_pressed, + alt_pressed); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::RemoveAccelerator(int command_id) { + if (CEF_MEMBER_MISSING(struct_, remove_accelerator)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->remove_accelerator(struct_, + command_id); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::RemoveAcceleratorAt(int index) { + if (CEF_MEMBER_MISSING(struct_, remove_accelerator_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->remove_accelerator_at(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::GetAccelerator(int command_id, int& key_code, + bool& shift_pressed, bool& ctrl_pressed, bool& alt_pressed) { + if (CEF_MEMBER_MISSING(struct_, get_accelerator)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: shift_pressed; type: bool_byref + int shift_pressedInt = shift_pressed; + // Translate param: ctrl_pressed; type: bool_byref + int ctrl_pressedInt = ctrl_pressed; + // Translate param: alt_pressed; type: bool_byref + int alt_pressedInt = alt_pressed; + + // Execute + int _retval = struct_->get_accelerator(struct_, + command_id, + &key_code, + &shift_pressedInt, + &ctrl_pressedInt, + &alt_pressedInt); + + // Restore param:shift_pressed; type: bool_byref + shift_pressed = shift_pressedInt?true:false; + // Restore param:ctrl_pressed; type: bool_byref + ctrl_pressed = ctrl_pressedInt?true:false; + // Restore param:alt_pressed; type: bool_byref + alt_pressed = alt_pressedInt?true:false; + + // Return type: bool + return _retval?true:false; +} + +bool CefMenuModelCToCpp::GetAcceleratorAt(int index, int& key_code, + bool& shift_pressed, bool& ctrl_pressed, bool& alt_pressed) { + if (CEF_MEMBER_MISSING(struct_, get_accelerator_at)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: shift_pressed; type: bool_byref + int shift_pressedInt = shift_pressed; + // Translate param: ctrl_pressed; type: bool_byref + int ctrl_pressedInt = ctrl_pressed; + // Translate param: alt_pressed; type: bool_byref + int alt_pressedInt = alt_pressed; + + // Execute + int _retval = struct_->get_accelerator_at(struct_, + index, + &key_code, + &shift_pressedInt, + &ctrl_pressedInt, + &alt_pressedInt); + + // Restore param:shift_pressed; type: bool_byref + shift_pressed = shift_pressedInt?true:false; + // Restore param:ctrl_pressed; type: bool_byref + ctrl_pressed = ctrl_pressedInt?true:false; + // Restore param:alt_pressed; type: bool_byref + alt_pressed = alt_pressedInt?true:false; + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/menu_model_ctocpp.h b/libcef_dll/ctocpp/menu_model_ctocpp.h new file mode 100644 index 000000000..8a298c51f --- /dev/null +++ b/libcef_dll/ctocpp/menu_model_ctocpp.h @@ -0,0 +1,97 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_MENU_MODEL_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_MENU_MODEL_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_menu_model.h" +#include "include/capi/cef_menu_model_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefMenuModelCToCpp + : public CefCToCpp { + public: + explicit CefMenuModelCToCpp(cef_menu_model_t* str) + : CefCToCpp(str) {} + + // CefMenuModel methods + virtual bool Clear() OVERRIDE; + virtual int GetCount() OVERRIDE; + virtual bool AddSeparator() OVERRIDE; + virtual bool AddItem(int command_id, const CefString& label) OVERRIDE; + virtual bool AddCheckItem(int command_id, const CefString& label) OVERRIDE; + virtual bool AddRadioItem(int command_id, const CefString& label, + int group_id) OVERRIDE; + virtual CefRefPtr AddSubMenu(int command_id, + const CefString& label) OVERRIDE; + virtual bool InsertSeparatorAt(int index) OVERRIDE; + virtual bool InsertItemAt(int index, int command_id, + const CefString& label) OVERRIDE; + virtual bool InsertCheckItemAt(int index, int command_id, + const CefString& label) OVERRIDE; + virtual bool InsertRadioItemAt(int index, int command_id, + const CefString& label, int group_id) OVERRIDE; + virtual CefRefPtr InsertSubMenuAt(int index, int command_id, + const CefString& label) OVERRIDE; + virtual bool Remove(int command_id) OVERRIDE; + virtual bool RemoveAt(int index) OVERRIDE; + virtual int GetIndexOf(int command_id) OVERRIDE; + virtual int GetCommandIdAt(int index) OVERRIDE; + virtual bool SetCommandIdAt(int index, int command_id) OVERRIDE; + virtual CefString GetLabel(int command_id) OVERRIDE; + virtual CefString GetLabelAt(int index) OVERRIDE; + virtual bool SetLabel(int command_id, const CefString& label) OVERRIDE; + virtual bool SetLabelAt(int index, const CefString& label) OVERRIDE; + virtual MenuItemType GetType(int command_id) OVERRIDE; + virtual MenuItemType GetTypeAt(int index) OVERRIDE; + virtual int GetGroupId(int command_id) OVERRIDE; + virtual int GetGroupIdAt(int index) OVERRIDE; + virtual bool SetGroupId(int command_id, int group_id) OVERRIDE; + virtual bool SetGroupIdAt(int index, int group_id) OVERRIDE; + virtual CefRefPtr GetSubMenu(int command_id) OVERRIDE; + virtual CefRefPtr GetSubMenuAt(int index) OVERRIDE; + virtual bool IsVisible(int command_id) OVERRIDE; + virtual bool IsVisibleAt(int index) OVERRIDE; + virtual bool SetVisible(int command_id, bool visible) OVERRIDE; + virtual bool SetVisibleAt(int index, bool visible) OVERRIDE; + virtual bool IsEnabled(int command_id) OVERRIDE; + virtual bool IsEnabledAt(int index) OVERRIDE; + virtual bool SetEnabled(int command_id, bool enabled) OVERRIDE; + virtual bool SetEnabledAt(int index, bool enabled) OVERRIDE; + virtual bool IsChecked(int command_id) OVERRIDE; + virtual bool IsCheckedAt(int index) OVERRIDE; + virtual bool SetChecked(int command_id, bool checked) OVERRIDE; + virtual bool SetCheckedAt(int index, bool checked) OVERRIDE; + virtual bool HasAccelerator(int command_id) OVERRIDE; + virtual bool HasAcceleratorAt(int index) OVERRIDE; + virtual bool SetAccelerator(int command_id, int key_code, bool shift_pressed, + bool ctrl_pressed, bool alt_pressed) OVERRIDE; + virtual bool SetAcceleratorAt(int index, int key_code, bool shift_pressed, + bool ctrl_pressed, bool alt_pressed) OVERRIDE; + virtual bool RemoveAccelerator(int command_id) OVERRIDE; + virtual bool RemoveAcceleratorAt(int index) OVERRIDE; + virtual bool GetAccelerator(int command_id, int& key_code, + bool& shift_pressed, bool& ctrl_pressed, bool& alt_pressed) OVERRIDE; + virtual bool GetAcceleratorAt(int index, int& key_code, bool& shift_pressed, + bool& ctrl_pressed, bool& alt_pressed) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_MENU_MODEL_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/navigation_entry_ctocpp.cc b/libcef_dll/ctocpp/navigation_entry_ctocpp.cc new file mode 100644 index 000000000..c5801e4e9 --- /dev/null +++ b/libcef_dll/ctocpp/navigation_entry_ctocpp.cc @@ -0,0 +1,164 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/navigation_entry_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefNavigationEntryCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefNavigationEntryCToCpp::GetURL() { + if (CEF_MEMBER_MISSING(struct_, get_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefNavigationEntryCToCpp::GetDisplayURL() { + if (CEF_MEMBER_MISSING(struct_, get_display_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_display_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefNavigationEntryCToCpp::GetOriginalURL() { + if (CEF_MEMBER_MISSING(struct_, get_original_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_original_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefNavigationEntryCToCpp::GetTitle() { + if (CEF_MEMBER_MISSING(struct_, get_title)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_title(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefNavigationEntry::TransitionType CefNavigationEntryCToCpp::GetTransitionType( + ) { + if (CEF_MEMBER_MISSING(struct_, get_transition_type)) + return TT_EXPLICIT; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_transition_type_t _retval = struct_->get_transition_type(struct_); + + // Return type: simple + return _retval; +} + +bool CefNavigationEntryCToCpp::HasPostData() { + if (CEF_MEMBER_MISSING(struct_, has_post_data)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_post_data(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefNavigationEntryCToCpp::GetFrameName() { + if (CEF_MEMBER_MISSING(struct_, get_frame_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_frame_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefTime CefNavigationEntryCToCpp::GetCompletionTime() { + if (CEF_MEMBER_MISSING(struct_, get_completion_time)) + return CefTime(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_time_t _retval = struct_->get_completion_time(struct_); + + // Return type: simple + return _retval; +} + +int CefNavigationEntryCToCpp::GetHttpStatusCode() { + if (CEF_MEMBER_MISSING(struct_, get_http_status_code)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_http_status_code(struct_); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/navigation_entry_ctocpp.h b/libcef_dll/ctocpp/navigation_entry_ctocpp.h new file mode 100644 index 000000000..f1832c147 --- /dev/null +++ b/libcef_dll/ctocpp/navigation_entry_ctocpp.h @@ -0,0 +1,50 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_NAVIGATION_ENTRY_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_NAVIGATION_ENTRY_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_navigation_entry.h" +#include "include/capi/cef_navigation_entry_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefNavigationEntryCToCpp + : public CefCToCpp { + public: + explicit CefNavigationEntryCToCpp(cef_navigation_entry_t* str) + : CefCToCpp(str) {} + + // CefNavigationEntry methods + virtual bool IsValid() OVERRIDE; + virtual CefString GetURL() OVERRIDE; + virtual CefString GetDisplayURL() OVERRIDE; + virtual CefString GetOriginalURL() OVERRIDE; + virtual CefString GetTitle() OVERRIDE; + virtual TransitionType GetTransitionType() OVERRIDE; + virtual bool HasPostData() OVERRIDE; + virtual CefString GetFrameName() OVERRIDE; + virtual CefTime GetCompletionTime() OVERRIDE; + virtual int GetHttpStatusCode() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_NAVIGATION_ENTRY_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.cc b/libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.cc new file mode 100644 index 000000000..ed226ea12 --- /dev/null +++ b/libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/navigation_entry_cpptoc.h" +#include "libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefNavigationEntryVisitorCToCpp::Visit(CefRefPtr entry, + bool current, int index, int total) { + if (CEF_MEMBER_MISSING(struct_, visit)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: entry; type: refptr_diff + DCHECK(entry.get()); + if (!entry.get()) + return false; + + // Execute + int _retval = struct_->visit(struct_, + CefNavigationEntryCppToC::Wrap(entry), + current, + index, + total); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = + 0; +#endif + diff --git a/libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h b/libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h new file mode 100644 index 000000000..2b8858be2 --- /dev/null +++ b/libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_NAVIGATION_ENTRY_VISITOR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_NAVIGATION_ENTRY_VISITOR_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefNavigationEntryVisitorCToCpp + : public CefCToCpp { + public: + explicit CefNavigationEntryVisitorCToCpp(cef_navigation_entry_visitor_t* str) + : CefCToCpp(str) {} + + // CefNavigationEntryVisitor methods + bool Visit(CefRefPtr entry, bool current, int index, + int total) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_NAVIGATION_ENTRY_VISITOR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/permission_handler_ctocpp.cc b/libcef_dll/ctocpp/permission_handler_ctocpp.cc new file mode 100644 index 000000000..700e91b39 --- /dev/null +++ b/libcef_dll/ctocpp/permission_handler_ctocpp.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/ctocpp/permission_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefPermissionHandlerCToCpp::OnBeforeScriptExtensionLoad( + CefRefPtr browser, CefRefPtr frame, + const CefString& extensionName) { + if (CEF_MEMBER_MISSING(struct_, on_before_script_extension_load)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: extensionName; type: string_byref_const + DCHECK(!extensionName.empty()); + if (extensionName.empty()) + return false; + + // Execute + int _retval = struct_->on_before_script_extension_load(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + extensionName.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/permission_handler_ctocpp.h b/libcef_dll/ctocpp/permission_handler_ctocpp.h new file mode 100644 index 000000000..0bffa2a81 --- /dev/null +++ b/libcef_dll/ctocpp/permission_handler_ctocpp.h @@ -0,0 +1,47 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_PERMISSION_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PERMISSION_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_permission_handler.h" +#include "include/capi/cef_permission_handler_capi.h" +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_frame.h" +#include "include/capi/cef_frame_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefPermissionHandlerCToCpp + : public CefCToCpp { + public: + explicit CefPermissionHandlerCToCpp(cef_permission_handler_t* str) + : CefCToCpp(str) {} + virtual ~CefPermissionHandlerCToCpp() {} + + // CefPermissionHandler methods + virtual bool OnBeforeScriptExtensionLoad(CefRefPtr browser, + CefRefPtr frame, const CefString& extensionName) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PERMISSION_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/post_data_ctocpp.cc b/libcef_dll/ctocpp/post_data_ctocpp.cc new file mode 100644 index 000000000..72cfb3433 --- /dev/null +++ b/libcef_dll/ctocpp/post_data_ctocpp.cc @@ -0,0 +1,150 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include +#include "libcef_dll/ctocpp/post_data_ctocpp.h" +#include "libcef_dll/ctocpp/post_data_element_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefPostData::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_post_data_t* _retval = cef_post_data_create(); + + // Return type: refptr_same + return CefPostDataCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefPostDataCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +size_t CefPostDataCToCpp::GetElementCount() { + if (CEF_MEMBER_MISSING(struct_, get_element_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_element_count(struct_); + + // Return type: simple + return _retval; +} + +void CefPostDataCToCpp::GetElements(ElementVector& elements) { + if (CEF_MEMBER_MISSING(struct_, get_elements)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: elements; type: refptr_vec_same_byref + size_t elementsSize = elements.size(); + size_t elementsCount = std::max(GetElementCount(), elementsSize); + cef_post_data_element_t** elementsList = NULL; + if (elementsCount > 0) { + elementsList = new cef_post_data_element_t*[elementsCount]; + DCHECK(elementsList); + if (elementsList) { + memset(elementsList, 0, sizeof(cef_post_data_element_t*)*elementsCount); + } + if (elementsList && elementsSize > 0) { + for (size_t i = 0; i < elementsSize; ++i) { + elementsList[i] = CefPostDataElementCToCpp::Unwrap(elements[i]); + } + } + } + + // Execute + struct_->get_elements(struct_, + &elementsCount, + elementsList); + + // Restore param:elements; type: refptr_vec_same_byref + elements.clear(); + if (elementsCount > 0 && elementsList) { + for (size_t i = 0; i < elementsCount; ++i) { + elements.push_back(CefPostDataElementCToCpp::Wrap(elementsList[i])); + } + delete [] elementsList; + } +} + +bool CefPostDataCToCpp::RemoveElement(CefRefPtr element) { + if (CEF_MEMBER_MISSING(struct_, remove_element)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: element; type: refptr_same + DCHECK(element.get()); + if (!element.get()) + return false; + + // Execute + int _retval = struct_->remove_element(struct_, + CefPostDataElementCToCpp::Unwrap(element)); + + // Return type: bool + return _retval?true:false; +} + +bool CefPostDataCToCpp::AddElement(CefRefPtr element) { + if (CEF_MEMBER_MISSING(struct_, add_element)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: element; type: refptr_same + DCHECK(element.get()); + if (!element.get()) + return false; + + // Execute + int _retval = struct_->add_element(struct_, + CefPostDataElementCToCpp::Unwrap(element)); + + // Return type: bool + return _retval?true:false; +} + +void CefPostDataCToCpp::RemoveElements() { + if (CEF_MEMBER_MISSING(struct_, remove_elements)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->remove_elements(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/post_data_ctocpp.h b/libcef_dll/ctocpp/post_data_ctocpp.h new file mode 100644 index 000000000..0074c16e5 --- /dev/null +++ b/libcef_dll/ctocpp/post_data_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_POST_DATA_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_POST_DATA_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request.h" +#include "include/capi/cef_request_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefPostDataCToCpp + : public CefCToCpp { + public: + explicit CefPostDataCToCpp(cef_post_data_t* str) + : CefCToCpp(str) {} + + // CefPostData methods + virtual bool IsReadOnly() OVERRIDE; + virtual size_t GetElementCount() OVERRIDE; + virtual void GetElements(ElementVector& elements) OVERRIDE; + virtual bool RemoveElement(CefRefPtr element) OVERRIDE; + virtual bool AddElement(CefRefPtr element) OVERRIDE; + virtual void RemoveElements() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_POST_DATA_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/post_data_element_ctocpp.cc b/libcef_dll/ctocpp/post_data_element_ctocpp.cc new file mode 100644 index 000000000..da225b047 --- /dev/null +++ b/libcef_dll/ctocpp/post_data_element_ctocpp.cc @@ -0,0 +1,153 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/post_data_element_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefPostDataElement::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_post_data_element_t* _retval = cef_post_data_element_create(); + + // Return type: refptr_same + return CefPostDataElementCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefPostDataElementCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefPostDataElementCToCpp::SetToEmpty() { + if (CEF_MEMBER_MISSING(struct_, set_to_empty)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_to_empty(struct_); +} + +void CefPostDataElementCToCpp::SetToFile(const CefString& fileName) { + if (CEF_MEMBER_MISSING(struct_, set_to_file)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(!fileName.empty()); + if (fileName.empty()) + return; + + // Execute + struct_->set_to_file(struct_, + fileName.GetStruct()); +} + +void CefPostDataElementCToCpp::SetToBytes(size_t size, const void* bytes) { + if (CEF_MEMBER_MISSING(struct_, set_to_bytes)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: bytes; type: simple_byaddr + DCHECK(bytes); + if (!bytes) + return; + + // Execute + struct_->set_to_bytes(struct_, + size, + bytes); +} + +CefPostDataElement::Type CefPostDataElementCToCpp::GetType() { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return PDE_TYPE_EMPTY; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_postdataelement_type_t _retval = struct_->get_type(struct_); + + // Return type: simple + return _retval; +} + +CefString CefPostDataElementCToCpp::GetFile() { + if (CEF_MEMBER_MISSING(struct_, get_file)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_file(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +size_t CefPostDataElementCToCpp::GetBytesCount() { + if (CEF_MEMBER_MISSING(struct_, get_bytes_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_bytes_count(struct_); + + // Return type: simple + return _retval; +} + +size_t CefPostDataElementCToCpp::GetBytes(size_t size, void* bytes) { + if (CEF_MEMBER_MISSING(struct_, get_bytes)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: bytes; type: simple_byaddr + DCHECK(bytes); + if (!bytes) + return 0; + + // Execute + size_t _retval = struct_->get_bytes(struct_, + size, + bytes); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/post_data_element_ctocpp.h b/libcef_dll/ctocpp/post_data_element_ctocpp.h new file mode 100644 index 000000000..6b309d3f1 --- /dev/null +++ b/libcef_dll/ctocpp/post_data_element_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_POST_DATA_ELEMENT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_POST_DATA_ELEMENT_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request.h" +#include "include/capi/cef_request_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefPostDataElementCToCpp + : public CefCToCpp { + public: + explicit CefPostDataElementCToCpp(cef_post_data_element_t* str) + : CefCToCpp(str) {} + + // CefPostDataElement methods + virtual bool IsReadOnly() OVERRIDE; + virtual void SetToEmpty() OVERRIDE; + virtual void SetToFile(const CefString& fileName) OVERRIDE; + virtual void SetToBytes(size_t size, const void* bytes) OVERRIDE; + virtual Type GetType() OVERRIDE; + virtual CefString GetFile() OVERRIDE; + virtual size_t GetBytesCount() OVERRIDE; + virtual size_t GetBytes(size_t size, void* bytes) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_POST_DATA_ELEMENT_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/print_dialog_callback_ctocpp.cc b/libcef_dll/ctocpp/print_dialog_callback_ctocpp.cc new file mode 100644 index 000000000..e5a0d07e3 --- /dev/null +++ b/libcef_dll/ctocpp/print_dialog_callback_ctocpp.cc @@ -0,0 +1,51 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/print_dialog_callback_ctocpp.h" +#include "libcef_dll/ctocpp/print_settings_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefPrintDialogCallbackCToCpp::Continue( + CefRefPtr settings) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: settings; type: refptr_same + DCHECK(settings.get()); + if (!settings.get()) + return; + + // Execute + struct_->cont(struct_, + CefPrintSettingsCToCpp::Unwrap(settings)); +} + +void CefPrintDialogCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/print_dialog_callback_ctocpp.h b/libcef_dll/ctocpp/print_dialog_callback_ctocpp.h new file mode 100644 index 000000000..cac349543 --- /dev/null +++ b/libcef_dll/ctocpp/print_dialog_callback_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_PRINT_DIALOG_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PRINT_DIALOG_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_print_handler.h" +#include "include/capi/cef_print_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefPrintDialogCallbackCToCpp + : public CefCToCpp { + public: + explicit CefPrintDialogCallbackCToCpp(cef_print_dialog_callback_t* str) + : CefCToCpp(str) {} + + // CefPrintDialogCallback methods + virtual void Continue(CefRefPtr settings) OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PRINT_DIALOG_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/print_handler_ctocpp.cc b/libcef_dll/ctocpp/print_handler_ctocpp.cc new file mode 100644 index 000000000..d7807936a --- /dev/null +++ b/libcef_dll/ctocpp/print_handler_ctocpp.cc @@ -0,0 +1,105 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/print_dialog_callback_cpptoc.h" +#include "libcef_dll/cpptoc/print_job_callback_cpptoc.h" +#include "libcef_dll/cpptoc/print_settings_cpptoc.h" +#include "libcef_dll/ctocpp/print_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefPrintHandlerCToCpp::OnPrintSettings( + CefRefPtr settings, bool get_defaults) { + if (CEF_MEMBER_MISSING(struct_, on_print_settings)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: settings; type: refptr_diff + DCHECK(settings.get()); + if (!settings.get()) + return; + + // Execute + struct_->on_print_settings(struct_, + CefPrintSettingsCppToC::Wrap(settings), + get_defaults); +} + +bool CefPrintHandlerCToCpp::OnPrintDialog(bool has_selection, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_print_dialog)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->on_print_dialog(struct_, + has_selection, + CefPrintDialogCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +bool CefPrintHandlerCToCpp::OnPrintJob(const CefString& document_name, + const CefString& pdf_file_path, CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_print_job)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: document_name; type: string_byref_const + DCHECK(!document_name.empty()); + if (document_name.empty()) + return false; + // Verify param: pdf_file_path; type: string_byref_const + DCHECK(!pdf_file_path.empty()); + if (pdf_file_path.empty()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->on_print_job(struct_, + document_name.GetStruct(), + pdf_file_path.GetStruct(), + CefPrintJobCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefPrintHandlerCToCpp::OnPrintReset() { + if (CEF_MEMBER_MISSING(struct_, on_print_reset)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->on_print_reset(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/print_handler_ctocpp.h b/libcef_dll/ctocpp/print_handler_ctocpp.h new file mode 100644 index 000000000..3d39b0ee7 --- /dev/null +++ b/libcef_dll/ctocpp/print_handler_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_PRINT_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PRINT_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_print_handler.h" +#include "include/capi/cef_print_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefPrintHandlerCToCpp + : public CefCToCpp { + public: + explicit CefPrintHandlerCToCpp(cef_print_handler_t* str) + : CefCToCpp( + str) {} + + // CefPrintHandler methods + void OnPrintSettings(CefRefPtr settings, + bool get_defaults) override; + bool OnPrintDialog(bool has_selection, + CefRefPtr callback) override; + bool OnPrintJob(const CefString& document_name, + const CefString& pdf_file_path, + CefRefPtr callback) override; + void OnPrintReset() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PRINT_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/print_job_callback_ctocpp.cc b/libcef_dll/ctocpp/print_job_callback_ctocpp.cc new file mode 100644 index 000000000..4ea878411 --- /dev/null +++ b/libcef_dll/ctocpp/print_job_callback_ctocpp.cc @@ -0,0 +1,33 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/print_job_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefPrintJobCallbackCToCpp::Continue() { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cont(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/print_job_callback_ctocpp.h b/libcef_dll/ctocpp/print_job_callback_ctocpp.h new file mode 100644 index 000000000..951560824 --- /dev/null +++ b/libcef_dll/ctocpp/print_job_callback_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_PRINT_JOB_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PRINT_JOB_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_print_handler.h" +#include "include/capi/cef_print_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefPrintJobCallbackCToCpp + : public CefCToCpp { + public: + explicit CefPrintJobCallbackCToCpp(cef_print_job_callback_t* str) + : CefCToCpp(str) {} + + // CefPrintJobCallback methods + virtual void Continue() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PRINT_JOB_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/print_settings_ctocpp.cc b/libcef_dll/ctocpp/print_settings_ctocpp.cc new file mode 100644 index 000000000..465a27d2b --- /dev/null +++ b/libcef_dll/ctocpp/print_settings_ctocpp.cc @@ -0,0 +1,367 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include +#include "libcef_dll/ctocpp/print_settings_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefPrintSettings::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_print_settings_t* _retval = cef_print_settings_create(); + + // Return type: refptr_same + return CefPrintSettingsCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefPrintSettingsCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefPrintSettingsCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefPrintSettingsCToCpp::Copy() { + if (CEF_MEMBER_MISSING(struct_, copy)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_print_settings_t* _retval = struct_->copy(struct_); + + // Return type: refptr_same + return CefPrintSettingsCToCpp::Wrap(_retval); +} + +void CefPrintSettingsCToCpp::SetOrientation(bool landscape) { + if (CEF_MEMBER_MISSING(struct_, set_orientation)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_orientation(struct_, + landscape); +} + +bool CefPrintSettingsCToCpp::IsLandscape() { + if (CEF_MEMBER_MISSING(struct_, is_landscape)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_landscape(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefPrintSettingsCToCpp::SetPrinterPrintableArea( + const CefSize& physical_size_device_units, + const CefRect& printable_area_device_units, bool landscape_needs_flip) { + if (CEF_MEMBER_MISSING(struct_, set_printer_printable_area)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_printer_printable_area(struct_, + &physical_size_device_units, + &printable_area_device_units, + landscape_needs_flip); +} + +void CefPrintSettingsCToCpp::SetDeviceName(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, set_device_name)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: name + + // Execute + struct_->set_device_name(struct_, + name.GetStruct()); +} + +CefString CefPrintSettingsCToCpp::GetDeviceName() { + if (CEF_MEMBER_MISSING(struct_, get_device_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_device_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefPrintSettingsCToCpp::SetDPI(int dpi) { + if (CEF_MEMBER_MISSING(struct_, set_dpi)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_dpi(struct_, + dpi); +} + +int CefPrintSettingsCToCpp::GetDPI() { + if (CEF_MEMBER_MISSING(struct_, get_dpi)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_dpi(struct_); + + // Return type: simple + return _retval; +} + +void CefPrintSettingsCToCpp::SetPageRanges(const PageRangeList& ranges) { + if (CEF_MEMBER_MISSING(struct_, set_page_ranges)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: ranges; type: simple_vec_byref_const + const size_t rangesCount = ranges.size(); + cef_page_range_t* rangesList = NULL; + if (rangesCount > 0) { + rangesList = new cef_page_range_t[rangesCount]; + DCHECK(rangesList); + if (rangesList) { + for (size_t i = 0; i < rangesCount; ++i) { + rangesList[i] = ranges[i]; + } + } + } + + // Execute + struct_->set_page_ranges(struct_, + rangesCount, + rangesList); + + // Restore param:ranges; type: simple_vec_byref_const + if (rangesList) + delete [] rangesList; +} + +size_t CefPrintSettingsCToCpp::GetPageRangesCount() { + if (CEF_MEMBER_MISSING(struct_, get_page_ranges_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_page_ranges_count(struct_); + + // Return type: simple + return _retval; +} + +void CefPrintSettingsCToCpp::GetPageRanges(PageRangeList& ranges) { + if (CEF_MEMBER_MISSING(struct_, get_page_ranges)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: ranges; type: simple_vec_byref + size_t rangesSize = ranges.size(); + size_t rangesCount = std::max(GetPageRangesCount(), rangesSize); + cef_page_range_t* rangesList = NULL; + if (rangesCount > 0) { + rangesList = new cef_page_range_t[rangesCount]; + DCHECK(rangesList); + if (rangesList) { + memset(rangesList, 0, sizeof(cef_page_range_t)*rangesCount); + } + if (rangesList && rangesSize > 0) { + for (size_t i = 0; i < rangesSize; ++i) { + rangesList[i] = ranges[i]; + } + } + } + + // Execute + struct_->get_page_ranges(struct_, + &rangesCount, + rangesList); + + // Restore param:ranges; type: simple_vec_byref + ranges.clear(); + if (rangesCount > 0 && rangesList) { + for (size_t i = 0; i < rangesCount; ++i) { + ranges.push_back(rangesList[i]); + } + delete [] rangesList; + } +} + +void CefPrintSettingsCToCpp::SetSelectionOnly(bool selection_only) { + if (CEF_MEMBER_MISSING(struct_, set_selection_only)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_selection_only(struct_, + selection_only); +} + +bool CefPrintSettingsCToCpp::IsSelectionOnly() { + if (CEF_MEMBER_MISSING(struct_, is_selection_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_selection_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefPrintSettingsCToCpp::SetCollate(bool collate) { + if (CEF_MEMBER_MISSING(struct_, set_collate)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_collate(struct_, + collate); +} + +bool CefPrintSettingsCToCpp::WillCollate() { + if (CEF_MEMBER_MISSING(struct_, will_collate)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->will_collate(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefPrintSettingsCToCpp::SetColorModel(ColorModel model) { + if (CEF_MEMBER_MISSING(struct_, set_color_model)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_color_model(struct_, + model); +} + +CefPrintSettings::ColorModel CefPrintSettingsCToCpp::GetColorModel() { + if (CEF_MEMBER_MISSING(struct_, get_color_model)) + return COLOR_MODEL_UNKNOWN; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_color_model_t _retval = struct_->get_color_model(struct_); + + // Return type: simple + return _retval; +} + +void CefPrintSettingsCToCpp::SetCopies(int copies) { + if (CEF_MEMBER_MISSING(struct_, set_copies)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_copies(struct_, + copies); +} + +int CefPrintSettingsCToCpp::GetCopies() { + if (CEF_MEMBER_MISSING(struct_, get_copies)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_copies(struct_); + + // Return type: simple + return _retval; +} + +void CefPrintSettingsCToCpp::SetDuplexMode(DuplexMode mode) { + if (CEF_MEMBER_MISSING(struct_, set_duplex_mode)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_duplex_mode(struct_, + mode); +} + +CefPrintSettings::DuplexMode CefPrintSettingsCToCpp::GetDuplexMode() { + if (CEF_MEMBER_MISSING(struct_, get_duplex_mode)) + return DUPLEX_MODE_UNKNOWN; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_duplex_mode_t _retval = struct_->get_duplex_mode(struct_); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/print_settings_ctocpp.h b/libcef_dll/ctocpp/print_settings_ctocpp.h new file mode 100644 index 000000000..326a88432 --- /dev/null +++ b/libcef_dll/ctocpp/print_settings_ctocpp.h @@ -0,0 +1,66 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_PRINT_SETTINGS_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PRINT_SETTINGS_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_print_settings.h" +#include "include/capi/cef_print_settings_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefPrintSettingsCToCpp + : public CefCToCpp { + public: + explicit CefPrintSettingsCToCpp(cef_print_settings_t* str) + : CefCToCpp(str) {} + + // CefPrintSettings methods + virtual bool IsValid() OVERRIDE; + virtual bool IsReadOnly() OVERRIDE; + virtual CefRefPtr Copy() OVERRIDE; + virtual void SetOrientation(bool landscape) OVERRIDE; + virtual bool IsLandscape() OVERRIDE; + virtual void SetPrinterPrintableArea( + const CefSize& physical_size_device_units, + const CefRect& printable_area_device_units, + bool landscape_needs_flip) OVERRIDE; + virtual void SetDeviceName(const CefString& name) OVERRIDE; + virtual CefString GetDeviceName() OVERRIDE; + virtual void SetDPI(int dpi) OVERRIDE; + virtual int GetDPI() OVERRIDE; + virtual void SetPageRanges(const PageRangeList& ranges) OVERRIDE; + virtual size_t GetPageRangesCount() OVERRIDE; + virtual void GetPageRanges(PageRangeList& ranges) OVERRIDE; + virtual void SetSelectionOnly(bool selection_only) OVERRIDE; + virtual bool IsSelectionOnly() OVERRIDE; + virtual void SetCollate(bool collate) OVERRIDE; + virtual bool WillCollate() OVERRIDE; + virtual void SetColorModel(ColorModel model) OVERRIDE; + virtual ColorModel GetColorModel() OVERRIDE; + virtual void SetCopies(int copies) OVERRIDE; + virtual int GetCopies() OVERRIDE; + virtual void SetDuplexMode(DuplexMode mode) OVERRIDE; + virtual DuplexMode GetDuplexMode() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PRINT_SETTINGS_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/process_message_ctocpp.cc b/libcef_dll/ctocpp/process_message_ctocpp.cc new file mode 100644 index 000000000..62585fda3 --- /dev/null +++ b/libcef_dll/ctocpp/process_message_ctocpp.cc @@ -0,0 +1,110 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/list_value_ctocpp.h" +#include "libcef_dll/ctocpp/process_message_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefProcessMessage::Create(const CefString& name) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return NULL; + + // Execute + cef_process_message_t* _retval = cef_process_message_create( + name.GetStruct()); + + // Return type: refptr_same + return CefProcessMessageCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefProcessMessageCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefProcessMessageCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefProcessMessageCToCpp::Copy() { + if (CEF_MEMBER_MISSING(struct_, copy)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_process_message_t* _retval = struct_->copy(struct_); + + // Return type: refptr_same + return CefProcessMessageCToCpp::Wrap(_retval); +} + +CefString CefProcessMessageCToCpp::GetName() { + if (CEF_MEMBER_MISSING(struct_, get_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefProcessMessageCToCpp::GetArgumentList() { + if (CEF_MEMBER_MISSING(struct_, get_argument_list)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_list_value_t* _retval = struct_->get_argument_list(struct_); + + // Return type: refptr_same + return CefListValueCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/process_message_ctocpp.h b/libcef_dll/ctocpp/process_message_ctocpp.h new file mode 100644 index 000000000..b97e622dc --- /dev/null +++ b/libcef_dll/ctocpp/process_message_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_PROCESS_MESSAGE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PROCESS_MESSAGE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_process_message.h" +#include "include/capi/cef_process_message_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefProcessMessageCToCpp + : public CefCToCpp { + public: + explicit CefProcessMessageCToCpp(cef_process_message_t* str) + : CefCToCpp(str) {} + + // CefProcessMessage methods + virtual bool IsValid() OVERRIDE; + virtual bool IsReadOnly() OVERRIDE; + virtual CefRefPtr Copy() OVERRIDE; + virtual CefString GetName() OVERRIDE; + virtual CefRefPtr GetArgumentList() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PROCESS_MESSAGE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/quota_callback_ctocpp.cc b/libcef_dll/ctocpp/quota_callback_ctocpp.cc new file mode 100644 index 000000000..51fa06161 --- /dev/null +++ b/libcef_dll/ctocpp/quota_callback_ctocpp.cc @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/quota_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefQuotaCallbackCToCpp::Continue(bool allow) { + if (CEF_MEMBER_MISSING(struct_, cont)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cont(struct_, + allow); +} + +void CefQuotaCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/quota_callback_ctocpp.h b/libcef_dll/ctocpp/quota_callback_ctocpp.h new file mode 100644 index 000000000..80cf63004 --- /dev/null +++ b/libcef_dll/ctocpp/quota_callback_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_QUOTA_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_QUOTA_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request_handler.h" +#include "include/capi/cef_request_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefQuotaCallbackCToCpp + : public CefCToCpp { + public: + explicit CefQuotaCallbackCToCpp(cef_quota_callback_t* str) + : CefCToCpp(str) {} + + // CefQuotaCallback methods + virtual void Continue(bool allow) OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_QUOTA_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/read_handler_ctocpp.cc b/libcef_dll/ctocpp/read_handler_ctocpp.cc new file mode 100644 index 000000000..7f5165782 --- /dev/null +++ b/libcef_dll/ctocpp/read_handler_ctocpp.cc @@ -0,0 +1,98 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/read_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +size_t CefReadHandlerCToCpp::Read(void* ptr, size_t size, size_t n) { + if (CEF_MEMBER_MISSING(struct_, read)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = struct_->read(struct_, + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CefReadHandlerCToCpp::Seek(int64 offset, int whence) { + if (CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->seek(struct_, + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CefReadHandlerCToCpp::Tell() { + if (CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->tell(struct_); + + // Return type: simple + return _retval; +} + +int CefReadHandlerCToCpp::Eof() { + if (CEF_MEMBER_MISSING(struct_, eof)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->eof(struct_); + + // Return type: simple + return _retval; +} + +bool CefReadHandlerCToCpp::MayBlock() { + if (CEF_MEMBER_MISSING(struct_, may_block)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->may_block(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/read_handler_ctocpp.h b/libcef_dll/ctocpp/read_handler_ctocpp.h new file mode 100644 index 000000000..792e7c39e --- /dev/null +++ b/libcef_dll/ctocpp/read_handler_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_READ_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_READ_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefReadHandlerCToCpp + : public CefCToCpp { + public: + explicit CefReadHandlerCToCpp(cef_read_handler_t* str) + : CefCToCpp( + str) {} + + // CefReadHandler methods + size_t Read(void* ptr, size_t size, size_t n) override; + int Seek(int64 offset, int whence) override; + int64 Tell() override; + int Eof() override; + bool MayBlock() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_READ_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/render_handler_ctocpp.cc b/libcef_dll/ctocpp/render_handler_ctocpp.cc new file mode 100644 index 000000000..0fd65c571 --- /dev/null +++ b/libcef_dll/ctocpp/render_handler_ctocpp.cc @@ -0,0 +1,278 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/ctocpp/render_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefRenderHandlerCToCpp::GetRootScreenRect(CefRefPtr browser, + CefRect& rect) { + if (CEF_MEMBER_MISSING(struct_, get_root_screen_rect)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->get_root_screen_rect(struct_, + CefBrowserCppToC::Wrap(browser), + &rect); + + // Return type: bool + return _retval?true:false; +} + +bool CefRenderHandlerCToCpp::GetViewRect(CefRefPtr browser, + CefRect& rect) { + if (CEF_MEMBER_MISSING(struct_, get_view_rect)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->get_view_rect(struct_, + CefBrowserCppToC::Wrap(browser), + &rect); + + // Return type: bool + return _retval?true:false; +} + +bool CefRenderHandlerCToCpp::GetScreenPoint(CefRefPtr browser, + int viewX, int viewY, int& screenX, int& screenY) { + if (CEF_MEMBER_MISSING(struct_, get_screen_point)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->get_screen_point(struct_, + CefBrowserCppToC::Wrap(browser), + viewX, + viewY, + &screenX, + &screenY); + + // Return type: bool + return _retval?true:false; +} + +bool CefRenderHandlerCToCpp::GetScreenInfo(CefRefPtr browser, + CefScreenInfo& screen_info) { + if (CEF_MEMBER_MISSING(struct_, get_screen_info)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + + // Execute + int _retval = struct_->get_screen_info(struct_, + CefBrowserCppToC::Wrap(browser), + &screen_info); + + // Return type: bool + return _retval?true:false; +} + +void CefRenderHandlerCToCpp::OnPopupShow(CefRefPtr browser, + bool show) { + if (CEF_MEMBER_MISSING(struct_, on_popup_show)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_popup_show(struct_, + CefBrowserCppToC::Wrap(browser), + show); +} + +void CefRenderHandlerCToCpp::OnPopupSize(CefRefPtr browser, + const CefRect& rect) { + if (CEF_MEMBER_MISSING(struct_, on_popup_size)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_popup_size(struct_, + CefBrowserCppToC::Wrap(browser), + &rect); +} + +void CefRenderHandlerCToCpp::OnPaint(CefRefPtr browser, + PaintElementType type, const RectList& dirtyRects, const void* buffer, + int width, int height) { + if (CEF_MEMBER_MISSING(struct_, on_paint)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return; + + // Translate param: dirtyRects; type: simple_vec_byref_const + const size_t dirtyRectsCount = dirtyRects.size(); + cef_rect_t* dirtyRectsList = NULL; + if (dirtyRectsCount > 0) { + dirtyRectsList = new cef_rect_t[dirtyRectsCount]; + DCHECK(dirtyRectsList); + if (dirtyRectsList) { + for (size_t i = 0; i < dirtyRectsCount; ++i) { + dirtyRectsList[i] = dirtyRects[i]; + } + } + } + + // Execute + struct_->on_paint(struct_, + CefBrowserCppToC::Wrap(browser), + type, + dirtyRectsCount, + dirtyRectsList, + buffer, + width, + height); + + // Restore param:dirtyRects; type: simple_vec_byref_const + if (dirtyRectsList) + delete [] dirtyRectsList; +} + +void CefRenderHandlerCToCpp::OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor, CursorType type, + const CefCursorInfo& custom_cursor_info) { + if (CEF_MEMBER_MISSING(struct_, on_cursor_change)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_cursor_change(struct_, + CefBrowserCppToC::Wrap(browser), + cursor, + type, + &custom_cursor_info); +} + +bool CefRenderHandlerCToCpp::StartDragging(CefRefPtr browser, + CefRefPtr drag_data, DragOperationsMask allowed_ops, int x, + int y) { + if (CEF_MEMBER_MISSING(struct_, start_dragging)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: drag_data; type: refptr_diff + DCHECK(drag_data.get()); + if (!drag_data.get()) + return false; + + // Execute + int _retval = struct_->start_dragging(struct_, + CefBrowserCppToC::Wrap(browser), + CefDragDataCppToC::Wrap(drag_data), + allowed_ops, + x, + y); + + // Return type: bool + return _retval?true:false; +} + +void CefRenderHandlerCToCpp::UpdateDragCursor(CefRefPtr browser, + DragOperation operation) { + if (CEF_MEMBER_MISSING(struct_, update_drag_cursor)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->update_drag_cursor(struct_, + CefBrowserCppToC::Wrap(browser), + operation); +} + +void CefRenderHandlerCToCpp::OnScrollOffsetChanged( + CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_scroll_offset_changed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_scroll_offset_changed(struct_, + CefBrowserCppToC::Wrap(browser)); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/render_handler_ctocpp.h b/libcef_dll/ctocpp/render_handler_ctocpp.h new file mode 100644 index 000000000..1e81e2810 --- /dev/null +++ b/libcef_dll/ctocpp/render_handler_ctocpp.h @@ -0,0 +1,59 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_RENDER_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_RENDER_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_render_handler.h" +#include "include/capi/cef_render_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefRenderHandlerCToCpp + : public CefCToCpp { + public: + explicit CefRenderHandlerCToCpp(cef_render_handler_t* str) + : CefCToCpp(str) {} + + // CefRenderHandler methods + bool GetRootScreenRect(CefRefPtr browser, CefRect& rect) override; + bool GetViewRect(CefRefPtr browser, CefRect& rect) override; + bool GetScreenPoint(CefRefPtr browser, int viewX, int viewY, + int& screenX, int& screenY) override; + bool GetScreenInfo(CefRefPtr browser, + CefScreenInfo& screen_info) override; + void OnPopupShow(CefRefPtr browser, bool show) override; + void OnPopupSize(CefRefPtr browser, const CefRect& rect) override; + void OnPaint(CefRefPtr browser, PaintElementType type, + const RectList& dirtyRects, const void* buffer, int width, + int height) override; + void OnCursorChange(CefRefPtr browser, CefCursorHandle cursor, + CursorType type, const CefCursorInfo& custom_cursor_info) override; + bool StartDragging(CefRefPtr browser, + CefRefPtr drag_data, DragOperationsMask allowed_ops, int x, + int y) override; + void UpdateDragCursor(CefRefPtr browser, + DragOperation operation) override; + void OnScrollOffsetChanged(CefRefPtr browser) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RENDER_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/render_process_handler_ctocpp.cc b/libcef_dll/ctocpp/render_process_handler_ctocpp.cc new file mode 100644 index 000000000..06f4ce15c --- /dev/null +++ b/libcef_dll/ctocpp/render_process_handler_ctocpp.cc @@ -0,0 +1,284 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/list_value_cpptoc.h" +#include "libcef_dll/cpptoc/process_message_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/cpptoc/v8exception_cpptoc.h" +#include "libcef_dll/cpptoc/v8stack_trace_cpptoc.h" +#include "libcef_dll/ctocpp/load_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_process_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefRenderProcessHandlerCToCpp::OnRenderThreadCreated( + CefRefPtr extra_info) { + if (CEF_MEMBER_MISSING(struct_, on_render_thread_created)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: extra_info; type: refptr_diff + DCHECK(extra_info.get()); + if (!extra_info.get()) + return; + + // Execute + struct_->on_render_thread_created(struct_, + CefListValueCppToC::Wrap(extra_info)); +} + +void CefRenderProcessHandlerCToCpp::OnWebKitInitialized() { + if (CEF_MEMBER_MISSING(struct_, on_web_kit_initialized)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->on_web_kit_initialized(struct_); +} + +void CefRenderProcessHandlerCToCpp::OnBrowserCreated( + CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_browser_created)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_browser_created(struct_, + CefBrowserCppToC::Wrap(browser)); +} + +void CefRenderProcessHandlerCToCpp::OnBrowserDestroyed( + CefRefPtr browser) { + if (CEF_MEMBER_MISSING(struct_, on_browser_destroyed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_browser_destroyed(struct_, + CefBrowserCppToC::Wrap(browser)); +} + +CefRefPtr CefRenderProcessHandlerCToCpp::GetLoadHandler() { + if (CEF_MEMBER_MISSING(struct_, get_load_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_load_handler_t* _retval = struct_->get_load_handler(struct_); + + // Return type: refptr_same + return CefLoadHandlerCToCpp::Wrap(_retval); +} + +bool CefRenderProcessHandlerCToCpp::OnBeforeNavigation( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr request, NavigationType navigation_type, + bool is_redirect) { + if (CEF_MEMBER_MISSING(struct_, on_before_navigation)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return false; + + // Execute + int _retval = struct_->on_before_navigation(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefRequestCppToC::Wrap(request), + navigation_type, + is_redirect); + + // Return type: bool + return _retval?true:false; +} + +void CefRenderProcessHandlerCToCpp::OnContextCreated( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr context) { + if (CEF_MEMBER_MISSING(struct_, on_context_created)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: context; type: refptr_diff + DCHECK(context.get()); + if (!context.get()) + return; + + // Execute + struct_->on_context_created(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefV8ContextCppToC::Wrap(context)); +} + +void CefRenderProcessHandlerCToCpp::OnContextReleased( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr context) { + if (CEF_MEMBER_MISSING(struct_, on_context_released)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: context; type: refptr_diff + DCHECK(context.get()); + if (!context.get()) + return; + + // Execute + struct_->on_context_released(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefV8ContextCppToC::Wrap(context)); +} + +void CefRenderProcessHandlerCToCpp::OnUncaughtException( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr context, CefRefPtr exception, + CefRefPtr stackTrace) { + if (CEF_MEMBER_MISSING(struct_, on_uncaught_exception)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: context; type: refptr_diff + DCHECK(context.get()); + if (!context.get()) + return; + // Verify param: exception; type: refptr_diff + DCHECK(exception.get()); + if (!exception.get()) + return; + // Verify param: stackTrace; type: refptr_diff + DCHECK(stackTrace.get()); + if (!stackTrace.get()) + return; + + // Execute + struct_->on_uncaught_exception(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefV8ContextCppToC::Wrap(context), + CefV8ExceptionCppToC::Wrap(exception), + CefV8StackTraceCppToC::Wrap(stackTrace)); +} + +void CefRenderProcessHandlerCToCpp::OnFocusedNodeChanged( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr node) { + if (CEF_MEMBER_MISSING(struct_, on_focused_node_changed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Unverified params: frame, node + + // Execute + struct_->on_focused_node_changed(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefDOMNodeCppToC::Wrap(node)); +} + +bool CefRenderProcessHandlerCToCpp::OnProcessMessageReceived( + CefRefPtr browser, CefProcessId source_process, + CefRefPtr message) { + if (CEF_MEMBER_MISSING(struct_, on_process_message_received)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: message; type: refptr_diff + DCHECK(message.get()); + if (!message.get()) + return false; + + // Execute + int _retval = struct_->on_process_message_received(struct_, + CefBrowserCppToC::Wrap(browser), + source_process, + CefProcessMessageCppToC::Wrap(message)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/render_process_handler_ctocpp.h b/libcef_dll/ctocpp/render_process_handler_ctocpp.h new file mode 100644 index 000000000..59be0932d --- /dev/null +++ b/libcef_dll/ctocpp/render_process_handler_ctocpp.h @@ -0,0 +1,61 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_RENDER_PROCESS_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_RENDER_PROCESS_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_render_process_handler.h" +#include "include/capi/cef_render_process_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefRenderProcessHandlerCToCpp + : public CefCToCpp { + public: + explicit CefRenderProcessHandlerCToCpp(cef_render_process_handler_t* str) + : CefCToCpp(str) {} + + // CefRenderProcessHandler methods + void OnRenderThreadCreated(CefRefPtr extra_info) override; + void OnWebKitInitialized() override; + void OnBrowserCreated(CefRefPtr browser) override; + void OnBrowserDestroyed(CefRefPtr browser) override; + CefRefPtr GetLoadHandler() override; + bool OnBeforeNavigation(CefRefPtr browser, + CefRefPtr frame, CefRefPtr request, + NavigationType navigation_type, bool is_redirect) override; + void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, CefRefPtr context) override; + void OnContextReleased(CefRefPtr browser, + CefRefPtr frame, CefRefPtr context) override; + void OnUncaughtException(CefRefPtr browser, + CefRefPtr frame, CefRefPtr context, + CefRefPtr exception, + CefRefPtr stackTrace) override; + void OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, CefRefPtr node) override; + bool OnProcessMessageReceived(CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RENDER_PROCESS_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/request_context_ctocpp.cc b/libcef_dll/ctocpp/request_context_ctocpp.cc new file mode 100644 index 000000000..9ca570821 --- /dev/null +++ b/libcef_dll/ctocpp/request_context_ctocpp.cc @@ -0,0 +1,96 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/request_context_handler_cpptoc.h" +#include "libcef_dll/ctocpp/request_context_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefRequestContext::GetGlobalContext() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_request_context_t* _retval = cef_request_context_get_global_context(); + + // Return type: refptr_same + return CefRequestContextCToCpp::Wrap(_retval); +} + +CefRefPtr CefRequestContext::CreateContext( + CefRefPtr handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: handler + + // Execute + cef_request_context_t* _retval = cef_request_context_create_context( + CefRequestContextHandlerCppToC::Wrap(handler)); + + // Return type: refptr_same + return CefRequestContextCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefRequestContextCToCpp::IsSame(CefRefPtr other) { + if (CEF_MEMBER_MISSING(struct_, is_same)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: other; type: refptr_same + DCHECK(other.get()); + if (!other.get()) + return false; + + // Execute + int _retval = struct_->is_same(struct_, + CefRequestContextCToCpp::Unwrap(other)); + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestContextCToCpp::IsGlobal() { + if (CEF_MEMBER_MISSING(struct_, is_global)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_global(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefRequestContextCToCpp::GetHandler() { + if (CEF_MEMBER_MISSING(struct_, get_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_request_context_handler_t* _retval = struct_->get_handler(struct_); + + // Return type: refptr_diff + return CefRequestContextHandlerCppToC::Unwrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/request_context_ctocpp.h b/libcef_dll/ctocpp/request_context_ctocpp.h new file mode 100644 index 000000000..a4eff0359 --- /dev/null +++ b/libcef_dll/ctocpp/request_context_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_REQUEST_CONTEXT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_REQUEST_CONTEXT_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request_context.h" +#include "include/capi/cef_request_context_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefRequestContextCToCpp + : public CefCToCpp { + public: + explicit CefRequestContextCToCpp(cef_request_context_t* str) + : CefCToCpp(str) {} + + // CefRequestContext methods + virtual bool IsSame(CefRefPtr other) OVERRIDE; + virtual bool IsGlobal() OVERRIDE; + virtual CefRefPtr GetHandler() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_CONTEXT_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/request_context_handler_ctocpp.cc b/libcef_dll/ctocpp/request_context_handler_ctocpp.cc new file mode 100644 index 000000000..dd0ba9e98 --- /dev/null +++ b/libcef_dll/ctocpp/request_context_handler_ctocpp.cc @@ -0,0 +1,37 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h" +#include "libcef_dll/ctocpp/request_context_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefRequestContextHandlerCToCpp::GetCookieManager() { + if (CEF_MEMBER_MISSING(struct_, get_cookie_manager)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_cookie_manager_t* _retval = struct_->get_cookie_manager(struct_); + + // Return type: refptr_diff + return CefCookieManagerCppToC::Unwrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/request_context_handler_ctocpp.h b/libcef_dll/ctocpp/request_context_handler_ctocpp.h new file mode 100644 index 000000000..133b01dbe --- /dev/null +++ b/libcef_dll/ctocpp/request_context_handler_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_REQUEST_CONTEXT_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_REQUEST_CONTEXT_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request_context_handler.h" +#include "include/capi/cef_request_context_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefRequestContextHandlerCToCpp + : public CefCToCpp { + public: + explicit CefRequestContextHandlerCToCpp(cef_request_context_handler_t* str) + : CefCToCpp(str) {} + + // CefRequestContextHandler methods + CefRefPtr GetCookieManager() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_CONTEXT_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/request_ctocpp.cc b/libcef_dll/ctocpp/request_ctocpp.cc new file mode 100644 index 000000000..bac0dd35a --- /dev/null +++ b/libcef_dll/ctocpp/request_ctocpp.cc @@ -0,0 +1,303 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/post_data_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefRequest::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_request_t* _retval = cef_request_create(); + + // Return type: refptr_same + return CefRequestCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefRequestCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefRequestCToCpp::GetURL() { + if (CEF_MEMBER_MISSING(struct_, get_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_url(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefRequestCToCpp::SetURL(const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, set_url)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->set_url(struct_, + url.GetStruct()); +} + +CefString CefRequestCToCpp::GetMethod() { + if (CEF_MEMBER_MISSING(struct_, get_method)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_method(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefRequestCToCpp::SetMethod(const CefString& method) { + if (CEF_MEMBER_MISSING(struct_, set_method)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: method; type: string_byref_const + DCHECK(!method.empty()); + if (method.empty()) + return; + + // Execute + struct_->set_method(struct_, + method.GetStruct()); +} + +CefRefPtr CefRequestCToCpp::GetPostData() { + if (CEF_MEMBER_MISSING(struct_, get_post_data)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_post_data_t* _retval = struct_->get_post_data(struct_); + + // Return type: refptr_same + return CefPostDataCToCpp::Wrap(_retval); +} + +void CefRequestCToCpp::SetPostData(CefRefPtr postData) { + if (CEF_MEMBER_MISSING(struct_, set_post_data)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: postData; type: refptr_same + DCHECK(postData.get()); + if (!postData.get()) + return; + + // Execute + struct_->set_post_data(struct_, + CefPostDataCToCpp::Unwrap(postData)); +} + +void CefRequestCToCpp::GetHeaderMap(HeaderMap& headerMap) { + if (CEF_MEMBER_MISSING(struct_, get_header_map)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: headerMap; type: string_map_multi_byref + cef_string_multimap_t headerMapMultimap = cef_string_multimap_alloc(); + DCHECK(headerMapMultimap); + if (headerMapMultimap) + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + struct_->get_header_map(struct_, + headerMapMultimap); + + // Restore param:headerMap; type: string_map_multi_byref + if (headerMapMultimap) { + headerMap.clear(); + transfer_string_multimap_contents(headerMapMultimap, headerMap); + cef_string_multimap_free(headerMapMultimap); + } +} + +void CefRequestCToCpp::SetHeaderMap(const HeaderMap& headerMap) { + if (CEF_MEMBER_MISSING(struct_, set_header_map)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: headerMap; type: string_map_multi_byref_const + cef_string_multimap_t headerMapMultimap = cef_string_multimap_alloc(); + DCHECK(headerMapMultimap); + if (headerMapMultimap) + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + struct_->set_header_map(struct_, + headerMapMultimap); + + // Restore param:headerMap; type: string_map_multi_byref_const + if (headerMapMultimap) + cef_string_multimap_free(headerMapMultimap); +} + +void CefRequestCToCpp::Set(const CefString& url, const CefString& method, + CefRefPtr postData, const HeaderMap& headerMap) { + if (CEF_MEMBER_MISSING(struct_, set)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + // Verify param: method; type: string_byref_const + DCHECK(!method.empty()); + if (method.empty()) + return; + // Unverified params: postData + + // Translate param: headerMap; type: string_map_multi_byref_const + cef_string_multimap_t headerMapMultimap = cef_string_multimap_alloc(); + DCHECK(headerMapMultimap); + if (headerMapMultimap) + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + struct_->set(struct_, + url.GetStruct(), + method.GetStruct(), + CefPostDataCToCpp::Unwrap(postData), + headerMapMultimap); + + // Restore param:headerMap; type: string_map_multi_byref_const + if (headerMapMultimap) + cef_string_multimap_free(headerMapMultimap); +} + +int CefRequestCToCpp::GetFlags() { + if (CEF_MEMBER_MISSING(struct_, get_flags)) + return UR_FLAG_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_flags(struct_); + + // Return type: simple + return _retval; +} + +void CefRequestCToCpp::SetFlags(int flags) { + if (CEF_MEMBER_MISSING(struct_, set_flags)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_flags(struct_, + flags); +} + +CefString CefRequestCToCpp::GetFirstPartyForCookies() { + if (CEF_MEMBER_MISSING(struct_, get_first_party_for_cookies)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_first_party_for_cookies(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefRequestCToCpp::SetFirstPartyForCookies(const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, set_first_party_for_cookies)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->set_first_party_for_cookies(struct_, + url.GetStruct()); +} + +CefRequest::ResourceType CefRequestCToCpp::GetResourceType() { + if (CEF_MEMBER_MISSING(struct_, get_resource_type)) + return RT_SUB_RESOURCE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_resource_type_t _retval = struct_->get_resource_type(struct_); + + // Return type: simple + return _retval; +} + +CefRequest::TransitionType CefRequestCToCpp::GetTransitionType() { + if (CEF_MEMBER_MISSING(struct_, get_transition_type)) + return TT_EXPLICIT; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_transition_type_t _retval = struct_->get_transition_type(struct_); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/request_ctocpp.h b/libcef_dll/ctocpp/request_ctocpp.h new file mode 100644 index 000000000..c90fd2c5f --- /dev/null +++ b/libcef_dll/ctocpp/request_ctocpp.h @@ -0,0 +1,55 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_REQUEST_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_REQUEST_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_request.h" +#include "include/capi/cef_request_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefRequestCToCpp + : public CefCToCpp { + public: + explicit CefRequestCToCpp(cef_request_t* str) + : CefCToCpp(str) {} + + // CefRequest methods + virtual bool IsReadOnly() OVERRIDE; + virtual CefString GetURL() OVERRIDE; + virtual void SetURL(const CefString& url) OVERRIDE; + virtual CefString GetMethod() OVERRIDE; + virtual void SetMethod(const CefString& method) OVERRIDE; + virtual CefRefPtr GetPostData() OVERRIDE; + virtual void SetPostData(CefRefPtr postData) OVERRIDE; + virtual void GetHeaderMap(HeaderMap& headerMap) OVERRIDE; + virtual void SetHeaderMap(const HeaderMap& headerMap) OVERRIDE; + virtual void Set(const CefString& url, const CefString& method, + CefRefPtr postData, const HeaderMap& headerMap) OVERRIDE; + virtual int GetFlags() OVERRIDE; + virtual void SetFlags(int flags) OVERRIDE; + virtual CefString GetFirstPartyForCookies() OVERRIDE; + virtual void SetFirstPartyForCookies(const CefString& url) OVERRIDE; + virtual ResourceType GetResourceType() OVERRIDE; + virtual TransitionType GetTransitionType() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/request_handler_ctocpp.cc b/libcef_dll/ctocpp/request_handler_ctocpp.cc new file mode 100644 index 000000000..8bb196293 --- /dev/null +++ b/libcef_dll/ctocpp/request_handler_ctocpp.cc @@ -0,0 +1,356 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.h" +#include "libcef_dll/cpptoc/auth_callback_cpptoc.h" +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/quota_callback_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/web_plugin_info_cpptoc.h" +#include "libcef_dll/ctocpp/request_handler_ctocpp.h" +#include "libcef_dll/ctocpp/resource_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefRequestHandlerCToCpp::OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, CefRefPtr request, + bool is_redirect) { + if (CEF_MEMBER_MISSING(struct_, on_before_browse)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return false; + + // Execute + int _retval = struct_->on_before_browse(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefRequestCppToC::Wrap(request), + is_redirect); + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestHandlerCToCpp::OnBeforeResourceLoad( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr request) { + if (CEF_MEMBER_MISSING(struct_, on_before_resource_load)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return false; + + // Execute + int _retval = struct_->on_before_resource_load(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefRequestCppToC::Wrap(request)); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefRequestHandlerCToCpp::GetResourceHandler( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr request) { + if (CEF_MEMBER_MISSING(struct_, get_resource_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return NULL; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return NULL; + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return NULL; + + // Execute + cef_resource_handler_t* _retval = struct_->get_resource_handler(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + CefRequestCppToC::Wrap(request)); + + // Return type: refptr_same + return CefResourceHandlerCToCpp::Wrap(_retval); +} + +void CefRequestHandlerCToCpp::OnResourceRedirect(CefRefPtr browser, + CefRefPtr frame, const CefString& old_url, CefString& new_url) { + if (CEF_MEMBER_MISSING(struct_, on_resource_redirect)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return; + // Verify param: old_url; type: string_byref_const + DCHECK(!old_url.empty()); + if (old_url.empty()) + return; + + // Execute + struct_->on_resource_redirect(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + old_url.GetStruct(), + new_url.GetWritableStruct()); +} + +bool CefRequestHandlerCToCpp::GetAuthCredentials(CefRefPtr browser, + CefRefPtr frame, bool isProxy, const CefString& host, int port, + const CefString& realm, const CefString& scheme, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, get_auth_credentials)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: frame; type: refptr_diff + DCHECK(frame.get()); + if (!frame.get()) + return false; + // Verify param: host; type: string_byref_const + DCHECK(!host.empty()); + if (host.empty()) + return false; + // Verify param: scheme; type: string_byref_const + DCHECK(!scheme.empty()); + if (scheme.empty()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + // Unverified params: realm + + // Execute + int _retval = struct_->get_auth_credentials(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + isProxy, + host.GetStruct(), + port, + realm.GetStruct(), + scheme.GetStruct(), + CefAuthCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestHandlerCToCpp::OnQuotaRequest(CefRefPtr browser, + const CefString& origin_url, int64 new_size, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_quota_request)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: origin_url; type: string_byref_const + DCHECK(!origin_url.empty()); + if (origin_url.empty()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->on_quota_request(struct_, + CefBrowserCppToC::Wrap(browser), + origin_url.GetStruct(), + new_size, + CefQuotaCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefRequestHandlerCToCpp::OnProtocolExecution(CefRefPtr browser, + const CefString& url, bool& allow_os_execution) { + if (CEF_MEMBER_MISSING(struct_, on_protocol_execution)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Translate param: allow_os_execution; type: bool_byref + int allow_os_executionInt = allow_os_execution; + + // Execute + struct_->on_protocol_execution(struct_, + CefBrowserCppToC::Wrap(browser), + url.GetStruct(), + &allow_os_executionInt); + + // Restore param:allow_os_execution; type: bool_byref + allow_os_execution = allow_os_executionInt?true:false; +} + +bool CefRequestHandlerCToCpp::OnCertificateError(cef_errorcode_t cert_error, + const CefString& request_url, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, on_certificate_error)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request_url; type: string_byref_const + DCHECK(!request_url.empty()); + if (request_url.empty()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->on_certificate_error(struct_, + cert_error, + request_url.GetStruct(), + CefAllowCertificateErrorCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestHandlerCToCpp::OnBeforePluginLoad(CefRefPtr browser, + const CefString& url, const CefString& policy_url, + CefRefPtr info) { + if (CEF_MEMBER_MISSING(struct_, on_before_plugin_load)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return false; + // Verify param: info; type: refptr_diff + DCHECK(info.get()); + if (!info.get()) + return false; + // Unverified params: url, policy_url + + // Execute + int _retval = struct_->on_before_plugin_load(struct_, + CefBrowserCppToC::Wrap(browser), + url.GetStruct(), + policy_url.GetStruct(), + CefWebPluginInfoCppToC::Wrap(info)); + + // Return type: bool + return _retval?true:false; +} + +void CefRequestHandlerCToCpp::OnPluginCrashed(CefRefPtr browser, + const CefString& plugin_path) { + if (CEF_MEMBER_MISSING(struct_, on_plugin_crashed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + // Verify param: plugin_path; type: string_byref_const + DCHECK(!plugin_path.empty()); + if (plugin_path.empty()) + return; + + // Execute + struct_->on_plugin_crashed(struct_, + CefBrowserCppToC::Wrap(browser), + plugin_path.GetStruct()); +} + +void CefRequestHandlerCToCpp::OnRenderProcessTerminated( + CefRefPtr browser, TerminationStatus status) { + if (CEF_MEMBER_MISSING(struct_, on_render_process_terminated)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->on_render_process_terminated(struct_, + CefBrowserCppToC::Wrap(browser), + status); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/request_handler_ctocpp.h b/libcef_dll/ctocpp/request_handler_ctocpp.h new file mode 100644 index 000000000..989b36bbe --- /dev/null +++ b/libcef_dll/ctocpp/request_handler_ctocpp.h @@ -0,0 +1,68 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_REQUEST_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_REQUEST_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_request_handler.h" +#include "include/capi/cef_request_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefRequestHandlerCToCpp + : public CefCToCpp { + public: + explicit CefRequestHandlerCToCpp(cef_request_handler_t* str) + : CefCToCpp(str) {} + + // CefRequestHandler methods + bool OnBeforeBrowse(CefRefPtr browser, CefRefPtr frame, + CefRefPtr request, bool is_redirect) override; + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, CefRefPtr request) override; + CefRefPtr GetResourceHandler( + CefRefPtr browser, CefRefPtr frame, + CefRefPtr request) override; + void OnResourceRedirect(CefRefPtr browser, + CefRefPtr frame, const CefString& old_url, + CefString& new_url) override; + bool GetAuthCredentials(CefRefPtr browser, + CefRefPtr frame, bool isProxy, const CefString& host, int port, + const CefString& realm, const CefString& scheme, + CefRefPtr callback) override; + bool OnQuotaRequest(CefRefPtr browser, + const CefString& origin_url, int64 new_size, + CefRefPtr callback) override; + void OnProtocolExecution(CefRefPtr browser, const CefString& url, + bool& allow_os_execution) override; + bool OnCertificateError(cef_errorcode_t cert_error, + const CefString& request_url, + CefRefPtr callback) override; + bool OnBeforePluginLoad(CefRefPtr browser, const CefString& url, + const CefString& policy_url, CefRefPtr info) override; + void OnPluginCrashed(CefRefPtr browser, + const CefString& plugin_path) override; + void OnRenderProcessTerminated(CefRefPtr browser, + TerminationStatus status) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.cc b/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.cc new file mode 100644 index 000000000..85b2ab24f --- /dev/null +++ b/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefResourceBundleHandlerCToCpp::GetLocalizedString(int message_id, + CefString& string) { + if (CEF_MEMBER_MISSING(struct_, get_localized_string)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_localized_string(struct_, + message_id, + string.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefResourceBundleHandlerCToCpp::GetDataResource(int resource_id, + void*& data, size_t& data_size) { + if (CEF_MEMBER_MISSING(struct_, get_data_resource)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_data_resource(struct_, + resource_id, + &data, + &data_size); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h b/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h new file mode 100644 index 000000000..fa61b6ee2 --- /dev/null +++ b/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_RESOURCE_BUNDLE_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_RESOURCE_BUNDLE_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_resource_bundle_handler.h" +#include "include/capi/cef_resource_bundle_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefResourceBundleHandlerCToCpp + : public CefCToCpp { + public: + explicit CefResourceBundleHandlerCToCpp(cef_resource_bundle_handler_t* str) + : CefCToCpp(str) {} + + // CefResourceBundleHandler methods + bool GetLocalizedString(int message_id, CefString& string) override; + bool GetDataResource(int resource_id, void*& data, + size_t& data_size) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RESOURCE_BUNDLE_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/resource_handler_ctocpp.cc b/libcef_dll/ctocpp/resource_handler_ctocpp.cc new file mode 100644 index 000000000..39a09e72a --- /dev/null +++ b/libcef_dll/ctocpp/resource_handler_ctocpp.cc @@ -0,0 +1,136 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/callback_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/response_cpptoc.h" +#include "libcef_dll/ctocpp/resource_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefResourceHandlerCToCpp::ProcessRequest(CefRefPtr request, + CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, process_request)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->process_request(struct_, + CefRequestCppToC::Wrap(request), + CefCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefResourceHandlerCToCpp::GetResponseHeaders( + CefRefPtr response, int64& response_length, + CefString& redirectUrl) { + if (CEF_MEMBER_MISSING(struct_, get_response_headers)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: response; type: refptr_diff + DCHECK(response.get()); + if (!response.get()) + return; + + // Execute + struct_->get_response_headers(struct_, + CefResponseCppToC::Wrap(response), + &response_length, + redirectUrl.GetWritableStruct()); +} + +bool CefResourceHandlerCToCpp::ReadResponse(void* data_out, int bytes_to_read, + int& bytes_read, CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, read_response)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data_out; type: simple_byaddr + DCHECK(data_out); + if (!data_out) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = struct_->read_response(struct_, + data_out, + bytes_to_read, + &bytes_read, + CefCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +bool CefResourceHandlerCToCpp::CanGetCookie(const CefCookie& cookie) { + if (CEF_MEMBER_MISSING(struct_, can_get_cookie)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->can_get_cookie(struct_, + &cookie); + + // Return type: bool + return _retval?true:false; +} + +bool CefResourceHandlerCToCpp::CanSetCookie(const CefCookie& cookie) { + if (CEF_MEMBER_MISSING(struct_, can_set_cookie)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->can_set_cookie(struct_, + &cookie); + + // Return type: bool + return _retval?true:false; +} + +void CefResourceHandlerCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/resource_handler_ctocpp.h b/libcef_dll/ctocpp/resource_handler_ctocpp.h new file mode 100644 index 000000000..1d65272bc --- /dev/null +++ b/libcef_dll/ctocpp/resource_handler_ctocpp.h @@ -0,0 +1,49 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_RESOURCE_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_RESOURCE_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_resource_handler.h" +#include "include/capi/cef_resource_handler_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefResourceHandlerCToCpp + : public CefCToCpp { + public: + explicit CefResourceHandlerCToCpp(cef_resource_handler_t* str) + : CefCToCpp(str) {} + + // CefResourceHandler methods + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override; + void GetResponseHeaders(CefRefPtr response, + int64& response_length, CefString& redirectUrl) override; + bool ReadResponse(void* data_out, int bytes_to_read, int& bytes_read, + CefRefPtr callback) override; + bool CanGetCookie(const CefCookie& cookie) override; + bool CanSetCookie(const CefCookie& cookie) override; + void Cancel() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RESOURCE_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/response_ctocpp.cc b/libcef_dll/ctocpp/response_ctocpp.cc new file mode 100644 index 000000000..6d5373dec --- /dev/null +++ b/libcef_dll/ctocpp/response_ctocpp.cc @@ -0,0 +1,202 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/response_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefResponse::Create() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_response_t* _retval = cef_response_create(); + + // Return type: refptr_same + return CefResponseCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefResponseCToCpp::IsReadOnly() { + if (CEF_MEMBER_MISSING(struct_, is_read_only)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_read_only(struct_); + + // Return type: bool + return _retval?true:false; +} + +int CefResponseCToCpp::GetStatus() { + if (CEF_MEMBER_MISSING(struct_, get_status)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_status(struct_); + + // Return type: simple + return _retval; +} + +void CefResponseCToCpp::SetStatus(int status) { + if (CEF_MEMBER_MISSING(struct_, set_status)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_status(struct_, + status); +} + +CefString CefResponseCToCpp::GetStatusText() { + if (CEF_MEMBER_MISSING(struct_, get_status_text)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_status_text(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefResponseCToCpp::SetStatusText(const CefString& statusText) { + if (CEF_MEMBER_MISSING(struct_, set_status_text)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: statusText; type: string_byref_const + DCHECK(!statusText.empty()); + if (statusText.empty()) + return; + + // Execute + struct_->set_status_text(struct_, + statusText.GetStruct()); +} + +CefString CefResponseCToCpp::GetMimeType() { + if (CEF_MEMBER_MISSING(struct_, get_mime_type)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_mime_type(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefResponseCToCpp::SetMimeType(const CefString& mimeType) { + if (CEF_MEMBER_MISSING(struct_, set_mime_type)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: mimeType; type: string_byref_const + DCHECK(!mimeType.empty()); + if (mimeType.empty()) + return; + + // Execute + struct_->set_mime_type(struct_, + mimeType.GetStruct()); +} + +CefString CefResponseCToCpp::GetHeader(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, get_header)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_header(struct_, + name.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +void CefResponseCToCpp::GetHeaderMap(HeaderMap& headerMap) { + if (CEF_MEMBER_MISSING(struct_, get_header_map)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: headerMap; type: string_map_multi_byref + cef_string_multimap_t headerMapMultimap = cef_string_multimap_alloc(); + DCHECK(headerMapMultimap); + if (headerMapMultimap) + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + struct_->get_header_map(struct_, + headerMapMultimap); + + // Restore param:headerMap; type: string_map_multi_byref + if (headerMapMultimap) { + headerMap.clear(); + transfer_string_multimap_contents(headerMapMultimap, headerMap); + cef_string_multimap_free(headerMapMultimap); + } +} + +void CefResponseCToCpp::SetHeaderMap(const HeaderMap& headerMap) { + if (CEF_MEMBER_MISSING(struct_, set_header_map)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: headerMap; type: string_map_multi_byref_const + cef_string_multimap_t headerMapMultimap = cef_string_multimap_alloc(); + DCHECK(headerMapMultimap); + if (headerMapMultimap) + transfer_string_multimap_contents(headerMap, headerMapMultimap); + + // Execute + struct_->set_header_map(struct_, + headerMapMultimap); + + // Restore param:headerMap; type: string_map_multi_byref_const + if (headerMapMultimap) + cef_string_multimap_free(headerMapMultimap); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/response_ctocpp.h b/libcef_dll/ctocpp/response_ctocpp.h new file mode 100644 index 000000000..9aa557018 --- /dev/null +++ b/libcef_dll/ctocpp/response_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_RESPONSE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_RESPONSE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_response.h" +#include "include/capi/cef_response_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefResponseCToCpp + : public CefCToCpp { + public: + explicit CefResponseCToCpp(cef_response_t* str) + : CefCToCpp(str) {} + + // CefResponse methods + virtual bool IsReadOnly() OVERRIDE; + virtual int GetStatus() OVERRIDE; + virtual void SetStatus(int status) OVERRIDE; + virtual CefString GetStatusText() OVERRIDE; + virtual void SetStatusText(const CefString& statusText) OVERRIDE; + virtual CefString GetMimeType() OVERRIDE; + virtual void SetMimeType(const CefString& mimeType) OVERRIDE; + virtual CefString GetHeader(const CefString& name) OVERRIDE; + virtual void GetHeaderMap(HeaderMap& headerMap) OVERRIDE; + virtual void SetHeaderMap(const HeaderMap& headerMap) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RESPONSE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.cc b/libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.cc new file mode 100644 index 000000000..ce7a70f38 --- /dev/null +++ b/libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.cc @@ -0,0 +1,53 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefRunFileDialogCallbackCToCpp::OnFileDialogDismissed( + int selected_accept_filter, const std::vector& file_paths) { + if (CEF_MEMBER_MISSING(struct_, on_file_dialog_dismissed)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: selected_accept_filter; type: simple_byval + DCHECK_GE(selected_accept_filter, 0); + if (selected_accept_filter < 0) + return; + // Unverified params: file_paths + + // Translate param: file_paths; type: string_vec_byref_const + cef_string_list_t file_pathsList = cef_string_list_alloc(); + DCHECK(file_pathsList); + if (file_pathsList) + transfer_string_list_contents(file_paths, file_pathsList); + + // Execute + struct_->on_file_dialog_dismissed(struct_, + selected_accept_filter, + file_pathsList); + + // Restore param:file_paths; type: string_vec_byref_const + if (file_pathsList) + cef_string_list_free(file_pathsList); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h b/libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h new file mode 100644 index 000000000..af1300cfa --- /dev/null +++ b/libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_RUN_FILE_DIALOG_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_RUN_FILE_DIALOG_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include +#include "include/cef_browser.h" +#include "include/capi/cef_browser_capi.h" +#include "include/cef_client.h" +#include "include/capi/cef_client_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefRunFileDialogCallbackCToCpp + : public CefCToCpp { + public: + explicit CefRunFileDialogCallbackCToCpp(cef_run_file_dialog_callback_t* str) + : CefCToCpp(str) {} + + // CefRunFileDialogCallback methods + void OnFileDialogDismissed(int selected_accept_filter, + const std::vector& file_paths) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RUN_FILE_DIALOG_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc new file mode 100644 index 000000000..cbc02d5be --- /dev/null +++ b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc @@ -0,0 +1,56 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/ctocpp/resource_handler_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefSchemeHandlerFactoryCToCpp::Create( + CefRefPtr browser, CefRefPtr frame, + const CefString& scheme_name, CefRefPtr request) { + if (CEF_MEMBER_MISSING(struct_, create)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: scheme_name; type: string_byref_const + DCHECK(!scheme_name.empty()); + if (scheme_name.empty()) + return NULL; + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return NULL; + // Unverified params: browser, frame + + // Execute + cef_resource_handler_t* _retval = struct_->create(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + scheme_name.GetStruct(), + CefRequestCppToC::Wrap(request)); + + // Return type: refptr_same + return CefResourceHandlerCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h new file mode 100644 index 000000000..660c5ed8c --- /dev/null +++ b/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_FACTORY_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_FACTORY_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_scheme.h" +#include "include/capi/cef_scheme_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefSchemeHandlerFactoryCToCpp + : public CefCToCpp { + public: + explicit CefSchemeHandlerFactoryCToCpp(cef_scheme_handler_factory_t* str) + : CefCToCpp(str) {} + + // CefSchemeHandlerFactory methods + CefRefPtr Create(CefRefPtr browser, + CefRefPtr frame, const CefString& scheme_name, + CefRefPtr request) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_FACTORY_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/scheme_registrar_ctocpp.cc b/libcef_dll/ctocpp/scheme_registrar_ctocpp.cc new file mode 100644 index 000000000..cb4bb0b5a --- /dev/null +++ b/libcef_dll/ctocpp/scheme_registrar_ctocpp.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/scheme_registrar_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefSchemeRegistrarCToCpp::AddCustomScheme(const CefString& scheme_name, + bool is_standard, bool is_local, bool is_display_isolated) { + if (CEF_MEMBER_MISSING(struct_, add_custom_scheme)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: scheme_name; type: string_byref_const + DCHECK(!scheme_name.empty()); + if (scheme_name.empty()) + return false; + + // Execute + int _retval = struct_->add_custom_scheme(struct_, + scheme_name.GetStruct(), + is_standard, + is_local, + is_display_isolated); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/scheme_registrar_ctocpp.h b/libcef_dll/ctocpp/scheme_registrar_ctocpp.h new file mode 100644 index 000000000..a5141999d --- /dev/null +++ b/libcef_dll/ctocpp/scheme_registrar_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_SCHEME_REGISTRAR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_SCHEME_REGISTRAR_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_scheme.h" +#include "include/capi/cef_scheme_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefSchemeRegistrarCToCpp + : public CefCToCpp { + public: + explicit CefSchemeRegistrarCToCpp(cef_scheme_registrar_t* str) + : CefCToCpp(str) {} + + // CefSchemeRegistrar methods + virtual bool AddCustomScheme(const CefString& scheme_name, bool is_standard, + bool is_local, bool is_display_isolated) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_SCHEME_REGISTRAR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/stream_reader_ctocpp.cc b/libcef_dll/ctocpp/stream_reader_ctocpp.cc new file mode 100644 index 000000000..051c96def --- /dev/null +++ b/libcef_dll/ctocpp/stream_reader_ctocpp.cc @@ -0,0 +1,154 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/read_handler_cpptoc.h" +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefStreamReader::CreateForFile( + const CefString& fileName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(!fileName.empty()); + if (fileName.empty()) + return NULL; + + // Execute + cef_stream_reader_t* _retval = cef_stream_reader_create_for_file( + fileName.GetStruct()); + + // Return type: refptr_same + return CefStreamReaderCToCpp::Wrap(_retval); +} + +CefRefPtr CefStreamReader::CreateForData(void* data, + size_t size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return NULL; + + // Execute + cef_stream_reader_t* _retval = cef_stream_reader_create_for_data( + data, + size); + + // Return type: refptr_same + return CefStreamReaderCToCpp::Wrap(_retval); +} + +CefRefPtr CefStreamReader::CreateForHandler( + CefRefPtr handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: handler; type: refptr_diff + DCHECK(handler.get()); + if (!handler.get()) + return NULL; + + // Execute + cef_stream_reader_t* _retval = cef_stream_reader_create_for_handler( + CefReadHandlerCppToC::Wrap(handler)); + + // Return type: refptr_same + return CefStreamReaderCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +size_t CefStreamReaderCToCpp::Read(void* ptr, size_t size, size_t n) { + if (CEF_MEMBER_MISSING(struct_, read)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = struct_->read(struct_, + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CefStreamReaderCToCpp::Seek(int64 offset, int whence) { + if (CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->seek(struct_, + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CefStreamReaderCToCpp::Tell() { + if (CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->tell(struct_); + + // Return type: simple + return _retval; +} + +int CefStreamReaderCToCpp::Eof() { + if (CEF_MEMBER_MISSING(struct_, eof)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->eof(struct_); + + // Return type: simple + return _retval; +} + +bool CefStreamReaderCToCpp::MayBlock() { + if (CEF_MEMBER_MISSING(struct_, may_block)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->may_block(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/stream_reader_ctocpp.h b/libcef_dll/ctocpp/stream_reader_ctocpp.h new file mode 100644 index 000000000..41459a9b5 --- /dev/null +++ b/libcef_dll/ctocpp/stream_reader_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_STREAM_READER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_STREAM_READER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefStreamReaderCToCpp + : public CefCToCpp { + public: + explicit CefStreamReaderCToCpp(cef_stream_reader_t* str) + : CefCToCpp( + str) {} + + // CefStreamReader methods + virtual size_t Read(void* ptr, size_t size, size_t n) OVERRIDE; + virtual int Seek(int64 offset, int whence) OVERRIDE; + virtual int64 Tell() OVERRIDE; + virtual int Eof() OVERRIDE; + virtual bool MayBlock() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_STREAM_READER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/stream_writer_ctocpp.cc b/libcef_dll/ctocpp/stream_writer_ctocpp.cc new file mode 100644 index 000000000..382efdc1f --- /dev/null +++ b/libcef_dll/ctocpp/stream_writer_ctocpp.cc @@ -0,0 +1,136 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/write_handler_cpptoc.h" +#include "libcef_dll/ctocpp/stream_writer_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefStreamWriter::CreateForFile( + const CefString& fileName) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(!fileName.empty()); + if (fileName.empty()) + return NULL; + + // Execute + cef_stream_writer_t* _retval = cef_stream_writer_create_for_file( + fileName.GetStruct()); + + // Return type: refptr_same + return CefStreamWriterCToCpp::Wrap(_retval); +} + +CefRefPtr CefStreamWriter::CreateForHandler( + CefRefPtr handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: handler; type: refptr_diff + DCHECK(handler.get()); + if (!handler.get()) + return NULL; + + // Execute + cef_stream_writer_t* _retval = cef_stream_writer_create_for_handler( + CefWriteHandlerCppToC::Wrap(handler)); + + // Return type: refptr_same + return CefStreamWriterCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +size_t CefStreamWriterCToCpp::Write(const void* ptr, size_t size, size_t n) { + if (CEF_MEMBER_MISSING(struct_, write)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = struct_->write(struct_, + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CefStreamWriterCToCpp::Seek(int64 offset, int whence) { + if (CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->seek(struct_, + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CefStreamWriterCToCpp::Tell() { + if (CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->tell(struct_); + + // Return type: simple + return _retval; +} + +int CefStreamWriterCToCpp::Flush() { + if (CEF_MEMBER_MISSING(struct_, flush)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->flush(struct_); + + // Return type: simple + return _retval; +} + +bool CefStreamWriterCToCpp::MayBlock() { + if (CEF_MEMBER_MISSING(struct_, may_block)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->may_block(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/stream_writer_ctocpp.h b/libcef_dll/ctocpp/stream_writer_ctocpp.h new file mode 100644 index 000000000..03fe511fa --- /dev/null +++ b/libcef_dll/ctocpp/stream_writer_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_STREAM_WRITER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_STREAM_WRITER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefStreamWriterCToCpp + : public CefCToCpp { + public: + explicit CefStreamWriterCToCpp(cef_stream_writer_t* str) + : CefCToCpp( + str) {} + + // CefStreamWriter methods + virtual size_t Write(const void* ptr, size_t size, size_t n) OVERRIDE; + virtual int Seek(int64 offset, int whence) OVERRIDE; + virtual int64 Tell() OVERRIDE; + virtual int Flush() OVERRIDE; + virtual bool MayBlock() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_STREAM_WRITER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/string_visitor_ctocpp.cc b/libcef_dll/ctocpp/string_visitor_ctocpp.cc new file mode 100644 index 000000000..e6b6915d5 --- /dev/null +++ b/libcef_dll/ctocpp/string_visitor_ctocpp.cc @@ -0,0 +1,36 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/string_visitor_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefStringVisitorCToCpp::Visit(const CefString& string) { + if (CEF_MEMBER_MISSING(struct_, visit)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: string + + // Execute + struct_->visit(struct_, + string.GetStruct()); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/string_visitor_ctocpp.h b/libcef_dll/ctocpp/string_visitor_ctocpp.h new file mode 100644 index 000000000..788a8fcde --- /dev/null +++ b/libcef_dll/ctocpp/string_visitor_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_STRING_VISITOR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_STRING_VISITOR_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_string_visitor.h" +#include "include/capi/cef_string_visitor_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefStringVisitorCToCpp + : public CefCToCpp { + public: + explicit CefStringVisitorCToCpp(cef_string_visitor_t* str) + : CefCToCpp(str) {} + + // CefStringVisitor methods + void Visit(const CefString& string) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_STRING_VISITOR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/task_ctocpp.cc b/libcef_dll/ctocpp/task_ctocpp.cc new file mode 100644 index 000000000..9f28e3980 --- /dev/null +++ b/libcef_dll/ctocpp/task_ctocpp.cc @@ -0,0 +1,33 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/task_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefTaskCToCpp::Execute() { + if (CEF_MEMBER_MISSING(struct_, execute)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->execute(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/task_ctocpp.h b/libcef_dll/ctocpp/task_ctocpp.h new file mode 100644 index 000000000..c2fb222b8 --- /dev/null +++ b/libcef_dll/ctocpp/task_ctocpp.h @@ -0,0 +1,39 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_TASK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_TASK_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_task.h" +#include "include/capi/cef_task_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefTaskCToCpp + : public CefCToCpp { + public: + explicit CefTaskCToCpp(cef_task_t* str) + : CefCToCpp(str) {} + + // CefTask methods + void Execute() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_TASK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/task_runner_ctocpp.cc b/libcef_dll/ctocpp/task_runner_ctocpp.cc new file mode 100644 index 000000000..a7f6c46cb --- /dev/null +++ b/libcef_dll/ctocpp/task_runner_ctocpp.cc @@ -0,0 +1,134 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/task_cpptoc.h" +#include "libcef_dll/ctocpp/task_runner_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefTaskRunner::GetForCurrentThread() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_task_runner_t* _retval = cef_task_runner_get_for_current_thread(); + + // Return type: refptr_same + return CefTaskRunnerCToCpp::Wrap(_retval); +} + +CefRefPtr CefTaskRunner::GetForThread(CefThreadId threadId) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_task_runner_t* _retval = cef_task_runner_get_for_thread( + threadId); + + // Return type: refptr_same + return CefTaskRunnerCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefTaskRunnerCToCpp::IsSame(CefRefPtr that) { + if (CEF_MEMBER_MISSING(struct_, is_same)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: that; type: refptr_same + DCHECK(that.get()); + if (!that.get()) + return false; + + // Execute + int _retval = struct_->is_same(struct_, + CefTaskRunnerCToCpp::Unwrap(that)); + + // Return type: bool + return _retval?true:false; +} + +bool CefTaskRunnerCToCpp::BelongsToCurrentThread() { + if (CEF_MEMBER_MISSING(struct_, belongs_to_current_thread)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->belongs_to_current_thread(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefTaskRunnerCToCpp::BelongsToThread(CefThreadId threadId) { + if (CEF_MEMBER_MISSING(struct_, belongs_to_thread)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->belongs_to_thread(struct_, + threadId); + + // Return type: bool + return _retval?true:false; +} + +bool CefTaskRunnerCToCpp::PostTask(CefRefPtr task) { + if (CEF_MEMBER_MISSING(struct_, post_task)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: task; type: refptr_diff + DCHECK(task.get()); + if (!task.get()) + return false; + + // Execute + int _retval = struct_->post_task(struct_, + CefTaskCppToC::Wrap(task)); + + // Return type: bool + return _retval?true:false; +} + +bool CefTaskRunnerCToCpp::PostDelayedTask(CefRefPtr task, + int64 delay_ms) { + if (CEF_MEMBER_MISSING(struct_, post_delayed_task)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: task; type: refptr_diff + DCHECK(task.get()); + if (!task.get()) + return false; + + // Execute + int _retval = struct_->post_delayed_task(struct_, + CefTaskCppToC::Wrap(task), + delay_ms); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/task_runner_ctocpp.h b/libcef_dll/ctocpp/task_runner_ctocpp.h new file mode 100644 index 000000000..ce9fa6b3e --- /dev/null +++ b/libcef_dll/ctocpp/task_runner_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_TASK_RUNNER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_TASK_RUNNER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_task.h" +#include "include/capi/cef_task_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefTaskRunnerCToCpp + : public CefCToCpp { + public: + explicit CefTaskRunnerCToCpp(cef_task_runner_t* str) + : CefCToCpp(str) {} + + // CefTaskRunner methods + virtual bool IsSame(CefRefPtr that) OVERRIDE; + virtual bool BelongsToCurrentThread() OVERRIDE; + virtual bool BelongsToThread(CefThreadId threadId) OVERRIDE; + virtual bool PostTask(CefRefPtr task) OVERRIDE; + virtual bool PostDelayedTask(CefRefPtr task, + int64 delay_ms) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_TASK_RUNNER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/urlrequest_client_ctocpp.cc b/libcef_dll/ctocpp/urlrequest_client_ctocpp.cc new file mode 100644 index 000000000..c3e3560d0 --- /dev/null +++ b/libcef_dll/ctocpp/urlrequest_client_ctocpp.cc @@ -0,0 +1,138 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/auth_callback_cpptoc.h" +#include "libcef_dll/cpptoc/urlrequest_cpptoc.h" +#include "libcef_dll/ctocpp/urlrequest_client_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefURLRequestClientCToCpp::OnRequestComplete( + CefRefPtr request) { + if (CEF_MEMBER_MISSING(struct_, on_request_complete)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return; + + // Execute + struct_->on_request_complete(struct_, + CefURLRequestCppToC::Wrap(request)); +} + +void CefURLRequestClientCToCpp::OnUploadProgress( + CefRefPtr request, int64 current, int64 total) { + if (CEF_MEMBER_MISSING(struct_, on_upload_progress)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return; + + // Execute + struct_->on_upload_progress(struct_, + CefURLRequestCppToC::Wrap(request), + current, + total); +} + +void CefURLRequestClientCToCpp::OnDownloadProgress( + CefRefPtr request, int64 current, int64 total) { + if (CEF_MEMBER_MISSING(struct_, on_download_progress)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return; + + // Execute + struct_->on_download_progress(struct_, + CefURLRequestCppToC::Wrap(request), + current, + total); +} + +void CefURLRequestClientCToCpp::OnDownloadData(CefRefPtr request, + const void* data, size_t data_length) { + if (CEF_MEMBER_MISSING(struct_, on_download_data)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return; + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return; + + // Execute + struct_->on_download_data(struct_, + CefURLRequestCppToC::Wrap(request), + data, + data_length); +} + +bool CefURLRequestClientCToCpp::GetAuthCredentials(bool isProxy, + const CefString& host, int port, const CefString& realm, + const CefString& scheme, CefRefPtr callback) { + if (CEF_MEMBER_MISSING(struct_, get_auth_credentials)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: host; type: string_byref_const + DCHECK(!host.empty()); + if (host.empty()) + return false; + // Verify param: scheme; type: string_byref_const + DCHECK(!scheme.empty()); + if (scheme.empty()) + return false; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + // Unverified params: realm + + // Execute + int _retval = struct_->get_auth_credentials(struct_, + isProxy, + host.GetStruct(), + port, + realm.GetStruct(), + scheme.GetStruct(), + CefAuthCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/urlrequest_client_ctocpp.h b/libcef_dll/ctocpp/urlrequest_client_ctocpp.h new file mode 100644 index 000000000..3c2e61640 --- /dev/null +++ b/libcef_dll/ctocpp/urlrequest_client_ctocpp.h @@ -0,0 +1,50 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CLIENT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CLIENT_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_urlrequest.h" +#include "include/capi/cef_urlrequest_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefURLRequestClientCToCpp + : public CefCToCpp { + public: + explicit CefURLRequestClientCToCpp(cef_urlrequest_client_t* str) + : CefCToCpp(str) {} + + // CefURLRequestClient methods + void OnRequestComplete(CefRefPtr request) override; + void OnUploadProgress(CefRefPtr request, int64 current, + int64 total) override; + void OnDownloadProgress(CefRefPtr request, int64 current, + int64 total) override; + void OnDownloadData(CefRefPtr request, const void* data, + size_t data_length) override; + bool GetAuthCredentials(bool isProxy, const CefString& host, int port, + const CefString& realm, const CefString& scheme, + CefRefPtr callback) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CLIENT_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/urlrequest_ctocpp.cc b/libcef_dll/ctocpp/urlrequest_ctocpp.cc new file mode 100644 index 000000000..ac2fcca97 --- /dev/null +++ b/libcef_dll/ctocpp/urlrequest_ctocpp.cc @@ -0,0 +1,126 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/urlrequest_client_cpptoc.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/response_ctocpp.h" +#include "libcef_dll/ctocpp/urlrequest_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefURLRequest::Create(CefRefPtr request, + CefRefPtr client) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: request; type: refptr_same + DCHECK(request.get()); + if (!request.get()) + return NULL; + // Verify param: client; type: refptr_diff + DCHECK(client.get()); + if (!client.get()) + return NULL; + + // Execute + cef_urlrequest_t* _retval = cef_urlrequest_create( + CefRequestCToCpp::Unwrap(request), + CefURLRequestClientCppToC::Wrap(client)); + + // Return type: refptr_same + return CefURLRequestCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefURLRequestCToCpp::GetRequest() { + if (CEF_MEMBER_MISSING(struct_, get_request)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_request_t* _retval = struct_->get_request(struct_); + + // Return type: refptr_same + return CefRequestCToCpp::Wrap(_retval); +} + +CefRefPtr CefURLRequestCToCpp::GetClient() { + if (CEF_MEMBER_MISSING(struct_, get_client)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_urlrequest_client_t* _retval = struct_->get_client(struct_); + + // Return type: refptr_diff + return CefURLRequestClientCppToC::Unwrap(_retval); +} + +CefURLRequest::Status CefURLRequestCToCpp::GetRequestStatus() { + if (CEF_MEMBER_MISSING(struct_, get_request_status)) + return UR_UNKNOWN; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_urlrequest_status_t _retval = struct_->get_request_status(struct_); + + // Return type: simple + return _retval; +} + +CefURLRequest::ErrorCode CefURLRequestCToCpp::GetRequestError() { + if (CEF_MEMBER_MISSING(struct_, get_request_error)) + return ERR_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_errorcode_t _retval = struct_->get_request_error(struct_); + + // Return type: simple + return _retval; +} + +CefRefPtr CefURLRequestCToCpp::GetResponse() { + if (CEF_MEMBER_MISSING(struct_, get_response)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_response_t* _retval = struct_->get_response(struct_); + + // Return type: refptr_same + return CefResponseCToCpp::Wrap(_retval); +} + +void CefURLRequestCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/urlrequest_ctocpp.h b/libcef_dll/ctocpp/urlrequest_ctocpp.h new file mode 100644 index 000000000..0dcf7427c --- /dev/null +++ b/libcef_dll/ctocpp/urlrequest_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_urlrequest.h" +#include "include/capi/cef_urlrequest_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefURLRequestCToCpp + : public CefCToCpp { + public: + explicit CefURLRequestCToCpp(cef_urlrequest_t* str) + : CefCToCpp(str) {} + + // CefURLRequest methods + virtual CefRefPtr GetRequest() OVERRIDE; + virtual CefRefPtr GetClient() OVERRIDE; + virtual Status GetRequestStatus() OVERRIDE; + virtual ErrorCode GetRequestError() OVERRIDE; + virtual CefRefPtr GetResponse() OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_URLREQUEST_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8accessor_ctocpp.cc b/libcef_dll/ctocpp/v8accessor_ctocpp.cc new file mode 100644 index 000000000..fc6b824ef --- /dev/null +++ b/libcef_dll/ctocpp/v8accessor_ctocpp.cc @@ -0,0 +1,99 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8value_cpptoc.h" +#include "libcef_dll/ctocpp/v8accessor_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefV8AccessorCToCpp::Get(const CefString& name, + const CefRefPtr object, CefRefPtr& retval, + CefString& exception) { + if (CEF_MEMBER_MISSING(struct_, get)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return false; + // Verify param: object; type: refptr_diff + DCHECK(object.get()); + if (!object.get()) + return false; + + // Translate param: retval; type: refptr_diff_byref + cef_v8value_t* retvalStruct = NULL; + if (retval.get()) + retvalStruct = CefV8ValueCppToC::Wrap(retval); + cef_v8value_t* retvalOrig = retvalStruct; + + // Execute + int _retval = struct_->get(struct_, + name.GetStruct(), + CefV8ValueCppToC::Wrap(object), + &retvalStruct, + exception.GetWritableStruct()); + + // Restore param:retval; type: refptr_diff_byref + if (retvalStruct) { + if (retvalStruct != retvalOrig) { + retval = CefV8ValueCppToC::Unwrap(retvalStruct); + } + } else { + retval = NULL; + } + + // Return type: bool + return _retval?true:false; +} + +bool CefV8AccessorCToCpp::Set(const CefString& name, + const CefRefPtr object, const CefRefPtr value, + CefString& exception) { + if (CEF_MEMBER_MISSING(struct_, set)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return false; + // Verify param: object; type: refptr_diff + DCHECK(object.get()); + if (!object.get()) + return false; + // Verify param: value; type: refptr_diff + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set(struct_, + name.GetStruct(), + CefV8ValueCppToC::Wrap(object), + CefV8ValueCppToC::Wrap(value), + exception.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8accessor_ctocpp.h b/libcef_dll/ctocpp/v8accessor_ctocpp.h new file mode 100644 index 000000000..078a3f940 --- /dev/null +++ b/libcef_dll/ctocpp/v8accessor_ctocpp.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8ACCESSOR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8ACCESSOR_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefV8AccessorCToCpp + : public CefCToCpp { + public: + explicit CefV8AccessorCToCpp(cef_v8accessor_t* str) + : CefCToCpp(str) {} + + // CefV8Accessor methods + bool Get(const CefString& name, const CefRefPtr object, + CefRefPtr& retval, CefString& exception) override; + bool Set(const CefString& name, const CefRefPtr object, + const CefRefPtr value, CefString& exception) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8ACCESSOR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8context_ctocpp.cc b/libcef_dll/ctocpp/v8context_ctocpp.cc new file mode 100644 index 000000000..ca95b4004 --- /dev/null +++ b/libcef_dll/ctocpp/v8context_ctocpp.cc @@ -0,0 +1,221 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/task_runner_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" +#include "libcef_dll/ctocpp/v8exception_ctocpp.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefV8Context::GetCurrentContext() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8context_t* _retval = cef_v8context_get_current_context(); + + // Return type: refptr_same + return CefV8ContextCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Context::GetEnteredContext() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8context_t* _retval = cef_v8context_get_entered_context(); + + // Return type: refptr_same + return CefV8ContextCToCpp::Wrap(_retval); +} + +bool CefV8Context::InContext() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = cef_v8context_in_context(); + + // Return type: bool + return _retval?true:false; +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefRefPtr CefV8ContextCToCpp::GetTaskRunner() { + if (CEF_MEMBER_MISSING(struct_, get_task_runner)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_task_runner_t* _retval = struct_->get_task_runner(struct_); + + // Return type: refptr_same + return CefTaskRunnerCToCpp::Wrap(_retval); +} + +bool CefV8ContextCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefV8ContextCToCpp::GetBrowser() { + if (CEF_MEMBER_MISSING(struct_, get_browser)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_browser_t* _retval = struct_->get_browser(struct_); + + // Return type: refptr_same + return CefBrowserCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8ContextCToCpp::GetFrame() { + if (CEF_MEMBER_MISSING(struct_, get_frame)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_frame_t* _retval = struct_->get_frame(struct_); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8ContextCToCpp::GetGlobal() { + if (CEF_MEMBER_MISSING(struct_, get_global)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = struct_->get_global(struct_); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +bool CefV8ContextCToCpp::Enter() { + if (CEF_MEMBER_MISSING(struct_, enter)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->enter(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ContextCToCpp::Exit() { + if (CEF_MEMBER_MISSING(struct_, exit)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->exit(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ContextCToCpp::IsSame(CefRefPtr that) { + if (CEF_MEMBER_MISSING(struct_, is_same)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: that; type: refptr_same + DCHECK(that.get()); + if (!that.get()) + return false; + + // Execute + int _retval = struct_->is_same(struct_, + CefV8ContextCToCpp::Unwrap(that)); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ContextCToCpp::Eval(const CefString& code, + CefRefPtr& retval, CefRefPtr& exception) { + if (CEF_MEMBER_MISSING(struct_, eval)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: code; type: string_byref_const + DCHECK(!code.empty()); + if (code.empty()) + return false; + + // Translate param: retval; type: refptr_same_byref + cef_v8value_t* retvalStruct = NULL; + if (retval.get()) + retvalStruct = CefV8ValueCToCpp::Unwrap(retval); + cef_v8value_t* retvalOrig = retvalStruct; + // Translate param: exception; type: refptr_same_byref + cef_v8exception_t* exceptionStruct = NULL; + if (exception.get()) + exceptionStruct = CefV8ExceptionCToCpp::Unwrap(exception); + cef_v8exception_t* exceptionOrig = exceptionStruct; + + // Execute + int _retval = struct_->eval(struct_, + code.GetStruct(), + &retvalStruct, + &exceptionStruct); + + // Restore param:retval; type: refptr_same_byref + if (retvalStruct) { + if (retvalStruct != retvalOrig) { + retval = CefV8ValueCToCpp::Wrap(retvalStruct); + } + } else { + retval = NULL; + } + // Restore param:exception; type: refptr_same_byref + if (exceptionStruct) { + if (exceptionStruct != exceptionOrig) { + exception = CefV8ExceptionCToCpp::Wrap(exceptionStruct); + } + } else { + exception = NULL; + } + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8context_ctocpp.h b/libcef_dll/ctocpp/v8context_ctocpp.h new file mode 100644 index 000000000..aef9d2993 --- /dev/null +++ b/libcef_dll/ctocpp/v8context_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8CONTEXT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8CONTEXT_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefV8ContextCToCpp + : public CefCToCpp { + public: + explicit CefV8ContextCToCpp(cef_v8context_t* str) + : CefCToCpp(str) {} + + // CefV8Context methods + virtual CefRefPtr GetTaskRunner() OVERRIDE; + virtual bool IsValid() OVERRIDE; + virtual CefRefPtr GetBrowser() OVERRIDE; + virtual CefRefPtr GetFrame() OVERRIDE; + virtual CefRefPtr GetGlobal() OVERRIDE; + virtual bool Enter() OVERRIDE; + virtual bool Exit() OVERRIDE; + virtual bool IsSame(CefRefPtr that) OVERRIDE; + virtual bool Eval(const CefString& code, CefRefPtr& retval, + CefRefPtr& exception) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8CONTEXT_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8exception_ctocpp.cc b/libcef_dll/ctocpp/v8exception_ctocpp.cc new file mode 100644 index 000000000..707035105 --- /dev/null +++ b/libcef_dll/ctocpp/v8exception_ctocpp.cc @@ -0,0 +1,133 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/v8exception_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefString CefV8ExceptionCToCpp::GetMessage() { + if (CEF_MEMBER_MISSING(struct_, get_message)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_message(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefV8ExceptionCToCpp::GetSourceLine() { + if (CEF_MEMBER_MISSING(struct_, get_source_line)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_source_line(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefV8ExceptionCToCpp::GetScriptResourceName() { + if (CEF_MEMBER_MISSING(struct_, get_script_resource_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_script_resource_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int CefV8ExceptionCToCpp::GetLineNumber() { + if (CEF_MEMBER_MISSING(struct_, get_line_number)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_line_number(struct_); + + // Return type: simple + return _retval; +} + +int CefV8ExceptionCToCpp::GetStartPosition() { + if (CEF_MEMBER_MISSING(struct_, get_start_position)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_start_position(struct_); + + // Return type: simple + return _retval; +} + +int CefV8ExceptionCToCpp::GetEndPosition() { + if (CEF_MEMBER_MISSING(struct_, get_end_position)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_end_position(struct_); + + // Return type: simple + return _retval; +} + +int CefV8ExceptionCToCpp::GetStartColumn() { + if (CEF_MEMBER_MISSING(struct_, get_start_column)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_start_column(struct_); + + // Return type: simple + return _retval; +} + +int CefV8ExceptionCToCpp::GetEndColumn() { + if (CEF_MEMBER_MISSING(struct_, get_end_column)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_end_column(struct_); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8exception_ctocpp.h b/libcef_dll/ctocpp/v8exception_ctocpp.h new file mode 100644 index 000000000..07610ce63 --- /dev/null +++ b/libcef_dll/ctocpp/v8exception_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8EXCEPTION_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8EXCEPTION_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefV8ExceptionCToCpp + : public CefCToCpp { + public: + explicit CefV8ExceptionCToCpp(cef_v8exception_t* str) + : CefCToCpp( + str) {} + + // CefV8Exception methods + virtual CefString GetMessage() OVERRIDE; + virtual CefString GetSourceLine() OVERRIDE; + virtual CefString GetScriptResourceName() OVERRIDE; + virtual int GetLineNumber() OVERRIDE; + virtual int GetStartPosition() OVERRIDE; + virtual int GetEndPosition() OVERRIDE; + virtual int GetStartColumn() OVERRIDE; + virtual int GetEndColumn() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8EXCEPTION_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8handler_ctocpp.cc b/libcef_dll/ctocpp/v8handler_ctocpp.cc new file mode 100644 index 000000000..370890f54 --- /dev/null +++ b/libcef_dll/ctocpp/v8handler_ctocpp.cc @@ -0,0 +1,84 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/v8value_cpptoc.h" +#include "libcef_dll/ctocpp/v8handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefV8HandlerCToCpp::Execute(const CefString& name, + CefRefPtr object, const CefV8ValueList& arguments, + CefRefPtr& retval, CefString& exception) { + if (CEF_MEMBER_MISSING(struct_, execute)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return false; + // Verify param: object; type: refptr_diff + DCHECK(object.get()); + if (!object.get()) + return false; + + // Translate param: arguments; type: refptr_vec_diff_byref_const + const size_t argumentsCount = arguments.size(); + cef_v8value_t** argumentsList = NULL; + if (argumentsCount > 0) { + argumentsList = new cef_v8value_t*[argumentsCount]; + DCHECK(argumentsList); + if (argumentsList) { + for (size_t i = 0; i < argumentsCount; ++i) { + argumentsList[i] = CefV8ValueCppToC::Wrap(arguments[i]); + } + } + } + // Translate param: retval; type: refptr_diff_byref + cef_v8value_t* retvalStruct = NULL; + if (retval.get()) + retvalStruct = CefV8ValueCppToC::Wrap(retval); + cef_v8value_t* retvalOrig = retvalStruct; + + // Execute + int _retval = struct_->execute(struct_, + name.GetStruct(), + CefV8ValueCppToC::Wrap(object), + argumentsCount, + argumentsList, + &retvalStruct, + exception.GetWritableStruct()); + + // Restore param:arguments; type: refptr_vec_diff_byref_const + if (argumentsList) + delete [] argumentsList; + // Restore param:retval; type: refptr_diff_byref + if (retvalStruct) { + if (retvalStruct != retvalOrig) { + retval = CefV8ValueCppToC::Unwrap(retvalStruct); + } + } else { + retval = NULL; + } + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8handler_ctocpp.h b/libcef_dll/ctocpp/v8handler_ctocpp.h new file mode 100644 index 000000000..8df864f36 --- /dev/null +++ b/libcef_dll/ctocpp/v8handler_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefV8HandlerCToCpp + : public CefCToCpp { + public: + explicit CefV8HandlerCToCpp(cef_v8handler_t* str) + : CefCToCpp(str) {} + + // CefV8Handler methods + bool Execute(const CefString& name, CefRefPtr object, + const CefV8ValueList& arguments, CefRefPtr& retval, + CefString& exception) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8stack_frame_ctocpp.cc b/libcef_dll/ctocpp/v8stack_frame_ctocpp.cc new file mode 100644 index 000000000..3446ac24f --- /dev/null +++ b/libcef_dll/ctocpp/v8stack_frame_ctocpp.cc @@ -0,0 +1,134 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/v8stack_frame_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefV8StackFrameCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefV8StackFrameCToCpp::GetScriptName() { + if (CEF_MEMBER_MISSING(struct_, get_script_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_script_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefV8StackFrameCToCpp::GetScriptNameOrSourceURL() { + if (CEF_MEMBER_MISSING(struct_, get_script_name_or_source_url)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_script_name_or_source_url( + struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefV8StackFrameCToCpp::GetFunctionName() { + if (CEF_MEMBER_MISSING(struct_, get_function_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_function_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int CefV8StackFrameCToCpp::GetLineNumber() { + if (CEF_MEMBER_MISSING(struct_, get_line_number)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_line_number(struct_); + + // Return type: simple + return _retval; +} + +int CefV8StackFrameCToCpp::GetColumn() { + if (CEF_MEMBER_MISSING(struct_, get_column)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_column(struct_); + + // Return type: simple + return _retval; +} + +bool CefV8StackFrameCToCpp::IsEval() { + if (CEF_MEMBER_MISSING(struct_, is_eval)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_eval(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8StackFrameCToCpp::IsConstructor() { + if (CEF_MEMBER_MISSING(struct_, is_constructor)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_constructor(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8stack_frame_ctocpp.h b/libcef_dll/ctocpp/v8stack_frame_ctocpp.h new file mode 100644 index 000000000..62bbf6275 --- /dev/null +++ b/libcef_dll/ctocpp/v8stack_frame_ctocpp.h @@ -0,0 +1,48 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8STACK_FRAME_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8STACK_FRAME_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefV8StackFrameCToCpp + : public CefCToCpp { + public: + explicit CefV8StackFrameCToCpp(cef_v8stack_frame_t* str) + : CefCToCpp( + str) {} + + // CefV8StackFrame methods + virtual bool IsValid() OVERRIDE; + virtual CefString GetScriptName() OVERRIDE; + virtual CefString GetScriptNameOrSourceURL() OVERRIDE; + virtual CefString GetFunctionName() OVERRIDE; + virtual int GetLineNumber() OVERRIDE; + virtual int GetColumn() OVERRIDE; + virtual bool IsEval() OVERRIDE; + virtual bool IsConstructor() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8STACK_FRAME_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8stack_trace_ctocpp.cc b/libcef_dll/ctocpp/v8stack_trace_ctocpp.cc new file mode 100644 index 000000000..129497430 --- /dev/null +++ b/libcef_dll/ctocpp/v8stack_trace_ctocpp.cc @@ -0,0 +1,78 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/v8stack_frame_ctocpp.h" +#include "libcef_dll/ctocpp/v8stack_trace_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefV8StackTrace::GetCurrent(int frame_limit) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8stack_trace_t* _retval = cef_v8stack_trace_get_current( + frame_limit); + + // Return type: refptr_same + return CefV8StackTraceCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefV8StackTraceCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +int CefV8StackTraceCToCpp::GetFrameCount() { + if (CEF_MEMBER_MISSING(struct_, get_frame_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_frame_count(struct_); + + // Return type: simple + return _retval; +} + +CefRefPtr CefV8StackTraceCToCpp::GetFrame(int index) { + if (CEF_MEMBER_MISSING(struct_, get_frame)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8stack_frame_t* _retval = struct_->get_frame(struct_, + index); + + // Return type: refptr_same + return CefV8StackFrameCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8stack_trace_ctocpp.h b/libcef_dll/ctocpp/v8stack_trace_ctocpp.h new file mode 100644 index 000000000..ff7b02a0a --- /dev/null +++ b/libcef_dll/ctocpp/v8stack_trace_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8STACK_TRACE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8STACK_TRACE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefV8StackTraceCToCpp + : public CefCToCpp { + public: + explicit CefV8StackTraceCToCpp(cef_v8stack_trace_t* str) + : CefCToCpp( + str) {} + + // CefV8StackTrace methods + virtual bool IsValid() OVERRIDE; + virtual int GetFrameCount() OVERRIDE; + virtual CefRefPtr GetFrame(int index) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8STACK_TRACE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/v8value_ctocpp.cc b/libcef_dll/ctocpp/v8value_ctocpp.cc new file mode 100644 index 000000000..848a481ff --- /dev/null +++ b/libcef_dll/ctocpp/v8value_ctocpp.cc @@ -0,0 +1,874 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/base_cpptoc.h" +#include "libcef_dll/cpptoc/v8accessor_cpptoc.h" +#include "libcef_dll/cpptoc/v8handler_cpptoc.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" +#include "libcef_dll/ctocpp/v8exception_ctocpp.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefV8Value::CreateUndefined() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_undefined(); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateNull() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_null(); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateBool(bool value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_bool( + value); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateInt(int32 value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_int( + value); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateUInt(uint32 value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_uint( + value); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateDouble(double value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_double( + value); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateDate(const CefTime& date) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_date( + &date); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateString(const CefString& value) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: value + + // Execute + cef_v8value_t* _retval = cef_v8value_create_string( + value.GetStruct()); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateObject( + CefRefPtr accessor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: accessor + + // Execute + cef_v8value_t* _retval = cef_v8value_create_object( + CefV8AccessorCppToC::Wrap(accessor)); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateArray(int length) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8value_t* _retval = cef_v8value_create_array( + length); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8Value::CreateFunction(const CefString& name, + CefRefPtr handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: name; type: string_byref_const + DCHECK(!name.empty()); + if (name.empty()) + return NULL; + // Verify param: handler; type: refptr_diff + DCHECK(handler.get()); + if (!handler.get()) + return NULL; + + // Execute + cef_v8value_t* _retval = cef_v8value_create_function( + name.GetStruct(), + CefV8HandlerCppToC::Wrap(handler)); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefV8ValueCToCpp::IsValid() { + if (CEF_MEMBER_MISSING(struct_, is_valid)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_valid(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsUndefined() { + if (CEF_MEMBER_MISSING(struct_, is_undefined)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_undefined(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsNull() { + if (CEF_MEMBER_MISSING(struct_, is_null)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_null(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsBool() { + if (CEF_MEMBER_MISSING(struct_, is_bool)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_bool(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsInt() { + if (CEF_MEMBER_MISSING(struct_, is_int)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_int(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsUInt() { + if (CEF_MEMBER_MISSING(struct_, is_uint)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_uint(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsDouble() { + if (CEF_MEMBER_MISSING(struct_, is_double)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_double(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsDate() { + if (CEF_MEMBER_MISSING(struct_, is_date)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_date(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsString() { + if (CEF_MEMBER_MISSING(struct_, is_string)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_string(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsObject() { + if (CEF_MEMBER_MISSING(struct_, is_object)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_object(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsArray() { + if (CEF_MEMBER_MISSING(struct_, is_array)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_array(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsFunction() { + if (CEF_MEMBER_MISSING(struct_, is_function)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_function(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::IsSame(CefRefPtr that) { + if (CEF_MEMBER_MISSING(struct_, is_same)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: that; type: refptr_same + DCHECK(that.get()); + if (!that.get()) + return false; + + // Execute + int _retval = struct_->is_same(struct_, + CefV8ValueCToCpp::Unwrap(that)); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::GetBoolValue() { + if (CEF_MEMBER_MISSING(struct_, get_bool_value)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_bool_value(struct_); + + // Return type: bool + return _retval?true:false; +} + +int32 CefV8ValueCToCpp::GetIntValue() { + if (CEF_MEMBER_MISSING(struct_, get_int_value)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int32 _retval = struct_->get_int_value(struct_); + + // Return type: simple + return _retval; +} + +uint32 CefV8ValueCToCpp::GetUIntValue() { + if (CEF_MEMBER_MISSING(struct_, get_uint_value)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + uint32 _retval = struct_->get_uint_value(struct_); + + // Return type: simple + return _retval; +} + +double CefV8ValueCToCpp::GetDoubleValue() { + if (CEF_MEMBER_MISSING(struct_, get_double_value)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + double _retval = struct_->get_double_value(struct_); + + // Return type: simple + return _retval; +} + +CefTime CefV8ValueCToCpp::GetDateValue() { + if (CEF_MEMBER_MISSING(struct_, get_date_value)) + return CefTime(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_time_t _retval = struct_->get_date_value(struct_); + + // Return type: simple + return _retval; +} + +CefString CefV8ValueCToCpp::GetStringValue() { + if (CEF_MEMBER_MISSING(struct_, get_string_value)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_string_value(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefV8ValueCToCpp::IsUserCreated() { + if (CEF_MEMBER_MISSING(struct_, is_user_created)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_user_created(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::HasException() { + if (CEF_MEMBER_MISSING(struct_, has_exception)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_exception(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefV8ValueCToCpp::GetException() { + if (CEF_MEMBER_MISSING(struct_, get_exception)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8exception_t* _retval = struct_->get_exception(struct_); + + // Return type: refptr_same + return CefV8ExceptionCToCpp::Wrap(_retval); +} + +bool CefV8ValueCToCpp::ClearException() { + if (CEF_MEMBER_MISSING(struct_, clear_exception)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->clear_exception(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::WillRethrowExceptions() { + if (CEF_MEMBER_MISSING(struct_, will_rethrow_exceptions)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->will_rethrow_exceptions(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::SetRethrowExceptions(bool rethrow) { + if (CEF_MEMBER_MISSING(struct_, set_rethrow_exceptions)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->set_rethrow_exceptions(struct_, + rethrow); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::HasValue(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, has_value_bykey)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: key + + // Execute + int _retval = struct_->has_value_bykey(struct_, + key.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::HasValue(int index) { + if (CEF_MEMBER_MISSING(struct_, has_value_byindex)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->has_value_byindex(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::DeleteValue(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, delete_value_bykey)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: key + + // Execute + int _retval = struct_->delete_value_bykey(struct_, + key.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::DeleteValue(int index) { + if (CEF_MEMBER_MISSING(struct_, delete_value_byindex)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->delete_value_byindex(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefV8ValueCToCpp::GetValue(const CefString& key) { + if (CEF_MEMBER_MISSING(struct_, get_value_bykey)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: key + + // Execute + cef_v8value_t* _retval = struct_->get_value_bykey(struct_, + key.GetStruct()); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8ValueCToCpp::GetValue(int index) { + if (CEF_MEMBER_MISSING(struct_, get_value_byindex)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return NULL; + + // Execute + cef_v8value_t* _retval = struct_->get_value_byindex(struct_, + index); + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +bool CefV8ValueCToCpp::SetValue(const CefString& key, + CefRefPtr value, PropertyAttribute attribute) { + if (CEF_MEMBER_MISSING(struct_, set_value_bykey)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + // Unverified params: key + + // Execute + int _retval = struct_->set_value_bykey(struct_, + key.GetStruct(), + CefV8ValueCToCpp::Unwrap(value), + attribute); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::SetValue(int index, CefRefPtr value) { + if (CEF_MEMBER_MISSING(struct_, set_value_byindex)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + // Verify param: value; type: refptr_same + DCHECK(value.get()); + if (!value.get()) + return false; + + // Execute + int _retval = struct_->set_value_byindex(struct_, + index, + CefV8ValueCToCpp::Unwrap(value)); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::SetValue(const CefString& key, AccessControl settings, + PropertyAttribute attribute) { + if (CEF_MEMBER_MISSING(struct_, set_value_byaccessor)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: key + + // Execute + int _retval = struct_->set_value_byaccessor(struct_, + key.GetStruct(), + settings, + attribute); + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::GetKeys(std::vector& keys) { + if (CEF_MEMBER_MISSING(struct_, get_keys)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: keys; type: string_vec_byref + cef_string_list_t keysList = cef_string_list_alloc(); + DCHECK(keysList); + if (keysList) + transfer_string_list_contents(keys, keysList); + + // Execute + int _retval = struct_->get_keys(struct_, + keysList); + + // Restore param:keys; type: string_vec_byref + if (keysList) { + keys.clear(); + transfer_string_list_contents(keysList, keys); + cef_string_list_free(keysList); + } + + // Return type: bool + return _retval?true:false; +} + +bool CefV8ValueCToCpp::SetUserData(CefRefPtr user_data) { + if (CEF_MEMBER_MISSING(struct_, set_user_data)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: user_data + + // Execute + int _retval = struct_->set_user_data(struct_, + CefBaseCppToC::Wrap(user_data)); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefV8ValueCToCpp::GetUserData() { + if (CEF_MEMBER_MISSING(struct_, get_user_data)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_base_t* _retval = struct_->get_user_data(struct_); + + // Return type: refptr_diff + return CefBaseCppToC::Unwrap(_retval); +} + +int CefV8ValueCToCpp::GetExternallyAllocatedMemory() { + if (CEF_MEMBER_MISSING(struct_, get_externally_allocated_memory)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_externally_allocated_memory(struct_); + + // Return type: simple + return _retval; +} + +int CefV8ValueCToCpp::AdjustExternallyAllocatedMemory(int change_in_bytes) { + if (CEF_MEMBER_MISSING(struct_, adjust_externally_allocated_memory)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->adjust_externally_allocated_memory(struct_, + change_in_bytes); + + // Return type: simple + return _retval; +} + +int CefV8ValueCToCpp::GetArrayLength() { + if (CEF_MEMBER_MISSING(struct_, get_array_length)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_array_length(struct_); + + // Return type: simple + return _retval; +} + +CefString CefV8ValueCToCpp::GetFunctionName() { + if (CEF_MEMBER_MISSING(struct_, get_function_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_function_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefRefPtr CefV8ValueCToCpp::GetFunctionHandler() { + if (CEF_MEMBER_MISSING(struct_, get_function_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8handler_t* _retval = struct_->get_function_handler(struct_); + + // Return type: refptr_diff + return CefV8HandlerCppToC::Unwrap(_retval); +} + +CefRefPtr CefV8ValueCToCpp::ExecuteFunction( + CefRefPtr object, const CefV8ValueList& arguments) { + if (CEF_MEMBER_MISSING(struct_, execute_function)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: object + + // Translate param: arguments; type: refptr_vec_same_byref_const + const size_t argumentsCount = arguments.size(); + cef_v8value_t** argumentsList = NULL; + if (argumentsCount > 0) { + argumentsList = new cef_v8value_t*[argumentsCount]; + DCHECK(argumentsList); + if (argumentsList) { + for (size_t i = 0; i < argumentsCount; ++i) { + argumentsList[i] = CefV8ValueCToCpp::Unwrap(arguments[i]); + } + } + } + + // Execute + cef_v8value_t* _retval = struct_->execute_function(struct_, + CefV8ValueCToCpp::Unwrap(object), + argumentsCount, + argumentsList); + + // Restore param:arguments; type: refptr_vec_same_byref_const + if (argumentsList) + delete [] argumentsList; + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + +CefRefPtr CefV8ValueCToCpp::ExecuteFunctionWithContext( + CefRefPtr context, CefRefPtr object, + const CefV8ValueList& arguments) { + if (CEF_MEMBER_MISSING(struct_, execute_function_with_context)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: context; type: refptr_same + DCHECK(context.get()); + if (!context.get()) + return NULL; + // Unverified params: object + + // Translate param: arguments; type: refptr_vec_same_byref_const + const size_t argumentsCount = arguments.size(); + cef_v8value_t** argumentsList = NULL; + if (argumentsCount > 0) { + argumentsList = new cef_v8value_t*[argumentsCount]; + DCHECK(argumentsList); + if (argumentsList) { + for (size_t i = 0; i < argumentsCount; ++i) { + argumentsList[i] = CefV8ValueCToCpp::Unwrap(arguments[i]); + } + } + } + + // Execute + cef_v8value_t* _retval = struct_->execute_function_with_context(struct_, + CefV8ContextCToCpp::Unwrap(context), + CefV8ValueCToCpp::Unwrap(object), + argumentsCount, + argumentsList); + + // Restore param:arguments; type: refptr_vec_same_byref_const + if (argumentsList) + delete [] argumentsList; + + // Return type: refptr_same + return CefV8ValueCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/v8value_ctocpp.h b/libcef_dll/ctocpp/v8value_ctocpp.h new file mode 100644 index 000000000..9101bf9e0 --- /dev/null +++ b/libcef_dll/ctocpp/v8value_ctocpp.h @@ -0,0 +1,88 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_V8VALUE_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8VALUE_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefV8ValueCToCpp + : public CefCToCpp { + public: + explicit CefV8ValueCToCpp(cef_v8value_t* str) + : CefCToCpp(str) {} + + // CefV8Value methods + virtual bool IsValid() OVERRIDE; + virtual bool IsUndefined() OVERRIDE; + virtual bool IsNull() OVERRIDE; + virtual bool IsBool() OVERRIDE; + virtual bool IsInt() OVERRIDE; + virtual bool IsUInt() OVERRIDE; + virtual bool IsDouble() OVERRIDE; + virtual bool IsDate() OVERRIDE; + virtual bool IsString() OVERRIDE; + virtual bool IsObject() OVERRIDE; + virtual bool IsArray() OVERRIDE; + virtual bool IsFunction() OVERRIDE; + virtual bool IsSame(CefRefPtr that) OVERRIDE; + virtual bool GetBoolValue() OVERRIDE; + virtual int32 GetIntValue() OVERRIDE; + virtual uint32 GetUIntValue() OVERRIDE; + virtual double GetDoubleValue() OVERRIDE; + virtual CefTime GetDateValue() OVERRIDE; + virtual CefString GetStringValue() OVERRIDE; + virtual bool IsUserCreated() OVERRIDE; + virtual bool HasException() OVERRIDE; + virtual CefRefPtr GetException() OVERRIDE; + virtual bool ClearException() OVERRIDE; + virtual bool WillRethrowExceptions() OVERRIDE; + virtual bool SetRethrowExceptions(bool rethrow) OVERRIDE; + virtual bool HasValue(const CefString& key) OVERRIDE; + virtual bool HasValue(int index) OVERRIDE; + virtual bool DeleteValue(const CefString& key) OVERRIDE; + virtual bool DeleteValue(int index) OVERRIDE; + virtual CefRefPtr GetValue(const CefString& key) OVERRIDE; + virtual CefRefPtr GetValue(int index) OVERRIDE; + virtual bool SetValue(const CefString& key, CefRefPtr value, + PropertyAttribute attribute) OVERRIDE; + virtual bool SetValue(int index, CefRefPtr value) OVERRIDE; + virtual bool SetValue(const CefString& key, AccessControl settings, + PropertyAttribute attribute) OVERRIDE; + virtual bool GetKeys(std::vector& keys) OVERRIDE; + virtual bool SetUserData(CefRefPtr user_data) OVERRIDE; + virtual CefRefPtr GetUserData() OVERRIDE; + virtual int GetExternallyAllocatedMemory() OVERRIDE; + virtual int AdjustExternallyAllocatedMemory(int change_in_bytes) OVERRIDE; + virtual int GetArrayLength() OVERRIDE; + virtual CefString GetFunctionName() OVERRIDE; + virtual CefRefPtr GetFunctionHandler() OVERRIDE; + virtual CefRefPtr ExecuteFunction(CefRefPtr object, + const CefV8ValueList& arguments) OVERRIDE; + virtual CefRefPtr ExecuteFunctionWithContext( + CefRefPtr context, CefRefPtr object, + const CefV8ValueList& arguments) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8VALUE_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/web_plugin_info_ctocpp.cc b/libcef_dll/ctocpp/web_plugin_info_ctocpp.cc new file mode 100644 index 000000000..d693125d3 --- /dev/null +++ b/libcef_dll/ctocpp/web_plugin_info_ctocpp.cc @@ -0,0 +1,83 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/web_plugin_info_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefString CefWebPluginInfoCToCpp::GetName() { + if (CEF_MEMBER_MISSING(struct_, get_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefWebPluginInfoCToCpp::GetPath() { + if (CEF_MEMBER_MISSING(struct_, get_path)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_path(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefWebPluginInfoCToCpp::GetVersion() { + if (CEF_MEMBER_MISSING(struct_, get_version)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_version(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefWebPluginInfoCToCpp::GetDescription() { + if (CEF_MEMBER_MISSING(struct_, get_description)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_description(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/web_plugin_info_ctocpp.h b/libcef_dll/ctocpp/web_plugin_info_ctocpp.h new file mode 100644 index 000000000..1d12cfb6f --- /dev/null +++ b/libcef_dll/ctocpp/web_plugin_info_ctocpp.h @@ -0,0 +1,44 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_INFO_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_INFO_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefWebPluginInfoCToCpp + : public CefCToCpp { + public: + explicit CefWebPluginInfoCToCpp(cef_web_plugin_info_t* str) + : CefCToCpp(str) {} + + // CefWebPluginInfo methods + virtual CefString GetName() OVERRIDE; + virtual CefString GetPath() OVERRIDE; + virtual CefString GetVersion() OVERRIDE; + virtual CefString GetDescription() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_INFO_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.cc b/libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.cc new file mode 100644 index 000000000..011691d92 --- /dev/null +++ b/libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/cpptoc/web_plugin_info_cpptoc.h" +#include "libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefWebPluginInfoVisitorCToCpp::Visit(CefRefPtr info, + int count, int total) { + if (CEF_MEMBER_MISSING(struct_, visit)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: info; type: refptr_diff + DCHECK(info.get()); + if (!info.get()) + return false; + + // Execute + int _retval = struct_->visit(struct_, + CefWebPluginInfoCppToC::Wrap(info), + count, + total); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.h b/libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.h new file mode 100644 index 000000000..f96165726 --- /dev/null +++ b/libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.h @@ -0,0 +1,41 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_INFO_VISITOR_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_INFO_VISITOR_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefWebPluginInfoVisitorCToCpp + : public CefCToCpp { + public: + explicit CefWebPluginInfoVisitorCToCpp(cef_web_plugin_info_visitor_t* str) + : CefCToCpp(str) {} + + // CefWebPluginInfoVisitor methods + bool Visit(CefRefPtr info, int count, int total) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_INFO_VISITOR_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.cc b/libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.cc new file mode 100644 index 000000000..179141fae --- /dev/null +++ b/libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.cc @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefWebPluginUnstableCallbackCToCpp::IsUnstable(const CefString& path, + bool unstable) { + if (CEF_MEMBER_MISSING(struct_, is_unstable)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + + // Execute + struct_->is_unstable(struct_, + path.GetStruct(), + unstable); +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.h b/libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.h new file mode 100644 index 000000000..256e28dcd --- /dev/null +++ b/libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.h @@ -0,0 +1,43 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_UNSTABLE_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_UNSTABLE_CALLBACK_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefWebPluginUnstableCallbackCToCpp + : public CefCToCpp { + public: + explicit CefWebPluginUnstableCallbackCToCpp( + cef_web_plugin_unstable_callback_t* str) + : CefCToCpp( + str) {} + + // CefWebPluginUnstableCallback methods + void IsUnstable(const CefString& path, bool unstable) override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WEB_PLUGIN_UNSTABLE_CALLBACK_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/write_handler_ctocpp.cc b/libcef_dll/ctocpp/write_handler_ctocpp.cc new file mode 100644 index 000000000..074c7b885 --- /dev/null +++ b/libcef_dll/ctocpp/write_handler_ctocpp.cc @@ -0,0 +1,98 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/write_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +size_t CefWriteHandlerCToCpp::Write(const void* ptr, size_t size, size_t n) { + if (CEF_MEMBER_MISSING(struct_, write)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: ptr; type: simple_byaddr + DCHECK(ptr); + if (!ptr) + return 0; + + // Execute + size_t _retval = struct_->write(struct_, + ptr, + size, + n); + + // Return type: simple + return _retval; +} + +int CefWriteHandlerCToCpp::Seek(int64 offset, int whence) { + if (CEF_MEMBER_MISSING(struct_, seek)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->seek(struct_, + offset, + whence); + + // Return type: simple + return _retval; +} + +int64 CefWriteHandlerCToCpp::Tell() { + if (CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->tell(struct_); + + // Return type: simple + return _retval; +} + +int CefWriteHandlerCToCpp::Flush() { + if (CEF_MEMBER_MISSING(struct_, flush)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->flush(struct_); + + // Return type: simple + return _retval; +} + +bool CefWriteHandlerCToCpp::MayBlock() { + if (CEF_MEMBER_MISSING(struct_, may_block)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->may_block(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/write_handler_ctocpp.h b/libcef_dll/ctocpp/write_handler_ctocpp.h new file mode 100644 index 000000000..84d35bfe3 --- /dev/null +++ b/libcef_dll/ctocpp/write_handler_ctocpp.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_WRITE_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_WRITE_HANDLER_CTOCPP_H_ +#pragma once + +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED + +#include "include/cef_stream.h" +#include "include/capi/cef_stream_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed DLL-side only. +class CefWriteHandlerCToCpp + : public CefCToCpp { + public: + explicit CefWriteHandlerCToCpp(cef_write_handler_t* str) + : CefCToCpp( + str) {} + + // CefWriteHandler methods + size_t Write(const void* ptr, size_t size, size_t n) override; + int Seek(int64 offset, int whence) override; + int64 Tell() override; + int Flush() override; + bool MayBlock() override; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WRITE_HANDLER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/xml_reader_ctocpp.cc b/libcef_dll/ctocpp/xml_reader_ctocpp.cc new file mode 100644 index 000000000..248775da3 --- /dev/null +++ b/libcef_dll/ctocpp/xml_reader_ctocpp.cc @@ -0,0 +1,501 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/xml_reader_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefXmlReader::Create(CefRefPtr stream, + EncodingType encodingType, const CefString& URI) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: stream; type: refptr_same + DCHECK(stream.get()); + if (!stream.get()) + return NULL; + // Verify param: URI; type: string_byref_const + DCHECK(!URI.empty()); + if (URI.empty()) + return NULL; + + // Execute + cef_xml_reader_t* _retval = cef_xml_reader_create( + CefStreamReaderCToCpp::Unwrap(stream), + encodingType, + URI.GetStruct()); + + // Return type: refptr_same + return CefXmlReaderCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefXmlReaderCToCpp::MoveToNextNode() { + if (CEF_MEMBER_MISSING(struct_, move_to_next_node)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_next_node(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::Close() { + if (CEF_MEMBER_MISSING(struct_, close)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->close(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::HasError() { + if (CEF_MEMBER_MISSING(struct_, has_error)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_error(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefXmlReaderCToCpp::GetError() { + if (CEF_MEMBER_MISSING(struct_, get_error)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_error(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefXmlReader::NodeType CefXmlReaderCToCpp::GetType() { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return XML_NODE_UNSUPPORTED; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_xml_node_type_t _retval = struct_->get_type(struct_); + + // Return type: simple + return _retval; +} + +int CefXmlReaderCToCpp::GetDepth() { + if (CEF_MEMBER_MISSING(struct_, get_depth)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_depth(struct_); + + // Return type: simple + return _retval; +} + +CefString CefXmlReaderCToCpp::GetLocalName() { + if (CEF_MEMBER_MISSING(struct_, get_local_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_local_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetPrefix() { + if (CEF_MEMBER_MISSING(struct_, get_prefix)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_prefix(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetQualifiedName() { + if (CEF_MEMBER_MISSING(struct_, get_qualified_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_qualified_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetNamespaceURI() { + if (CEF_MEMBER_MISSING(struct_, get_namespace_uri)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_namespace_uri(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetBaseURI() { + if (CEF_MEMBER_MISSING(struct_, get_base_uri)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_base_uri(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetXmlLang() { + if (CEF_MEMBER_MISSING(struct_, get_xml_lang)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_xml_lang(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefXmlReaderCToCpp::IsEmptyElement() { + if (CEF_MEMBER_MISSING(struct_, is_empty_element)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_empty_element(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::HasValue() { + if (CEF_MEMBER_MISSING(struct_, has_value)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_value(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefXmlReaderCToCpp::GetValue() { + if (CEF_MEMBER_MISSING(struct_, get_value)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_value(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +bool CefXmlReaderCToCpp::HasAttributes() { + if (CEF_MEMBER_MISSING(struct_, has_attributes)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->has_attributes(struct_); + + // Return type: bool + return _retval?true:false; +} + +size_t CefXmlReaderCToCpp::GetAttributeCount() { + if (CEF_MEMBER_MISSING(struct_, get_attribute_count)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = struct_->get_attribute_count(struct_); + + // Return type: simple + return _retval; +} + +CefString CefXmlReaderCToCpp::GetAttribute(int index) { + if (CEF_MEMBER_MISSING(struct_, get_attribute_byindex)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_attribute_byindex(struct_, + index); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetAttribute(const CefString& qualifiedName) { + if (CEF_MEMBER_MISSING(struct_, get_attribute_byqname)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: qualifiedName; type: string_byref_const + DCHECK(!qualifiedName.empty()); + if (qualifiedName.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_attribute_byqname(struct_, + qualifiedName.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetAttribute(const CefString& localName, + const CefString& namespaceURI) { + if (CEF_MEMBER_MISSING(struct_, get_attribute_bylname)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: localName; type: string_byref_const + DCHECK(!localName.empty()); + if (localName.empty()) + return CefString(); + // Verify param: namespaceURI; type: string_byref_const + DCHECK(!namespaceURI.empty()); + if (namespaceURI.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = struct_->get_attribute_bylname(struct_, + localName.GetStruct(), + namespaceURI.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetInnerXml() { + if (CEF_MEMBER_MISSING(struct_, get_inner_xml)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_inner_xml(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefXmlReaderCToCpp::GetOuterXml() { + if (CEF_MEMBER_MISSING(struct_, get_outer_xml)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_outer_xml(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int CefXmlReaderCToCpp::GetLineNumber() { + if (CEF_MEMBER_MISSING(struct_, get_line_number)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_line_number(struct_); + + // Return type: simple + return _retval; +} + +bool CefXmlReaderCToCpp::MoveToAttribute(int index) { + if (CEF_MEMBER_MISSING(struct_, move_to_attribute_byindex)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: index; type: simple_byval + DCHECK_GE(index, 0); + if (index < 0) + return false; + + // Execute + int _retval = struct_->move_to_attribute_byindex(struct_, + index); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::MoveToAttribute(const CefString& qualifiedName) { + if (CEF_MEMBER_MISSING(struct_, move_to_attribute_byqname)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: qualifiedName; type: string_byref_const + DCHECK(!qualifiedName.empty()); + if (qualifiedName.empty()) + return false; + + // Execute + int _retval = struct_->move_to_attribute_byqname(struct_, + qualifiedName.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::MoveToAttribute(const CefString& localName, + const CefString& namespaceURI) { + if (CEF_MEMBER_MISSING(struct_, move_to_attribute_bylname)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: localName; type: string_byref_const + DCHECK(!localName.empty()); + if (localName.empty()) + return false; + // Verify param: namespaceURI; type: string_byref_const + DCHECK(!namespaceURI.empty()); + if (namespaceURI.empty()) + return false; + + // Execute + int _retval = struct_->move_to_attribute_bylname(struct_, + localName.GetStruct(), + namespaceURI.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::MoveToFirstAttribute() { + if (CEF_MEMBER_MISSING(struct_, move_to_first_attribute)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_first_attribute(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::MoveToNextAttribute() { + if (CEF_MEMBER_MISSING(struct_, move_to_next_attribute)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_next_attribute(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefXmlReaderCToCpp::MoveToCarryingElement() { + if (CEF_MEMBER_MISSING(struct_, move_to_carrying_element)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_carrying_element(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/xml_reader_ctocpp.h b/libcef_dll/ctocpp/xml_reader_ctocpp.h new file mode 100644 index 000000000..640c13077 --- /dev/null +++ b/libcef_dll/ctocpp/xml_reader_ctocpp.h @@ -0,0 +1,69 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_XML_READER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_XML_READER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_xml_reader.h" +#include "include/capi/cef_xml_reader_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefXmlReaderCToCpp + : public CefCToCpp { + public: + explicit CefXmlReaderCToCpp(cef_xml_reader_t* str) + : CefCToCpp(str) {} + + // CefXmlReader methods + virtual bool MoveToNextNode() OVERRIDE; + virtual bool Close() OVERRIDE; + virtual bool HasError() OVERRIDE; + virtual CefString GetError() OVERRIDE; + virtual NodeType GetType() OVERRIDE; + virtual int GetDepth() OVERRIDE; + virtual CefString GetLocalName() OVERRIDE; + virtual CefString GetPrefix() OVERRIDE; + virtual CefString GetQualifiedName() OVERRIDE; + virtual CefString GetNamespaceURI() OVERRIDE; + virtual CefString GetBaseURI() OVERRIDE; + virtual CefString GetXmlLang() OVERRIDE; + virtual bool IsEmptyElement() OVERRIDE; + virtual bool HasValue() OVERRIDE; + virtual CefString GetValue() OVERRIDE; + virtual bool HasAttributes() OVERRIDE; + virtual size_t GetAttributeCount() OVERRIDE; + virtual CefString GetAttribute(int index) OVERRIDE; + virtual CefString GetAttribute(const CefString& qualifiedName) OVERRIDE; + virtual CefString GetAttribute(const CefString& localName, + const CefString& namespaceURI) OVERRIDE; + virtual CefString GetInnerXml() OVERRIDE; + virtual CefString GetOuterXml() OVERRIDE; + virtual int GetLineNumber() OVERRIDE; + virtual bool MoveToAttribute(int index) OVERRIDE; + virtual bool MoveToAttribute(const CefString& qualifiedName) OVERRIDE; + virtual bool MoveToAttribute(const CefString& localName, + const CefString& namespaceURI) OVERRIDE; + virtual bool MoveToFirstAttribute() OVERRIDE; + virtual bool MoveToNextAttribute() OVERRIDE; + virtual bool MoveToCarryingElement() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_XML_READER_CTOCPP_H_ + diff --git a/libcef_dll/ctocpp/zip_reader_ctocpp.cc b/libcef_dll/ctocpp/zip_reader_ctocpp.cc new file mode 100644 index 000000000..ec8314546 --- /dev/null +++ b/libcef_dll/ctocpp/zip_reader_ctocpp.cc @@ -0,0 +1,220 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/zip_reader_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefZipReader::Create( + CefRefPtr stream) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: stream; type: refptr_same + DCHECK(stream.get()); + if (!stream.get()) + return NULL; + + // Execute + cef_zip_reader_t* _retval = cef_zip_reader_create( + CefStreamReaderCToCpp::Unwrap(stream)); + + // Return type: refptr_same + return CefZipReaderCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefZipReaderCToCpp::MoveToFirstFile() { + if (CEF_MEMBER_MISSING(struct_, move_to_first_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_first_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::MoveToNextFile() { + if (CEF_MEMBER_MISSING(struct_, move_to_next_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_next_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::MoveToFile(const CefString& fileName, + bool caseSensitive) { + if (CEF_MEMBER_MISSING(struct_, move_to_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(!fileName.empty()); + if (fileName.empty()) + return false; + + // Execute + int _retval = struct_->move_to_file(struct_, + fileName.GetStruct(), + caseSensitive); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::Close() { + if (CEF_MEMBER_MISSING(struct_, close)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->close(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefZipReaderCToCpp::GetFileName() { + if (CEF_MEMBER_MISSING(struct_, get_file_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_file_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int64 CefZipReaderCToCpp::GetFileSize() { + if (CEF_MEMBER_MISSING(struct_, get_file_size)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->get_file_size(struct_); + + // Return type: simple + return _retval; +} + +time_t CefZipReaderCToCpp::GetFileLastModified() { + if (CEF_MEMBER_MISSING(struct_, get_file_last_modified)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + time_t _retval = struct_->get_file_last_modified(struct_); + + // Return type: simple + return _retval; +} + +bool CefZipReaderCToCpp::OpenFile(const CefString& password) { + if (CEF_MEMBER_MISSING(struct_, open_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: password + + // Execute + int _retval = struct_->open_file(struct_, + password.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::CloseFile() { + if (CEF_MEMBER_MISSING(struct_, close_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->close_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +int CefZipReaderCToCpp::ReadFile(void* buffer, size_t bufferSize) { + if (CEF_MEMBER_MISSING(struct_, read_file)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return 0; + + // Execute + int _retval = struct_->read_file(struct_, + buffer, + bufferSize); + + // Return type: simple + return _retval; +} + +int64 CefZipReaderCToCpp::Tell() { + if (CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->tell(struct_); + + // Return type: simple + return _retval; +} + +bool CefZipReaderCToCpp::Eof() { + if (CEF_MEMBER_MISSING(struct_, eof)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->eof(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> base::AtomicRefCount CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/libcef_dll/ctocpp/zip_reader_ctocpp.h b/libcef_dll/ctocpp/zip_reader_ctocpp.h new file mode 100644 index 000000000..e245305fb --- /dev/null +++ b/libcef_dll/ctocpp/zip_reader_ctocpp.h @@ -0,0 +1,51 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#ifndef CEF_LIBCEF_DLL_CTOCPP_ZIP_READER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_ZIP_READER_CTOCPP_H_ +#pragma once + +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED + +#include "include/cef_zip_reader.h" +#include "include/capi/cef_zip_reader_capi.h" +#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +// This class may be instantiated and accessed wrapper-side only. +class CefZipReaderCToCpp + : public CefCToCpp { + public: + explicit CefZipReaderCToCpp(cef_zip_reader_t* str) + : CefCToCpp(str) {} + + // CefZipReader methods + virtual bool MoveToFirstFile() OVERRIDE; + virtual bool MoveToNextFile() OVERRIDE; + virtual bool MoveToFile(const CefString& fileName, + bool caseSensitive) OVERRIDE; + virtual bool Close() OVERRIDE; + virtual CefString GetFileName() OVERRIDE; + virtual int64 GetFileSize() OVERRIDE; + virtual time_t GetFileLastModified() OVERRIDE; + virtual bool OpenFile(const CefString& password) OVERRIDE; + virtual bool CloseFile() OVERRIDE; + virtual int ReadFile(void* buffer, size_t bufferSize) OVERRIDE; + virtual int64 Tell() OVERRIDE; + virtual bool Eof() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_ZIP_READER_CTOCPP_H_ + diff --git a/libcef_dll/libcef.dll.manifest b/libcef_dll/libcef.dll.manifest new file mode 100644 index 000000000..76c638080 --- /dev/null +++ b/libcef_dll/libcef.dll.manifest @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/libcef_dll/libcef_dll.cc b/libcef_dll/libcef_dll.cc new file mode 100644 index 000000000..cde827369 --- /dev/null +++ b/libcef_dll/libcef_dll.cc @@ -0,0 +1,783 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "include/cef_app.h" +#include "include/capi/cef_app_capi.h" +#include "include/cef_geolocation.h" +#include "include/capi/cef_geolocation_capi.h" +#include "include/cef_origin_whitelist.h" +#include "include/capi/cef_origin_whitelist_capi.h" +#include "include/cef_path_util.h" +#include "include/capi/cef_path_util_capi.h" +#include "include/cef_process_util.h" +#include "include/capi/cef_process_util_capi.h" +#include "include/cef_scheme.h" +#include "include/capi/cef_scheme_capi.h" +#include "include/cef_task.h" +#include "include/capi/cef_task_capi.h" +#include "include/cef_trace.h" +#include "include/capi/cef_trace_capi.h" +#include "include/cef_url.h" +#include "include/capi/cef_url_capi.h" +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "libcef_dll/cpptoc/allow_certificate_error_callback_cpptoc.h" +#include "libcef_dll/cpptoc/auth_callback_cpptoc.h" +#include "libcef_dll/cpptoc/before_download_callback_cpptoc.h" +#include "libcef_dll/cpptoc/binary_value_cpptoc.h" +#include "libcef_dll/cpptoc/browser_cpptoc.h" +#include "libcef_dll/cpptoc/browser_host_cpptoc.h" +#include "libcef_dll/cpptoc/callback_cpptoc.h" +#include "libcef_dll/cpptoc/command_line_cpptoc.h" +#include "libcef_dll/cpptoc/context_menu_params_cpptoc.h" +#include "libcef_dll/cpptoc/domdocument_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" +#include "libcef_dll/cpptoc/dictionary_value_cpptoc.h" +#include "libcef_dll/cpptoc/download_item_cpptoc.h" +#include "libcef_dll/cpptoc/download_item_callback_cpptoc.h" +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/cpptoc/file_dialog_callback_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/geolocation_callback_cpptoc.h" +#include "libcef_dll/cpptoc/jsdialog_callback_cpptoc.h" +#include "libcef_dll/cpptoc/list_value_cpptoc.h" +#include "libcef_dll/cpptoc/menu_model_cpptoc.h" +#include "libcef_dll/cpptoc/navigation_entry_cpptoc.h" +#include "libcef_dll/cpptoc/print_dialog_callback_cpptoc.h" +#include "libcef_dll/cpptoc/print_job_callback_cpptoc.h" +#include "libcef_dll/cpptoc/print_settings_cpptoc.h" +#include "libcef_dll/cpptoc/process_message_cpptoc.h" +#include "libcef_dll/cpptoc/quota_callback_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_registrar_cpptoc.h" +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" +#include "libcef_dll/cpptoc/stream_writer_cpptoc.h" +#include "libcef_dll/cpptoc/task_runner_cpptoc.h" +#include "libcef_dll/cpptoc/urlrequest_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/cpptoc/v8exception_cpptoc.h" +#include "libcef_dll/cpptoc/v8stack_frame_cpptoc.h" +#include "libcef_dll/cpptoc/v8stack_trace_cpptoc.h" +#include "libcef_dll/cpptoc/v8value_cpptoc.h" +#include "libcef_dll/cpptoc/web_plugin_info_cpptoc.h" +#include "libcef_dll/cpptoc/xml_reader_cpptoc.h" +#include "libcef_dll/cpptoc/zip_reader_cpptoc.h" +#include "libcef_dll/ctocpp/app_ctocpp.h" +#include "libcef_dll/ctocpp/browser_process_handler_ctocpp.h" +#include "libcef_dll/ctocpp/completion_callback_ctocpp.h" +#include "libcef_dll/ctocpp/context_menu_handler_ctocpp.h" +#include "libcef_dll/ctocpp/cookie_visitor_ctocpp.h" +#include "libcef_dll/ctocpp/domvisitor_ctocpp.h" +#include "libcef_dll/ctocpp/dialog_handler_ctocpp.h" +#include "libcef_dll/ctocpp/display_handler_ctocpp.h" +#include "libcef_dll/ctocpp/download_handler_ctocpp.h" +#include "libcef_dll/ctocpp/drag_handler_ctocpp.h" +#include "libcef_dll/ctocpp/end_tracing_callback_ctocpp.h" +#include "libcef_dll/ctocpp/find_handler_ctocpp.h" +#include "libcef_dll/ctocpp/focus_handler_ctocpp.h" +#include "libcef_dll/ctocpp/geolocation_handler_ctocpp.h" +#include "libcef_dll/ctocpp/get_geolocation_callback_ctocpp.h" +#include "libcef_dll/ctocpp/jsdialog_handler_ctocpp.h" +#include "libcef_dll/ctocpp/keyboard_handler_ctocpp.h" +#include "libcef_dll/ctocpp/life_span_handler_ctocpp.h" +#include "libcef_dll/ctocpp/load_handler_ctocpp.h" +#include "libcef_dll/ctocpp/navigation_entry_visitor_ctocpp.h" +#include "libcef_dll/ctocpp/print_handler_ctocpp.h" +#include "libcef_dll/ctocpp/read_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_process_handler_ctocpp.h" +#include "libcef_dll/ctocpp/request_handler_ctocpp.h" +#include "libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h" +#include "libcef_dll/ctocpp/resource_handler_ctocpp.h" +#include "libcef_dll/ctocpp/run_file_dialog_callback_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h" +#include "libcef_dll/ctocpp/string_visitor_ctocpp.h" +#include "libcef_dll/ctocpp/task_ctocpp.h" +#include "libcef_dll/ctocpp/urlrequest_client_ctocpp.h" +#include "libcef_dll/ctocpp/v8accessor_ctocpp.h" +#include "libcef_dll/ctocpp/v8handler_ctocpp.h" +#include "libcef_dll/ctocpp/web_plugin_info_visitor_ctocpp.h" +#include "libcef_dll/ctocpp/web_plugin_unstable_callback_ctocpp.h" +#include "libcef_dll/ctocpp/write_handler_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT int cef_execute_process(const struct _cef_main_args_t* args, + struct _cef_app_t* application, void* windows_sandbox_info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: args; type: struct_byref_const + DCHECK(args); + if (!args) + return 0; + // Unverified params: application, windows_sandbox_info + + // Translate param: args; type: struct_byref_const + CefMainArgs argsObj; + if (args) + argsObj.Set(*args, false); + + // Execute + int _retval = CefExecuteProcess( + argsObj, + CefAppCToCpp::Wrap(application), + windows_sandbox_info); + + // Return type: simple + return _retval; +} + +CEF_EXPORT int cef_initialize(const struct _cef_main_args_t* args, + const struct _cef_settings_t* settings, struct _cef_app_t* application, + void* windows_sandbox_info) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: args; type: struct_byref_const + DCHECK(args); + if (!args) + return 0; + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return 0; + // Unverified params: application, windows_sandbox_info + + // Translate param: args; type: struct_byref_const + CefMainArgs argsObj; + if (args) + argsObj.Set(*args, false); + // Translate param: settings; type: struct_byref_const + CefSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + + // Execute + bool _retval = CefInitialize( + argsObj, + settingsObj, + CefAppCToCpp::Wrap(application), + windows_sandbox_info); + + // Return type: bool + return _retval; +} + +CEF_EXPORT void cef_shutdown() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefShutdown(); + +#ifndef NDEBUG + // Check that all wrapper objects have been destroyed + DCHECK(base::AtomicRefCountIsZero( + &CefAllowCertificateErrorCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefAuthCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefBeforeDownloadCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefBinaryValueCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefBrowserCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefBrowserHostCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefBrowserProcessHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefCompletionCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefContextMenuHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefContextMenuParamsCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefCookieVisitorCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDOMDocumentCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDOMNodeCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDOMVisitorCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDialogHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDictionaryValueCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDisplayHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDownloadHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefDownloadItemCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDownloadItemCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDragDataCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDragHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefEndTracingCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFileDialogCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFindHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFocusHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFrameCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefGeolocationCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefGeolocationHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefGetGeolocationCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefJSDialogCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefJSDialogHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefKeyboardHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefLifeSpanHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefListValueCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefLoadHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefMenuModelCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefNavigationEntryCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefNavigationEntryVisitorCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintDialogCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintJobCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintSettingsCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefProcessMessageCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefQuotaCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefReadHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefRenderHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefRenderProcessHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefRequestHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefResourceBundleHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefResourceHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefRunFileDialogCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefSchemeHandlerFactoryCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefSchemeRegistrarCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefStreamReaderCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefStreamWriterCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefStringVisitorCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefTaskCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefTaskRunnerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefURLRequestClientCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefURLRequestCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8AccessorCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8ContextCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8ExceptionCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8HandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8StackFrameCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8StackTraceCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8ValueCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefWebPluginInfoCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefWebPluginInfoVisitorCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefWebPluginUnstableCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefWriteHandlerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefXmlReaderCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefZipReaderCppToC::DebugObjCt)); +#endif // !NDEBUG +} + +CEF_EXPORT void cef_do_message_loop_work() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefDoMessageLoopWork(); +} + +CEF_EXPORT void cef_run_message_loop() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRunMessageLoop(); +} + +CEF_EXPORT void cef_quit_message_loop() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefQuitMessageLoop(); +} + +CEF_EXPORT void cef_set_osmodal_loop(int osModalLoop) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefSetOSModalLoop( + osModalLoop?true:false); +} + +CEF_EXPORT int cef_get_geolocation( + struct _cef_get_geolocation_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return 0; + + // Execute + bool _retval = CefGetGeolocation( + CefGetGeolocationCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_add_cross_origin_whitelist_entry( + const cef_string_t* source_origin, const cef_string_t* target_protocol, + const cef_string_t* target_domain, int allow_target_subdomains) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: source_origin; type: string_byref_const + DCHECK(source_origin); + if (!source_origin) + return 0; + // Verify param: target_protocol; type: string_byref_const + DCHECK(target_protocol); + if (!target_protocol) + return 0; + // Unverified params: target_domain + + // Execute + bool _retval = CefAddCrossOriginWhitelistEntry( + CefString(source_origin), + CefString(target_protocol), + CefString(target_domain), + allow_target_subdomains?true:false); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_remove_cross_origin_whitelist_entry( + const cef_string_t* source_origin, const cef_string_t* target_protocol, + const cef_string_t* target_domain, int allow_target_subdomains) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: source_origin; type: string_byref_const + DCHECK(source_origin); + if (!source_origin) + return 0; + // Verify param: target_protocol; type: string_byref_const + DCHECK(target_protocol); + if (!target_protocol) + return 0; + // Unverified params: target_domain + + // Execute + bool _retval = CefRemoveCrossOriginWhitelistEntry( + CefString(source_origin), + CefString(target_protocol), + CefString(target_domain), + allow_target_subdomains?true:false); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_clear_cross_origin_whitelist() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + bool _retval = CefClearCrossOriginWhitelist(); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_get_path(cef_path_key_t key, cef_string_t* path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref + DCHECK(path); + if (!path) + return 0; + + // Translate param: path; type: string_byref + CefString pathStr(path); + + // Execute + bool _retval = CefGetPath( + key, + pathStr); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_launch_process(struct _cef_command_line_t* command_line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: command_line; type: refptr_same + DCHECK(command_line); + if (!command_line) + return 0; + + // Execute + bool _retval = CefLaunchProcess( + CefCommandLineCppToC::Unwrap(command_line)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_register_scheme_handler_factory( + const cef_string_t* scheme_name, const cef_string_t* domain_name, + struct _cef_scheme_handler_factory_t* factory) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: scheme_name; type: string_byref_const + DCHECK(scheme_name); + if (!scheme_name) + return 0; + // Unverified params: domain_name, factory + + // Execute + bool _retval = CefRegisterSchemeHandlerFactory( + CefString(scheme_name), + CefString(domain_name), + CefSchemeHandlerFactoryCToCpp::Wrap(factory)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_clear_scheme_handler_factories() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + bool _retval = CefClearSchemeHandlerFactories(); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_currently_on(cef_thread_id_t threadId) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + bool _retval = CefCurrentlyOn( + threadId); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_post_task(cef_thread_id_t threadId, + struct _cef_task_t* task) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: task; type: refptr_diff + DCHECK(task); + if (!task) + return 0; + + // Execute + bool _retval = CefPostTask( + threadId, + CefTaskCToCpp::Wrap(task)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, + struct _cef_task_t* task, int64 delay_ms) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: task; type: refptr_diff + DCHECK(task); + if (!task) + return 0; + + // Execute + bool _retval = CefPostDelayedTask( + threadId, + CefTaskCToCpp::Wrap(task), + delay_ms); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_begin_tracing(const cef_string_t* categories, + struct _cef_completion_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: categories, callback + + // Execute + bool _retval = CefBeginTracing( + CefString(categories), + CefCompletionCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_end_tracing(const cef_string_t* tracing_file, + struct _cef_end_tracing_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: tracing_file, callback + + // Execute + bool _retval = CefEndTracing( + CefString(tracing_file), + CefEndTracingCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int64 cef_now_from_system_trace_time() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = CefNowFromSystemTraceTime(); + + // Return type: simple + return _retval; +} + +CEF_EXPORT int cef_parse_url(const cef_string_t* url, + struct _cef_urlparts_t* parts) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return 0; + // Verify param: parts; type: struct_byref + DCHECK(parts); + if (!parts) + return 0; + + // Translate param: parts; type: struct_byref + CefURLParts partsObj; + if (parts) + partsObj.AttachTo(*parts); + + // Execute + bool _retval = CefParseURL( + CefString(url), + partsObj); + + // Restore param: parts; type: struct_byref + if (parts) + partsObj.DetachTo(*parts); + + // Return type: bool + return _retval; +} + +CEF_EXPORT int cef_create_url(const struct _cef_urlparts_t* parts, + cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: parts; type: struct_byref_const + DCHECK(parts); + if (!parts) + return 0; + // Verify param: url; type: string_byref + DCHECK(url); + if (!url) + return 0; + + // Translate param: parts; type: struct_byref_const + CefURLParts partsObj; + if (parts) + partsObj.Set(*parts, false); + // Translate param: url; type: string_byref + CefString urlStr(url); + + // Execute + bool _retval = CefCreateURL( + partsObj, + urlStr); + + // Return type: bool + return _retval; +} + +CEF_EXPORT cef_string_userfree_t cef_get_mime_type( + const cef_string_t* extension) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: extension; type: string_byref_const + DCHECK(extension); + if (!extension) + return NULL; + + // Execute + CefString _retval = CefGetMimeType( + CefString(extension)); + + // Return type: string + return _retval.DetachToUserFree(); +} + +CEF_EXPORT void cef_get_extensions_for_mime_type(const cef_string_t* mime_type, + cef_string_list_t extensions) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: mime_type; type: string_byref_const + DCHECK(mime_type); + if (!mime_type) + return; + // Verify param: extensions; type: string_vec_byref + DCHECK(extensions); + if (!extensions) + return; + + // Translate param: extensions; type: string_vec_byref + std::vector extensionsList; + transfer_string_list_contents(extensions, extensionsList); + + // Execute + CefGetExtensionsForMimeType( + CefString(mime_type), + extensionsList); + + // Restore param: extensions; type: string_vec_byref + cef_string_list_clear(extensions); + transfer_string_list_contents(extensionsList, extensions); +} + +CEF_EXPORT int cef_register_extension(const cef_string_t* extension_name, + const cef_string_t* javascript_code, struct _cef_v8handler_t* handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: extension_name; type: string_byref_const + DCHECK(extension_name); + if (!extension_name) + return 0; + // Verify param: javascript_code; type: string_byref_const + DCHECK(javascript_code); + if (!javascript_code) + return 0; + // Unverified params: handler + + // Execute + bool _retval = CefRegisterExtension( + CefString(extension_name), + CefString(javascript_code), + CefV8HandlerCToCpp::Wrap(handler)); + + // Return type: bool + return _retval; +} + +CEF_EXPORT void cef_visit_web_plugin_info( + struct _cef_web_plugin_info_visitor_t* visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor); + if (!visitor) + return; + + // Execute + CefVisitWebPluginInfo( + CefWebPluginInfoVisitorCToCpp::Wrap(visitor)); +} + +CEF_EXPORT void cef_refresh_web_plugins() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefreshWebPlugins(); +} + +CEF_EXPORT void cef_add_web_plugin_path(const cef_string_t* path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + + // Execute + CefAddWebPluginPath( + CefString(path)); +} + +CEF_EXPORT void cef_add_web_plugin_directory(const cef_string_t* dir) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: dir; type: string_byref_const + DCHECK(dir); + if (!dir) + return; + + // Execute + CefAddWebPluginDirectory( + CefString(dir)); +} + +CEF_EXPORT void cef_remove_web_plugin_path(const cef_string_t* path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + + // Execute + CefRemoveWebPluginPath( + CefString(path)); +} + +CEF_EXPORT void cef_unregister_internal_web_plugin(const cef_string_t* path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + + // Execute + CefUnregisterInternalWebPlugin( + CefString(path)); +} + +CEF_EXPORT void cef_force_web_plugin_shutdown(const cef_string_t* path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + + // Execute + CefForceWebPluginShutdown( + CefString(path)); +} + +CEF_EXPORT void cef_register_web_plugin_crash(const cef_string_t* path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + + // Execute + CefRegisterWebPluginCrash( + CefString(path)); +} + +CEF_EXPORT void cef_is_web_plugin_unstable(const cef_string_t* path, + struct _cef_web_plugin_unstable_callback_t* callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(path); + if (!path) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback); + if (!callback) + return; + + // Execute + CefIsWebPluginUnstable( + CefString(path), + CefWebPluginUnstableCallbackCToCpp::Wrap(callback)); +} + diff --git a/libcef_dll/libcef_dll.rc b/libcef_dll/libcef_dll.rc new file mode 100644 index 000000000..6e5752258 --- /dev/null +++ b/libcef_dll/libcef_dll.rc @@ -0,0 +1,143 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#define APSTUDIO_HIDDEN_SYMBOLS +#include "windows.h" +#include "include/cef_version.h" +#undef APSTUDIO_HIDDEN_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#define APSTUDIO_HIDDEN_SYMBOLS\r\n" + "#include ""windows.h""\r\n" + "#include ""include/version.h""\r\n" + "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ALERT DIALOGEX 0, 0, 241, 76 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "JavaScript Alert" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,184,55,50,14 + LTEXT "",IDC_DIALOGTEXT,16,17,210,30 +END + +IDD_CONFIRM DIALOGEX 0, 0, 241, 76 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "JavaScript Confirm" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + PUSHBUTTON "Cancel",IDCANCEL,184,55,50,14 + DEFPUSHBUTTON "OK",IDOK,131,55,50,14 + LTEXT "",IDC_DIALOGTEXT,16,17,210,30 +END + +IDD_PROMPT DIALOGEX 0, 0, 241, 76 +STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "JavaScript Prompt" +FONT 8, "MS Shell Dlg", 400, 0, 0x1 +BEGIN + DEFPUSHBUTTON "OK",IDOK,131,55,50,14 + LTEXT "",IDC_DIALOGTEXT,16,17,210,18 + PUSHBUTTON "Cancel",IDCANCEL,184,55,50,14 + EDITTEXT IDC_PROMPTEDIT,15,33,210,14,ES_AUTOHSCROLL +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION CEF_VERSION_MAJOR,CHROME_VERSION_BUILD,CEF_REVISION,0 + PRODUCTVERSION CEF_VERSION_MAJOR,CHROME_VERSION_BUILD,CEF_REVISION,0 + FILEFLAGSMASK 0x17L +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x4L + FILETYPE 0x2L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "FileDescription", "Chromium Embedded Framework (CEF) Dynamic Link Library" + VALUE "FileVersion", MAKE_STRING(CEF_VERSION_MAJOR) "." MAKE_STRING(CHROME_VERSION_BUILD) "." MAKE_STRING(CEF_REVISION) + VALUE "InternalName", "libcef" + VALUE "LegalCopyright", "Copyright (C) " MAKE_STRING(COPYRIGHT_YEAR) " The Chromium Embedded Framework Authors" + VALUE "OriginalFilename", "libcef.dll" + VALUE "ProductName", "Chromium Embedded Framework (CEF) Dynamic Link Library" + VALUE "ProductVersion", MAKE_STRING(CEF_VERSION_MAJOR) "." MAKE_STRING(CHROME_VERSION_BUILD) "." MAKE_STRING(CEF_REVISION) + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/libcef_dll/libcef_dll2.cc b/libcef_dll/libcef_dll2.cc new file mode 100644 index 000000000..1a5172313 --- /dev/null +++ b/libcef_dll/libcef_dll2.cc @@ -0,0 +1,31 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// + +#include "include/cef_version.h" +#include + +CEF_EXPORT int cef_build_revision() { + return CEF_REVISION; +} + +CEF_EXPORT int cef_version_info(int entry) { + switch (entry) { + case 0: return CEF_VERSION_MAJOR; + case 1: return CEF_REVISION; + case 2: return CHROME_VERSION_MAJOR; + case 3: return CHROME_VERSION_MINOR; + case 4: return CHROME_VERSION_BUILD; + case 5: return CHROME_VERSION_PATCH; + default: return 0; + } +} + +CEF_EXPORT const char* cef_api_hash(int entry) { + switch (entry) { + case 0: return CEF_API_HASH_PLATFORM; + case 1: return CEF_API_HASH_UNIVERSAL; + default: return NULL; + } +} diff --git a/libcef_dll/resource.h b/libcef_dll/resource.h new file mode 100644 index 000000000..cbeef193d --- /dev/null +++ b/libcef_dll/resource.h @@ -0,0 +1,26 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by libcef_dll.rc +// + +// Avoid files associated with MacOS +#define _X86_ + +#define IDD_ALERT 130 +#define IDD_CONFIRM 131 +#define IDD_PROMPT 132 +#define IDC_PROMPTEDIT 1000 +#define IDC_DIALOGTEXT 1001 + + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 130 +#define _APS_NEXT_COMMAND_VALUE 32000 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 110 +#endif +#endif diff --git a/libcef_dll/sandbox/sandbox_win.cc b/libcef_dll/sandbox/sandbox_win.cc new file mode 100644 index 000000000..9f5ee10df --- /dev/null +++ b/libcef_dll/sandbox/sandbox_win.cc @@ -0,0 +1,39 @@ +// Copyright 2013 The Chromium Embedded Framework Authors. Portions Copyright +// 2011 the Chromium Authors. All rights reserved. Use of this source code is +// governed by a BSD-style license that can be found in the LICENSE file. + +// Include this first to avoid conflicts with cef_macros.h. +#include "base/macros.h" + +#include "include/cef_sandbox_win.h" + +#include "sandbox/win/src/process_mitigations.h" +#include "sandbox/win/src/sandbox_factory.h" + +namespace { + +// From content/app/startup_helper_win.cc: +void InitializeSandboxInfo(sandbox::SandboxInterfaceInfo* info) { + info->broker_services = sandbox::SandboxFactory::GetBrokerServices(); + if (!info->broker_services) { + info->target_services = sandbox::SandboxFactory::GetTargetServices(); + } else { + // Ensure the proper mitigations are enforced for the browser process. + sandbox::ApplyProcessMitigationsToCurrentProcess( + sandbox::MITIGATION_DEP | + sandbox::MITIGATION_DEP_NO_ATL_THUNK); + } +} + +} // namespace + +void* cef_sandbox_info_create() { + sandbox::SandboxInterfaceInfo* info = new sandbox::SandboxInterfaceInfo(); + memset(info, 0, sizeof(sandbox::SandboxInterfaceInfo)); + InitializeSandboxInfo(info); + return info; +} + +void cef_sandbox_info_destroy(void* sandbox_info) { + delete static_cast(sandbox_info); +} diff --git a/libcef_dll/transfer_util.cc b/libcef_dll/transfer_util.cc new file mode 100644 index 000000000..e9d8d4e22 --- /dev/null +++ b/libcef_dll/transfer_util.cc @@ -0,0 +1,72 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "transfer_util.h" + +void transfer_string_list_contents(cef_string_list_t fromList, + StringList& toList) +{ + int size = cef_string_list_size(fromList); + CefString value; + + for(int i = 0; i < size; i++) { + cef_string_list_value(fromList, i, value.GetWritableStruct()); + toList.push_back(value); + } +} + +void transfer_string_list_contents(const StringList& fromList, + cef_string_list_t toList) +{ + size_t size = fromList.size(); + for(size_t i = 0; i < size; ++i) + cef_string_list_append(toList, fromList[i].GetStruct()); +} + +void transfer_string_map_contents(cef_string_map_t fromMap, + StringMap& toMap) +{ + int size = cef_string_map_size(fromMap); + CefString key, value; + + for(int i = 0; i < size; ++i) { + cef_string_map_key(fromMap, i, key.GetWritableStruct()); + cef_string_map_value(fromMap, i, value.GetWritableStruct()); + + toMap.insert(std::make_pair(key, value)); + } +} + +void transfer_string_map_contents(const StringMap& fromMap, + cef_string_map_t toMap) +{ + StringMap::const_iterator it = fromMap.begin(); + for(; it != fromMap.end(); ++it) + cef_string_map_append(toMap, it->first.GetStruct(), it->second.GetStruct()); +} + +void transfer_string_multimap_contents(cef_string_multimap_t fromMap, + StringMultimap& toMap) +{ + int size = cef_string_multimap_size(fromMap); + CefString key, value; + + for(int i = 0; i < size; ++i) { + cef_string_multimap_key(fromMap, i, key.GetWritableStruct()); + cef_string_multimap_value(fromMap, i, value.GetWritableStruct()); + + toMap.insert(std::make_pair(key, value)); + } +} + +void transfer_string_multimap_contents(const StringMultimap& fromMap, + cef_string_multimap_t toMap) +{ + StringMultimap::const_iterator it = fromMap.begin(); + for(; it != fromMap.end(); ++it) { + cef_string_multimap_append(toMap, + it->first.GetStruct(), + it->second.GetStruct()); + } +} diff --git a/libcef_dll/transfer_util.h b/libcef_dll/transfer_util.h new file mode 100644 index 000000000..88dff1a38 --- /dev/null +++ b/libcef_dll/transfer_util.h @@ -0,0 +1,37 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DLL_TRANSFER_UTIL_H_ +#define CEF_LIBCEF_DLL_TRANSFER_UTIL_H_ +#pragma once + +#include +#include + +#include "include/internal/cef_string_list.h" +#include "include/internal/cef_string_map.h" +#include "include/internal/cef_string_multimap.h" + +// Copy contents from one list type to another. +typedef std::vector StringList; +void transfer_string_list_contents(cef_string_list_t fromList, + StringList& toList); +void transfer_string_list_contents(const StringList& fromList, + cef_string_list_t toList); + +// Copy contents from one map type to another. +typedef std::map StringMap; +void transfer_string_map_contents(cef_string_map_t fromMap, + StringMap& toMap); +void transfer_string_map_contents(const StringMap& fromMap, + cef_string_map_t toMap); + +// Copy contents from one map type to another. +typedef std::multimap StringMultimap; +void transfer_string_multimap_contents(cef_string_multimap_t fromMap, + StringMultimap& toMap); +void transfer_string_multimap_contents(const StringMultimap& fromMap, + cef_string_multimap_t toMap); + +#endif // CEF_LIBCEF_DLL_TRANSFER_UTIL_H_ diff --git a/libcef_dll/wrapper/cef_browser_info_map.h b/libcef_dll/wrapper/cef_browser_info_map.h new file mode 100644 index 000000000..9cf1ab486 --- /dev/null +++ b/libcef_dll/wrapper/cef_browser_info_map.h @@ -0,0 +1,265 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_LIBCEF_DLL_WRAPPER_CEF_BROWSER_INFO_MAP_H_ +#define CEF_LIBCEF_DLL_WRAPPER_CEF_BROWSER_INFO_MAP_H_ +#pragma once + +#include + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" + +// Default traits for CefBrowserInfoMap. Override to provide different object +// destruction behavior. +template +struct DefaultCefBrowserInfoMapTraits { + static void Destruct(ObjectType info) { + delete info; + } +}; + +// Maps an arbitrary IdType to an arbitrary ObjectType on a per-browser basis. +template > +class CefBrowserInfoMap { + public: + // Implement this interface to visit and optionally delete objects in the map. + class Visitor { + public: + typedef IdType InfoIdType; + typedef ObjectType InfoObjectType; + + // Called once for each info object. Set |remove| to true to remove the + // object from the map. It is safe to destruct removed objects in this + // callback. Return true to continue iterating or false to stop iterating. + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) =0; + + protected: + virtual ~Visitor() {} + }; + + CefBrowserInfoMap() {} + + ~CefBrowserInfoMap() { + clear(); + } + + // Add an object associated with the specified ID values. + void Add(int browser_id, IdType info_id, ObjectType info) { + InfoMap* info_map = NULL; + typename BrowserInfoMap::const_iterator it_browser = + browser_info_map_.find(browser_id); + if (it_browser == browser_info_map_.end()) { + // No InfoMap exists for the browser ID so create it. + info_map = new InfoMap; + browser_info_map_.insert(std::make_pair(browser_id, info_map)); + } else { + info_map = it_browser->second; + // The specified ID should not already exist in the map. + DCHECK(info_map->find(info_id) == info_map->end()); + } + + info_map->insert(std::make_pair(info_id, info)); + } + + // Find the object with the specified ID values. |visitor| can optionally be + // used to evaluate or remove the object at the same time. If the object is + // removed using the Visitor the caller is responsible for destroying it. + ObjectType Find(int browser_id, IdType info_id, Visitor* vistor) { + if (browser_info_map_.empty()) + return ObjectType(); + + typename BrowserInfoMap::iterator it_browser = + browser_info_map_.find(browser_id); + if (it_browser == browser_info_map_.end()) + return ObjectType(); + + InfoMap* info_map = it_browser->second; + typename InfoMap::iterator it_info = info_map->find(info_id); + if (it_info == info_map->end()) + return ObjectType(); + + ObjectType info = it_info->second; + + bool remove = false; + if (vistor) + vistor->OnNextInfo(browser_id, it_info->first, info, &remove); + if (remove) { + info_map->erase(it_info); + + if (info_map->empty()) { + // No more entries in the InfoMap so remove it. + browser_info_map_.erase(it_browser); + delete info_map; + } + } + + return info; + } + + // Find all objects. If any objects are removed using the Visitor the caller + // is responsible for destroying them. + void FindAll(Visitor* visitor) { + DCHECK(visitor); + + if (browser_info_map_.empty()) + return; + + bool remove, keepgoing = true; + + typename BrowserInfoMap::iterator it_browser = browser_info_map_.begin(); + while (it_browser != browser_info_map_.end()) { + InfoMap* info_map = it_browser->second; + + typename InfoMap::iterator it_info = info_map->begin(); + while (it_info != info_map->end()) { + remove = false; + keepgoing = visitor->OnNextInfo(it_browser->first, it_info->first, + it_info->second, &remove); + + if (remove) + info_map->erase(it_info++); + else + ++it_info; + + if (!keepgoing) + break; + } + + if (info_map->empty()) { + // No more entries in the InfoMap so remove it. + browser_info_map_.erase(it_browser++); + delete info_map; + } else { + ++it_browser; + } + + if (!keepgoing) + break; + } + } + + // Find all objects associated with the specified browser. If any objects are + // removed using the Visitor the caller is responsible for destroying them. + void FindAll(int browser_id, Visitor* visitor) { + DCHECK(visitor); + + if (browser_info_map_.empty()) + return; + + typename BrowserInfoMap::iterator it_browser = + browser_info_map_.find(browser_id); + if (it_browser == browser_info_map_.end()) + return; + + InfoMap* info_map = it_browser->second; + bool remove, keepgoing; + + typename InfoMap::iterator it_info = info_map->begin(); + while (it_info != info_map->end()) { + remove = false; + keepgoing = visitor->OnNextInfo(browser_id, it_info->first, + it_info->second, &remove); + + if (remove) + info_map->erase(it_info++); + else + ++it_info; + + if (!keepgoing) + break; + } + + if (info_map->empty()) { + // No more entries in the InfoMap so remove it. + browser_info_map_.erase(it_browser); + delete info_map; + } + } + + // Returns true if the map is empty. + bool empty() const { return browser_info_map_.empty(); } + + // Returns the number of objects in the map. + size_t size() const { + if (browser_info_map_.empty()) + return 0; + + size_t size = 0; + typename BrowserInfoMap::const_iterator it_browser = + browser_info_map_.begin(); + for (; it_browser != browser_info_map_.end(); ++it_browser) + size += it_browser->second->size(); + return size; + } + + // Returns the number of objects in the map that are associated with the + // specified browser. + size_t size(int browser_id) const { + if (browser_info_map_.empty()) + return 0; + + typename BrowserInfoMap::const_iterator it_browser = + browser_info_map_.find(browser_id); + if (it_browser != browser_info_map_.end()) + return it_browser->second->size(); + + return 0; + } + + // Remove all objects from the map. The objects will be destructed. + void clear() { + if (browser_info_map_.empty()) + return; + + typename BrowserInfoMap::const_iterator it_browser = + browser_info_map_.begin(); + for (; it_browser != browser_info_map_.end(); ++it_browser) { + InfoMap* info_map = it_browser->second; + typename InfoMap::const_iterator it_info = info_map->begin(); + for (; it_info != info_map->end(); ++it_info) + Traits::Destruct(it_info->second); + delete info_map; + } + browser_info_map_.clear(); + } + + // Remove all objects from the map that are associated with the specified + // browser. The objects will be destructed. + void clear(int browser_id) { + if (browser_info_map_.empty()) + return; + + typename BrowserInfoMap::iterator it_browser = + browser_info_map_.find(browser_id); + if (it_browser == browser_info_map_.end()) + return; + + InfoMap* info_map = it_browser->second; + typename InfoMap::const_iterator it_info = info_map->begin(); + for (; it_info != info_map->end(); ++it_info) + Traits::Destruct(it_info->second); + + browser_info_map_.erase(it_browser); + delete info_map; + } + + private: + // Map IdType to ObjectType instance. + typedef std::map InfoMap; + // Map browser ID to InfoMap instance. + typedef std::map BrowserInfoMap; + + BrowserInfoMap browser_info_map_; + + DISALLOW_COPY_AND_ASSIGN(CefBrowserInfoMap); +}; + + +#endif // CEF_LIBCEF_DLL_WRAPPER_CEF_BROWSER_INFO_MAP_H_ diff --git a/libcef_dll/wrapper/cef_byte_read_handler.cc b/libcef_dll/wrapper/cef_byte_read_handler.cc new file mode 100644 index 000000000..3d29feebf --- /dev/null +++ b/libcef_dll/wrapper/cef_byte_read_handler.cc @@ -0,0 +1,66 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/wrapper/cef_byte_read_handler.h" + +#include +#include +#include + +CefByteReadHandler::CefByteReadHandler(const unsigned char* bytes, size_t size, + CefRefPtr source) + : bytes_(bytes), size_(size), offset_(0), source_(source) { +} + +size_t CefByteReadHandler::Read(void* ptr, size_t size, size_t n) { + base::AutoLock lock_scope(lock_); + size_t s = static_cast(size_ - offset_) / size; + size_t ret = std::min(n, s); + memcpy(ptr, bytes_ + offset_, ret * size); + offset_ += ret * size; + return ret; +} + +int CefByteReadHandler::Seek(int64 offset, int whence) { + int rv = -1L; + base::AutoLock lock_scope(lock_); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > size_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { +#if defined(OS_WIN) + int64 offset_abs = _abs64(offset); +#else + int64 offset_abs = std::abs(offset); +#endif + if (offset_abs > size_) + break; + offset_ = size_ - offset_abs; + rv = 0; + break; + } + case SEEK_SET: + if (offset > size_ || offset < 0) + break; + offset_ = offset; + rv = 0; + break; + } + + return rv; +} + +int64 CefByteReadHandler::Tell() { + base::AutoLock lock_scope(lock_); + return offset_; +} + +int CefByteReadHandler::Eof() { + base::AutoLock lock_scope(lock_); + return (offset_ >= size_); +} diff --git a/libcef_dll/wrapper/cef_closure_task.cc b/libcef_dll/wrapper/cef_closure_task.cc new file mode 100644 index 000000000..0b4939053 --- /dev/null +++ b/libcef_dll/wrapper/cef_closure_task.cc @@ -0,0 +1,42 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/wrapper/cef_closure_task.h" +#include "include/base/cef_callback.h" + +namespace { + +class CefClosureTask : public CefTask { + public: + explicit CefClosureTask(const base::Closure& closure) + : closure_(closure) { + } + + // CefTask method + virtual void Execute() OVERRIDE { + closure_.Run(); + closure_.Reset(); + } + + private: + base::Closure closure_; + + IMPLEMENT_REFCOUNTING(CefClosureTask); + DISALLOW_COPY_AND_ASSIGN(CefClosureTask); +}; + +} // namespace + +CefRefPtr CefCreateClosureTask(const base::Closure& closure) { + return new CefClosureTask(closure); +} + +bool CefPostTask(CefThreadId threadId, const base::Closure& closure) { + return CefPostTask(threadId, new CefClosureTask(closure)); +} + +bool CefPostDelayedTask(CefThreadId threadId, const base::Closure& closure, + int64 delay_ms) { + return CefPostDelayedTask(threadId, new CefClosureTask(closure), delay_ms); +} diff --git a/libcef_dll/wrapper/cef_message_router.cc b/libcef_dll/wrapper/cef_message_router.cc new file mode 100644 index 000000000..8966ffa52 --- /dev/null +++ b/libcef_dll/wrapper/cef_message_router.cc @@ -0,0 +1,1149 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/wrapper/cef_message_router.h" + +#include +#include + +#include "include/base/cef_bind.h" +#include "include/base/cef_macros.h" +#include "include/cef_task.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_helpers.h" +#include "libcef_dll/wrapper/cef_browser_info_map.h" + +namespace { + +// ID value reserved for internal use. +const int kReservedId = 0; + +// Appended to the JS function name for related IPC messages. +const char kMessageSuffix[] = "Msg"; + +// JS object member argument names for cefQuery. +const char kMemberRequest[] = "request"; +const char kMemberOnSuccess[] = "onSuccess"; +const char kMemberOnFailure[] = "onFailure"; +const char kMemberPersistent[] = "persistent"; + +// Default error information when a query is canceled. +const int kCanceledErrorCode = -1; +const char kCanceledErrorMessage[] = "The query has been canceled"; + +// Validate configuration settings. +bool ValidateConfig(CefMessageRouterConfig& config) { + // Must specify function names. + if (config.js_cancel_function.empty() || + config.js_query_function.empty()) { + return false; + } + + return true; +} + +// Helper template for generated ID values. +template +class IdGenerator { + public: + IdGenerator() : next_id_(kReservedId) {} + + T GetNextId() { + T id = ++next_id_; + if (id == kReservedId) // In case the integer value wraps. + id = ++next_id_; + return id; + } + + private: + T next_id_; + + DISALLOW_COPY_AND_ASSIGN(IdGenerator); +}; + +// Browser-side router implementation. +class CefMessageRouterBrowserSideImpl : public CefMessageRouterBrowserSide { + public: + // Implementation of the Callback interface. + class CallbackImpl : public CefMessageRouterBrowserSide::Callback { + public: + CallbackImpl(CefRefPtr router, + int browser_id, + int64 query_id, + bool persistent) + : router_(router), + browser_id_(browser_id), + query_id_(query_id), + persistent_(persistent) { + } + virtual ~CallbackImpl() { + // Hitting this DCHECK means that you didn't call Success or Failure + // on the Callback after returning true from Handler::OnQuery. You must + // call Failure to terminate persistent queries. + DCHECK(!router_); + } + + virtual void Success(const CefString& response) OVERRIDE { + if (!CefCurrentlyOn(TID_UI)) { + // Must execute on the UI thread to access member variables. + CefPostTask(TID_UI, + base::Bind(&CallbackImpl::Success, this, response)); + return; + } + + if (router_) { + CefPostTask(TID_UI, + base::Bind(&CefMessageRouterBrowserSideImpl::OnCallbackSuccess, + router_, browser_id_, query_id_, response)); + + if (!persistent_) { + // Non-persistent callbacks are only good for a single use. + router_ = NULL; + } + } + } + + virtual void Failure(int error_code, + const CefString& error_message) OVERRIDE { + if (!CefCurrentlyOn(TID_UI)) { + // Must execute on the UI thread to access member variables. + CefPostTask(TID_UI, + base::Bind(&CallbackImpl::Failure, this, + error_code, error_message)); + return; + } + + if (router_) { + CefPostTask(TID_UI, + base::Bind(&CefMessageRouterBrowserSideImpl::OnCallbackFailure, + router_, browser_id_, query_id_, error_code, + error_message)); + + // Failure always invalidates the callback. + router_ = NULL; + } + } + + void Detach() { + CEF_REQUIRE_UI_THREAD(); + router_ = NULL; + } + + private: + CefRefPtr router_; + const int browser_id_; + const int64 query_id_; + const bool persistent_; + + IMPLEMENT_REFCOUNTING(CallbackImpl); + }; + + explicit CefMessageRouterBrowserSideImpl(const CefMessageRouterConfig& config) + : config_(config), + query_message_name_( + config.js_query_function.ToString() + kMessageSuffix), + cancel_message_name_( + config.js_cancel_function.ToString() + kMessageSuffix) { + } + + virtual ~CefMessageRouterBrowserSideImpl() { + // There should be no pending queries when the router is deleted. + DCHECK(browser_query_info_map_.empty()); + } + + virtual bool AddHandler(Handler* handler, bool first) OVERRIDE { + CEF_REQUIRE_UI_THREAD(); + if (handler_set_.find(handler) == handler_set_.end()) { + handler_set_.insert( + first ? handler_set_.begin() : handler_set_.end(), handler); + return true; + } + return false; + } + + virtual bool RemoveHandler(Handler* handler) OVERRIDE { + CEF_REQUIRE_UI_THREAD(); + if (handler_set_.erase(handler) > 0) { + CancelPendingFor(NULL, handler, true); + return true; + } + return false; + } + + virtual void CancelPending(CefRefPtr browser, + Handler* handler) OVERRIDE { + CancelPendingFor(browser, handler, true); + } + + virtual int GetPendingCount(CefRefPtr browser, + Handler* handler) OVERRIDE { + CEF_REQUIRE_UI_THREAD(); + + if (browser_query_info_map_.empty()) + return 0; + + if (handler) { + // Need to iterate over each QueryInfo object to test the handler. + class Visitor : public BrowserQueryInfoMap::Visitor { + public: + explicit Visitor(Handler* handler) + : handler_(handler), + count_(0) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + if (info->handler == handler_) + count_++; + return true; + } + + int count() const { return count_; } + + private: + Handler* handler_; + int count_; + }; + + Visitor visitor(handler); + + if (browser.get()) { + // Count queries associated with the specified browser. + browser_query_info_map_.FindAll( + browser->GetIdentifier(), &visitor); + } else { + // Count all queries for all browsers. + browser_query_info_map_.FindAll(&visitor); + } + + return visitor.count(); + } else if (browser.get()) { + return static_cast( + browser_query_info_map_.size(browser->GetIdentifier())); + } else { + return static_cast(browser_query_info_map_.size()); + } + + return 0; + } + + virtual void OnBeforeClose(CefRefPtr browser) OVERRIDE { + CancelPendingFor(browser, NULL, false); + } + + virtual void OnRenderProcessTerminated( + CefRefPtr browser) OVERRIDE { + CancelPendingFor(browser, NULL, false); + } + + virtual void OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame) OVERRIDE { + if (frame->IsMain()) + CancelPendingFor(browser, NULL, false); + } + + virtual bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) OVERRIDE { + CEF_REQUIRE_UI_THREAD(); + + const std::string& message_name = message->GetName(); + if (message_name == query_message_name_) { + CefRefPtr args = message->GetArgumentList(); + DCHECK_EQ(args->GetSize(), 6U); + + const int64 frame_id = CefInt64Set(args->GetInt(0), args->GetInt(1)); + const int context_id = args->GetInt(2); + const int request_id = args->GetInt(3); + const CefString& request = args->GetString(4); + const bool persistent = args->GetBool(5); + + if (handler_set_.empty()) { + // No handlers so cancel the query. + CancelUnhandledQuery(browser, context_id, request_id); + return true; + } + + const int browser_id = browser->GetIdentifier(); + const int64 query_id = query_id_generator_.GetNextId(); + + CefRefPtr frame = browser->GetFrame(frame_id); + CefRefPtr callback( + new CallbackImpl(this, browser_id, query_id, persistent)); + + // Make a copy of the handler list in case the user adds or removes a + // handler while we're iterating. + HandlerSet handler_set = handler_set_; + + bool handled = false; + HandlerSet::const_iterator it_handler = handler_set.begin(); + for (; it_handler != handler_set.end(); ++it_handler) { + handled = (*it_handler)->OnQuery(browser, frame, query_id, request, + persistent, callback.get()); + if (handled) + break; + } + + // If the query isn't handled nothing should be keeping a reference to + // the callback. + DCHECK(handled || callback->HasOneRef()); + + if (handled) { + // Persist the query information until the callback executes. + // It's safe to do this here because the callback will execute + // asynchronously. + QueryInfo* info = new QueryInfo; + info->browser = browser; + info->frame_id = frame_id; + info->context_id = context_id; + info->request_id = request_id; + info->persistent = persistent; + info->callback = callback; + info->handler = *(it_handler); + browser_query_info_map_.Add(browser_id, query_id, info); + } else { + // Invalidate the callback. + callback->Detach(); + + // No one chose to handle the query so cancel it. + CancelUnhandledQuery(browser, context_id, request_id); + } + + return true; + } else if (message_name == cancel_message_name_) { + CefRefPtr args = message->GetArgumentList(); + DCHECK_EQ(args->GetSize(), 2U); + + const int browser_id = browser->GetIdentifier(); + const int context_id = args->GetInt(0); + const int request_id = args->GetInt(1); + + CancelPendingRequest(browser_id, context_id, request_id); + return true; + } + + return false; + } + + private: + // Structure representing a pending query. + struct QueryInfo { + // Browser and frame originated the query. + CefRefPtr browser; + int64 frame_id; + + // IDs that uniquely identify the query in the renderer process. These + // values are opaque to the browser process but must be returned with the + // response. + int context_id; + int request_id; + + // True if the query is persistent. + bool persistent; + + // Callback associated with the query that must be detached when the query + // is canceled. + CefRefPtr callback; + + // Handler that should be notified if the query is automatically canceled. + Handler* handler; + }; + + // Retrieve a QueryInfo object from the map based on the browser-side query + // ID. If |always_remove| is true then the QueryInfo object will always be + // removed from the map. Othewise, the QueryInfo object will only be removed + // if the query is non-persistent. If |removed| is true the caller is + // responsible for deleting the returned QueryInfo object. + QueryInfo* GetQueryInfo(int browser_id, + int64 query_id, + bool always_remove, + bool* removed) { + class Visitor : public BrowserQueryInfoMap::Visitor { + public: + explicit Visitor(bool always_remove) + : always_remove_(always_remove), + removed_(false) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + *remove = removed_ = (always_remove_ || !info->persistent); + return true; + } + + bool removed() const { return removed_; } + + private: + const bool always_remove_; + bool removed_; + }; + + Visitor visitor(always_remove); + QueryInfo* info = + browser_query_info_map_.Find(browser_id, query_id, &visitor); + if (info) + *removed = visitor.removed(); + return info; + } + + // Called by CallbackImpl on success. + void OnCallbackSuccess(int browser_id, + int64 query_id, + const CefString& response) { + CEF_REQUIRE_UI_THREAD(); + + bool removed; + QueryInfo* info = GetQueryInfo(browser_id, query_id, false, &removed); + if (info) { + SendQuerySuccess(info, response); + if (removed) + delete info; + } + } + + // Called by CallbackImpl on failure. + void OnCallbackFailure(int browser_id, + int64 query_id, + int error_code, + const CefString& error_message) { + CEF_REQUIRE_UI_THREAD(); + + bool removed; + QueryInfo* info = GetQueryInfo(browser_id, query_id, true, &removed); + if (info) { + SendQueryFailure(info, error_code, error_message); + DCHECK(removed); + delete info; + } + } + + void SendQuerySuccess(QueryInfo* info, + const CefString& response) { + SendQuerySuccess(info->browser, info->context_id, info->request_id, + response); + } + + void SendQuerySuccess(CefRefPtr browser, + int context_id, + int request_id, + const CefString& response) { + CefRefPtr message = + CefProcessMessage::Create(query_message_name_); + CefRefPtr args = message->GetArgumentList(); + args->SetInt(0, context_id); + args->SetInt(1, request_id); + args->SetBool(2, true); // Indicates a success result. + args->SetString(3, response); + browser->SendProcessMessage(PID_RENDERER, message); + } + + void SendQueryFailure(QueryInfo* info, + int error_code, + const CefString& error_message) { + SendQueryFailure(info->browser, info->context_id, info->request_id, + error_code, error_message); + } + + void SendQueryFailure(CefRefPtr browser, + int context_id, + int request_id, + int error_code, + const CefString& error_message) { + CefRefPtr message = + CefProcessMessage::Create(query_message_name_); + CefRefPtr args = message->GetArgumentList(); + args->SetInt(0, context_id); + args->SetInt(1, request_id); + args->SetBool(2, false); // Indicates a failure result. + args->SetInt(3, error_code); + args->SetString(4, error_message); + browser->SendProcessMessage(PID_RENDERER, message); + } + + // Cancel a query that has not been sent to a handler. + void CancelUnhandledQuery(CefRefPtr browser, int context_id, + int request_id) { + SendQueryFailure(browser, context_id, request_id, kCanceledErrorCode, + kCanceledErrorMessage); + } + + // Cancel a query that has already been sent to a handler. + void CancelQuery(int64 query_id, QueryInfo* info, bool notify_renderer) { + if (notify_renderer) + SendQueryFailure(info, kCanceledErrorCode, kCanceledErrorMessage); + + CefRefPtr frame = info->browser->GetFrame(info->frame_id); + info->handler->OnQueryCanceled(info->browser, frame, query_id); + + // Invalidate the callback. + info->callback->Detach(); + } + + // Cancel all pending queries associated with either |browser| or |handler|. + // If both |browser| and |handler| are NULL all pending queries will be + // canceled. Set |notify_renderer| to true if the renderer should be notified. + void CancelPendingFor(CefRefPtr browser, + Handler* handler, + bool notify_renderer) { + if (!CefCurrentlyOn(TID_UI)) { + // Must execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&CefMessageRouterBrowserSideImpl::CancelPendingFor, this, + browser, handler, notify_renderer)); + return; + } + + if (browser_query_info_map_.empty()) + return; + + class Visitor : public BrowserQueryInfoMap::Visitor { + public: + Visitor(CefMessageRouterBrowserSideImpl* router, + Handler* handler, + bool notify_renderer) + : router_(router), + handler_(handler), + notify_renderer_(notify_renderer) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + if (!handler_ || info->handler == handler_) { + *remove = true; + router_->CancelQuery(info_id, info, notify_renderer_); + delete info; + } + return true; + } + + private: + CefMessageRouterBrowserSideImpl* router_; + Handler* handler_; + const bool notify_renderer_; + }; + + Visitor visitor(this, handler, notify_renderer); + + if (browser.get()) { + // Cancel all queries associated with the specified browser. + browser_query_info_map_.FindAll( + browser->GetIdentifier(), &visitor); + } else { + // Cancel all queries for all browsers. + browser_query_info_map_.FindAll(&visitor); + } + } + + // Cancel a query based on the renderer-side IDs. If |request_id| is + // kReservedId all requests associated with |context_id| will be canceled. + void CancelPendingRequest(int browser_id, int context_id, int request_id) { + class Visitor : public BrowserQueryInfoMap::Visitor { + public: + Visitor(CefMessageRouterBrowserSideImpl* router, + int context_id, + int request_id) + : router_(router), + context_id_(context_id), + request_id_(request_id) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + if (info->context_id == context_id_ && + (request_id_ == kReservedId || info->request_id == request_id_)) { + *remove = true; + router_->CancelQuery(info_id, info, false); + delete info; + + // Stop iterating if only canceling a single request. + return (request_id_ == kReservedId); + } + return true; + } + + private: + CefMessageRouterBrowserSideImpl* router_; + const int context_id_; + const int request_id_; + }; + + Visitor visitor(this, context_id, request_id); + browser_query_info_map_.FindAll(browser_id, &visitor); + } + + const CefMessageRouterConfig config_; + const std::string query_message_name_; + const std::string cancel_message_name_; + + IdGenerator query_id_generator_; + + // Set of currently registered handlers. An entry is added when a handler is + // registered and removed when a handler is unregistered. + typedef std::set HandlerSet; + HandlerSet handler_set_; + + // Map of query ID to QueryInfo instance. An entry is added when a Handler + // indicates that it will handle the query and removed when either the query + // is completed via the Callback, the query is explicitly canceled from the + // renderer process, or the associated context is (or will be) released. + typedef CefBrowserInfoMap BrowserQueryInfoMap; + BrowserQueryInfoMap browser_query_info_map_; + + DISALLOW_COPY_AND_ASSIGN(CefMessageRouterBrowserSideImpl); +}; + +// Renderer-side router implementation. +class CefMessageRouterRendererSideImpl : public CefMessageRouterRendererSide { + public: + class V8HandlerImpl : public CefV8Handler { + public: + V8HandlerImpl( + CefRefPtr router, + const CefMessageRouterConfig& config) + : router_(router), + config_(config), + context_id_(kReservedId) { + } + + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + if (name == config_.js_query_function) { + if (arguments.size() != 1 || !arguments[0]->IsObject()) { + exception = "Invalid arguments; expecting a single object"; + return true; + } + + CefRefPtr arg = arguments[0]; + + CefRefPtr requestVal = arg->GetValue(kMemberRequest); + if (!requestVal.get() || !requestVal->IsString()) { + exception = "Invalid arguments; object member '"+ + std::string(kMemberRequest) +"' is required and must " + "have type string"; + return true; + } + + CefRefPtr successVal = NULL; + if (arg->HasValue(kMemberOnSuccess)) { + successVal = arg->GetValue(kMemberOnSuccess); + if (!successVal->IsFunction()) { + exception = "Invalid arguments; object member '"+ + std::string(kMemberOnSuccess) +"' must have type " + "function"; + return true; + } + } + + CefRefPtr failureVal = NULL; + if (arg->HasValue(kMemberOnFailure)) { + failureVal = arg->GetValue(kMemberOnFailure); + if (!failureVal->IsFunction()) { + exception = "Invalid arguments; object member '"+ + std::string(kMemberOnFailure) +"' must have type " + "function"; + return true; + } + } + + CefRefPtr persistentVal = NULL; + if (arg->HasValue(kMemberPersistent)) { + persistentVal = arg->GetValue(kMemberPersistent); + if (!persistentVal->IsBool()) { + exception = "Invalid arguments; object member '"+ + std::string(kMemberPersistent) +"' must have type " + "boolean"; + return true; + } + } + + CefRefPtr context = CefV8Context::GetCurrentContext(); + const int context_id = GetIDForContext(context); + const int64 frame_id = context->GetFrame()->GetIdentifier(); + const bool persistent = + (persistentVal.get() && persistentVal->GetBoolValue()); + + const int request_id = router_->SendQuery( + context->GetBrowser(), frame_id, context_id, + requestVal->GetStringValue(), persistent, successVal, failureVal); + retval = CefV8Value::CreateInt(request_id); + return true; + } else if (name == config_.js_cancel_function) { + if (arguments.size() != 1 || !arguments[0]->IsInt()) { + exception = "Invalid arguments; expecting a single integer"; + return true; + } + + bool result = false; + const int request_id = arguments[0]->GetIntValue(); + if (request_id != kReservedId) { + CefRefPtr context = CefV8Context::GetCurrentContext(); + const int context_id = GetIDForContext(context); + const int64 frame_id = context->GetFrame()->GetIdentifier(); + + result = router_->SendCancel(context->GetBrowser(), frame_id, + context_id, request_id); + } + retval = CefV8Value::CreateBool(result); + return true; + } + + return false; + } + + private: + // Don't create the context ID until it's actually needed. + int GetIDForContext(CefRefPtr context) { + if (context_id_ == kReservedId) + context_id_ = router_->CreateIDForContext(context); + return context_id_; + } + + CefRefPtr router_; + const CefMessageRouterConfig config_; + int context_id_; + + IMPLEMENT_REFCOUNTING(V8HandlerImpl); + }; + + explicit CefMessageRouterRendererSideImpl(const CefMessageRouterConfig& config) + : config_(config), + query_message_name_( + config.js_query_function.ToString() + kMessageSuffix), + cancel_message_name_( + config.js_cancel_function.ToString() + kMessageSuffix) { + } + + virtual ~CefMessageRouterRendererSideImpl() { + } + + virtual int GetPendingCount(CefRefPtr browser, + CefRefPtr context) OVERRIDE { + CEF_REQUIRE_RENDERER_THREAD(); + + if (browser_request_info_map_.empty()) + return 0; + + if (context.get()) { + const int context_id = GetIDForContext(context, false); + if (context_id == kReservedId) + return 0; // Nothing associated with the specified context. + + // Need to iterate over each RequestInfo object to test the context. + class Visitor : public BrowserRequestInfoMap::Visitor { + public: + explicit Visitor(int context_id) + : context_id_(context_id), + count_(0) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + if (info_id.first == context_id_) + count_++; + return true; + } + + int count() const { return count_; } + + private: + int context_id_; + int count_; + }; + + Visitor visitor(context_id); + + if (browser.get()) { + // Count requests associated with the specified browser. + browser_request_info_map_.FindAll( + browser->GetIdentifier(), &visitor); + } else { + // Count all requests for all browsers. + browser_request_info_map_.FindAll(&visitor); + } + + return visitor.count(); + } else if (browser.get()) { + return static_cast( + browser_request_info_map_.size(browser->GetIdentifier())); + } else { + return static_cast(browser_request_info_map_.size()); + } + + return 0; + } + + virtual void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE { + CEF_REQUIRE_RENDERER_THREAD(); + + // Register function handlers with the 'window' object. + CefRefPtr window = context->GetGlobal(); + + CefRefPtr handler = new V8HandlerImpl(this, config_); + CefV8Value::PropertyAttribute attributes = + static_cast( + V8_PROPERTY_ATTRIBUTE_READONLY | + V8_PROPERTY_ATTRIBUTE_DONTENUM | + V8_PROPERTY_ATTRIBUTE_DONTDELETE); + + // Add the query function. + CefRefPtr query_func = + CefV8Value::CreateFunction(config_.js_query_function, handler.get()); + window->SetValue(config_.js_query_function, query_func, attributes); + + // Add the cancel function. + CefRefPtr cancel_func = + CefV8Value::CreateFunction(config_.js_cancel_function, handler.get()); + window->SetValue(config_.js_cancel_function, cancel_func, attributes); + } + + virtual void OnContextReleased(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE { + CEF_REQUIRE_RENDERER_THREAD(); + + // Get the context ID and remove the context from the map. + const int context_id = GetIDForContext(context, true); + if (context_id != kReservedId) { + // Cancel all pending requests for the context. + SendCancel(browser, frame->GetIdentifier(), context_id, kReservedId); + } + } + + virtual bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) OVERRIDE { + CEF_REQUIRE_RENDERER_THREAD(); + + const std::string& message_name = message->GetName(); + if (message_name == query_message_name_) { + CefRefPtr args = message->GetArgumentList(); + DCHECK_GT(args->GetSize(), 3U); + + const int context_id = args->GetInt(0); + const int request_id = args->GetInt(1); + bool is_success = args->GetBool(2); + + if (is_success) { + DCHECK_EQ(args->GetSize(), 4U); + const CefString& response = args->GetString(3); + CefPostTask(TID_RENDERER, + base::Bind( + &CefMessageRouterRendererSideImpl::ExecuteSuccessCallback, this, + browser->GetIdentifier(), context_id, request_id, response)); + } else { + DCHECK_EQ(args->GetSize(), 5U); + int error_code = args->GetInt(3); + const CefString& error_message = args->GetString(4); + CefPostTask(TID_RENDERER, + base::Bind( + &CefMessageRouterRendererSideImpl::ExecuteFailureCallback, this, + browser->GetIdentifier(), context_id, request_id, error_code, + error_message)); + } + + return true; + } + + return false; + } + + private: + // Structure representing a pending request. + struct RequestInfo { + // True if the request is persistent. + bool persistent; + + // Success callback function. May be NULL. + CefRefPtr success_callback; + + // Failure callback function. May be NULL. + CefRefPtr failure_callback; + }; + + // Retrieve a RequestInfo object from the map based on the renderer-side + // IDs. If |always_remove| is true then the RequestInfo object will always be + // removed from the map. Othewise, the RequestInfo object will only be removed + // if the query is non-persistent. If |removed| is true the caller is + // responsible for deleting the returned QueryInfo object. + RequestInfo* GetRequestInfo(int browser_id, + int request_id, + int context_id, + bool always_remove, + bool* removed) { + class Visitor : public BrowserRequestInfoMap::Visitor { + public: + explicit Visitor(bool always_remove) + : always_remove_(always_remove), + removed_(false) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + *remove = removed_ = (always_remove_ || !info->persistent); + return true; + } + + bool removed() const { return removed_; } + + private: + const bool always_remove_; + bool removed_; + }; + + Visitor visitor(always_remove); + RequestInfo* info = browser_request_info_map_.Find(browser_id, + std::make_pair(request_id, context_id), &visitor); + if (info) + *removed = visitor.removed(); + return info; + } + + // Returns the new request ID. + int SendQuery(CefRefPtr browser, + int64 frame_id, + int context_id, + const CefString& request, + bool persistent, + CefRefPtr success_callback, + CefRefPtr failure_callback) { + CEF_REQUIRE_RENDERER_THREAD(); + + const int request_id = request_id_generator_.GetNextId(); + + RequestInfo* info = new RequestInfo; + info->persistent = persistent; + info->success_callback = success_callback; + info->failure_callback = failure_callback; + browser_request_info_map_.Add(browser->GetIdentifier(), + std::make_pair(context_id, request_id), info); + + CefRefPtr message = + CefProcessMessage::Create(query_message_name_); + + CefRefPtr args = message->GetArgumentList(); + args->SetInt(0, CefInt64GetLow(frame_id)); + args->SetInt(1, CefInt64GetHigh(frame_id)); + args->SetInt(2, context_id); + args->SetInt(3, request_id); + args->SetString(4, request); + args->SetBool(5, persistent); + + browser->SendProcessMessage(PID_BROWSER, message); + + return request_id; + } + + // If |request_id| is kReservedId all requests associated with |context_id| + // will be canceled, otherwise only the specified |request_id| will be + // canceled. Returns true if any request was canceled. + bool SendCancel(CefRefPtr browser, + int64 frame_id, + int context_id, + int request_id) { + CEF_REQUIRE_RENDERER_THREAD(); + + const int browser_id = browser->GetIdentifier(); + + int cancel_count = 0; + if (request_id != kReservedId) { + // Cancel a single request. + bool removed; + RequestInfo* info = + GetRequestInfo(browser_id, context_id, request_id, true, &removed); + if (info) { + DCHECK(removed); + delete info; + cancel_count = 1; + } + } else { + // Cancel all requests with the specified context ID. + class Visitor : public BrowserRequestInfoMap::Visitor { + public: + explicit Visitor(int context_id) + : context_id_(context_id), + cancel_count_(0) {} + + virtual bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) OVERRIDE { + if (info_id.first == context_id_) { + *remove = true; + delete info; + cancel_count_++; + } + return true; + } + + int cancel_count() const { return cancel_count_; } + + private: + const int context_id_; + int cancel_count_; + }; + + Visitor visitor(context_id); + browser_request_info_map_.FindAll(browser_id, &visitor); + cancel_count = visitor.cancel_count(); + } + + if (cancel_count > 0) { + CefRefPtr message = + CefProcessMessage::Create(cancel_message_name_); + + CefRefPtr args = message->GetArgumentList(); + args->SetInt(0, context_id); + args->SetInt(1, request_id); + + browser->SendProcessMessage(PID_BROWSER, message); + return true; + } + + return false; + } + + // Execute the onSuccess JavaScript callback. + void ExecuteSuccessCallback(int browser_id, int context_id, int request_id, + const CefString& response) { + CEF_REQUIRE_RENDERER_THREAD(); + + bool removed; + RequestInfo* info = + GetRequestInfo(browser_id, context_id, request_id, false, &removed); + if (!info) + return; + + CefRefPtr context = GetContextByID(context_id); + if (context && info->success_callback) { + CefV8ValueList args; + args.push_back(CefV8Value::CreateString(response)); + info->success_callback->ExecuteFunctionWithContext(context, NULL, args); + } + + if (removed) + delete info; + } + + // Execute the onFailure JavaScript callback. + void ExecuteFailureCallback(int browser_id, int context_id, int request_id, + int error_code, const CefString& error_message) { + CEF_REQUIRE_RENDERER_THREAD(); + + bool removed; + RequestInfo* info = + GetRequestInfo(browser_id, context_id, request_id, true, &removed); + if (!info) + return; + + CefRefPtr context = GetContextByID(context_id); + if (context && info->failure_callback) { + CefV8ValueList args; + args.push_back(CefV8Value::CreateInt(error_code)); + args.push_back(CefV8Value::CreateString(error_message)); + info->failure_callback->ExecuteFunctionWithContext(context, NULL, args); + } + + DCHECK(removed); + delete info; + } + + int CreateIDForContext(CefRefPtr context) { + CEF_REQUIRE_RENDERER_THREAD(); + + // The context should not already have an associated ID. + DCHECK_EQ(GetIDForContext(context, false), kReservedId); + + const int context_id = context_id_generator_.GetNextId(); + context_map_.insert(std::make_pair(context_id, context)); + return context_id; + } + + // Retrieves the existing ID value associated with the specified |context|. + // If |remove| is true the context will also be removed from the map. + int GetIDForContext(CefRefPtr context, bool remove) { + CEF_REQUIRE_RENDERER_THREAD(); + + ContextMap::iterator it = context_map_.begin(); + for (; it != context_map_.end(); ++it) { + if (it->second->IsSame(context)) { + int context_id = it->first; + if (remove) + context_map_.erase(it); + return context_id; + } + } + + return kReservedId; + } + + CefRefPtr GetContextByID(int context_id) { + CEF_REQUIRE_RENDERER_THREAD(); + + ContextMap::const_iterator it = context_map_.find(context_id); + if (it != context_map_.end()) + return it->second; + return NULL; + } + + const CefMessageRouterConfig config_; + const std::string query_message_name_; + const std::string cancel_message_name_; + + IdGenerator context_id_generator_; + IdGenerator request_id_generator_; + + // Map of (request ID, context ID) to RequestInfo for pending queries. An + // entry is added when a request is initiated via the bound function and + // removed when either the request completes, is canceled via the bound + // function, or the associated context is released. + typedef CefBrowserInfoMap, RequestInfo*> + BrowserRequestInfoMap; + BrowserRequestInfoMap browser_request_info_map_; + + // Map of context ID to CefV8Context for existing contexts. An entry is added + // when a bound function is executed for the first time in the context and + // removed when the context is released. + typedef std::map > ContextMap; + ContextMap context_map_; + + DISALLOW_COPY_AND_ASSIGN(CefMessageRouterRendererSideImpl); +}; + +} // namespace + +CefMessageRouterConfig::CefMessageRouterConfig() + : js_query_function("cefQuery"), + js_cancel_function("cefQueryCancel") { +} + +// static +CefRefPtr CefMessageRouterBrowserSide::Create( + const CefMessageRouterConfig& config) { + CefMessageRouterConfig validated_config = config; + if (!ValidateConfig(validated_config)) + return NULL; + return new CefMessageRouterBrowserSideImpl(validated_config); +} + +// static +CefRefPtr CefMessageRouterRendererSide::Create( + const CefMessageRouterConfig& config) { + CefMessageRouterConfig validated_config = config; + if (!ValidateConfig(validated_config)) + return NULL; + return new CefMessageRouterRendererSideImpl(validated_config); +} diff --git a/libcef_dll/wrapper/cef_stream_resource_handler.cc b/libcef_dll/wrapper/cef_stream_resource_handler.cc new file mode 100644 index 000000000..f7e9868ac --- /dev/null +++ b/libcef_dll/wrapper/cef_stream_resource_handler.cc @@ -0,0 +1,203 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/wrapper/cef_stream_resource_handler.h" + +#include + +#include "include/base/cef_bind.h" +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_callback.h" +#include "include/cef_request.h" +#include "include/cef_stream.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_helpers.h" + +// Class that represents a readable/writable character buffer. +class CefStreamResourceHandler::Buffer { + public: + Buffer() + : size_(0), + bytes_requested_(0), + bytes_written_(0), + bytes_read_(0) { + } + + void Reset(int new_size) { + if (size_ < new_size) { + size_ = new_size; + buffer_.reset(new char[size_]); + DCHECK(buffer_); + } + bytes_requested_ = new_size; + bytes_written_ = 0; + bytes_read_ = 0; + } + + bool IsEmpty() const { + return (bytes_written_ == 0); + } + + bool CanRead() const { + return (bytes_read_ < bytes_written_); + } + + int WriteTo(void* data_out, int bytes_to_read) { + const int write_size = + std::min(bytes_to_read, bytes_written_ - bytes_read_); + if (write_size > 0) { + memcpy(data_out, buffer_ .get() + bytes_read_, write_size); + bytes_read_ += write_size; + } + return write_size; + } + + int ReadFrom(CefRefPtr reader) { + // Read until the buffer is full or until Read() returns 0 to indicate no + // more data. + int bytes_read; + do { + bytes_read = static_cast( + reader->Read(buffer_.get() + bytes_written_, 1, + bytes_requested_ - bytes_written_)); + bytes_written_ += bytes_read; + } while (bytes_read != 0 && bytes_written_ < bytes_requested_); + + return bytes_written_; + } + + private: + scoped_ptr buffer_; + int size_; + int bytes_requested_; + int bytes_written_; + int bytes_read_; + + DISALLOW_COPY_AND_ASSIGN(Buffer); +}; + +CefStreamResourceHandler::CefStreamResourceHandler( + const CefString& mime_type, + CefRefPtr stream) + : status_code_(200), + status_text_("OK"), + mime_type_(mime_type), + stream_(stream) +#ifndef NDEBUG + , buffer_owned_by_file_thread_(false) +#endif +{ + DCHECK(!mime_type_.empty()); + DCHECK(stream_.get()); + read_on_file_thread_ = stream_->MayBlock(); +} + +CefStreamResourceHandler::CefStreamResourceHandler( + int status_code, + const CefString& status_text, + const CefString& mime_type, + CefResponse::HeaderMap header_map, + CefRefPtr stream) + : status_code_(status_code), + status_text_(status_text), + mime_type_(mime_type), + header_map_(header_map), + stream_(stream) { + DCHECK(!mime_type_.empty()); + DCHECK(stream_.get()); + read_on_file_thread_ = stream_->MayBlock(); +} + +CefStreamResourceHandler::~CefStreamResourceHandler() { +} + +bool CefStreamResourceHandler::ProcessRequest(CefRefPtr request, + CefRefPtr callback) { + callback->Continue(); + return true; +} + +void CefStreamResourceHandler::GetResponseHeaders( + CefRefPtr response, + int64& response_length, + CefString& redirectUrl) { + response->SetStatus(status_code_); + response->SetStatusText(status_text_); + response->SetMimeType(mime_type_); + + if (!header_map_.empty()) + response->SetHeaderMap(header_map_); + + response_length = -1; +} + +bool CefStreamResourceHandler::ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) { + DCHECK_GT(bytes_to_read, 0); + + if (read_on_file_thread_) { +#ifndef NDEBUG + DCHECK(!buffer_owned_by_file_thread_); +#endif + if (buffer_ && (buffer_->CanRead() || buffer_->IsEmpty())) { + if (buffer_->CanRead()) { + // Provide data from the buffer. + bytes_read = buffer_->WriteTo(data_out, bytes_to_read); + return (bytes_read > 0); + } else { + // End of the steam. + bytes_read = 0; + return false; + } + } else { + // Perform another read on the file thread. + bytes_read = 0; +#ifndef NDEBUG + buffer_owned_by_file_thread_ = true; +#endif + CefPostTask(TID_FILE, + base::Bind(&CefStreamResourceHandler::ReadOnFileThread, this, + bytes_to_read, callback)); + return true; + } + } else { + // Read until the buffer is full or until Read() returns 0 to indicate no + // more data. + bytes_read = 0; + int read = 0; + do { + read = static_cast( + stream_->Read(static_cast(data_out) + bytes_read, 1, + bytes_to_read - bytes_read)); + bytes_read += read; + } while (read != 0 && bytes_read < bytes_to_read); + + return (bytes_read > 0); + } +} + +void CefStreamResourceHandler::Cancel() { +} + +void CefStreamResourceHandler::ReadOnFileThread( + int bytes_to_read, + CefRefPtr callback) { + CEF_REQUIRE_FILE_THREAD(); +#ifndef NDEBUG + DCHECK(buffer_owned_by_file_thread_); +#endif + + if (!buffer_) + buffer_.reset(new Buffer()); + buffer_->Reset(bytes_to_read); + buffer_->ReadFrom(stream_); + +#ifndef NDEBUG + buffer_owned_by_file_thread_ = false; +#endif + callback->Continue(); +} diff --git a/libcef_dll/wrapper/cef_xml_object.cc b/libcef_dll/wrapper/cef_xml_object.cc new file mode 100644 index 000000000..7e0d1712a --- /dev/null +++ b/libcef_dll/wrapper/cef_xml_object.cc @@ -0,0 +1,453 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/wrapper/cef_xml_object.h" + +#include + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/cef_stream.h" + +namespace { + +class CefXmlObjectLoader { + public: + explicit CefXmlObjectLoader(CefRefPtr root_object) + : root_object_(root_object) { + } + + bool Load(CefRefPtr stream, + CefXmlReader::EncodingType encodingType, + const CefString& URI) { + CefRefPtr reader( + CefXmlReader::Create(stream, encodingType, URI)); + if (!reader.get()) + return false; + + bool ret = reader->MoveToNextNode(); + if (ret) { + CefRefPtr cur_object(root_object_), new_object; + CefXmlObject::ObjectVector queue; + int cur_depth, value_depth = -1; + CefXmlReader::NodeType cur_type; + std::stringstream cur_value; + bool last_has_ns = false; + + queue.push_back(root_object_); + + do { + cur_depth = reader->GetDepth(); + if (value_depth >= 0 && cur_depth > value_depth) { + // The current node has already been parsed as part of a value. + continue; + } + + cur_type = reader->GetType(); + if (cur_type == XML_NODE_ELEMENT_START) { + if (cur_depth == value_depth) { + // Add to the current value. + cur_value << std::string(reader->GetOuterXml()); + continue; + } else if (last_has_ns && reader->GetPrefix().empty()) { + if (!cur_object->HasChildren()) { + // Start a new value because the last element has a namespace and + // this element does not. + value_depth = cur_depth; + cur_value << std::string(reader->GetOuterXml()); + } else { + // Value following a child element is not allowed. + std::stringstream ss; + ss << "Value following child element, line " << + reader->GetLineNumber(); + load_error_ = ss.str(); + ret = false; + break; + } + } else { + // Start a new element. + new_object = new CefXmlObject(reader->GetQualifiedName()); + cur_object->AddChild(new_object); + last_has_ns = !reader->GetPrefix().empty(); + + if (!reader->IsEmptyElement()) { + // The new element potentially has a value and/or children, so + // set the current object and add the object to the queue. + cur_object = new_object; + queue.push_back(cur_object); + } + + if (reader->HasAttributes() && reader->MoveToFirstAttribute()) { + // Read all object attributes. + do { + new_object->SetAttributeValue(reader->GetQualifiedName(), + reader->GetValue()); + } while (reader->MoveToNextAttribute()); + reader->MoveToCarryingElement(); + } + } + } else if (cur_type == XML_NODE_ELEMENT_END) { + if (cur_depth == value_depth) { + // Ending an element that is already in the value. + continue; + } else if (cur_depth < value_depth) { + // Done with parsing the value portion of the current element. + cur_object->SetValue(cur_value.str()); + cur_value.str(""); + value_depth = -1; + } + + // Pop the current element from the queue. + queue.pop_back(); + + if (queue.empty() || + cur_object->GetName() != reader->GetQualifiedName()) { + // Open tag without close tag or close tag without open tag should + // never occur (the parser catches this error). + NOTREACHED(); + std::stringstream ss; + ss << "Mismatched end tag for " << + std::string(cur_object->GetName()) << + ", line " << reader->GetLineNumber(); + load_error_ = ss.str(); + ret = false; + break; + } + + // Set the current object to the previous object in the queue. + cur_object = queue.back().get(); + } else if (cur_type == XML_NODE_TEXT || cur_type == XML_NODE_CDATA || + cur_type == XML_NODE_ENTITY_REFERENCE) { + if (cur_depth == value_depth) { + // Add to the current value. + cur_value << std::string(reader->GetValue()); + } else if (!cur_object->HasChildren()) { + // Start a new value. + value_depth = cur_depth; + cur_value << std::string(reader->GetValue()); + } else { + // Value following a child element is not allowed. + std::stringstream ss; + ss << "Value following child element, line " << + reader->GetLineNumber(); + load_error_ = ss.str(); + ret = false; + break; + } + } + } while (reader->MoveToNextNode()); + } + + if (reader->HasError()) { + load_error_ = reader->GetError(); + return false; + } + + return ret; + } + + CefString GetLoadError() { return load_error_; } + + private: + CefString load_error_; + CefRefPtr root_object_; + + DISALLOW_COPY_AND_ASSIGN(CefXmlObjectLoader); +}; + +} // namespace + +CefXmlObject::CefXmlObject(const CefString& name) + : name_(name), parent_(NULL) { +} + +CefXmlObject::~CefXmlObject() { +} + +bool CefXmlObject::Load(CefRefPtr stream, + CefXmlReader::EncodingType encodingType, + const CefString& URI, CefString* loadError) { + Clear(); + + CefXmlObjectLoader loader(this); + if (!loader.Load(stream, encodingType, URI)) { + if (loadError) + *loadError = loader.GetLoadError(); + return false; + } + return true; +} + +void CefXmlObject::Set(CefRefPtr object) { + DCHECK(object.get()); + + Clear(); + + name_ = object->GetName(); + Append(object, true); +} + +void CefXmlObject::Append(CefRefPtr object, + bool overwriteAttributes) { + DCHECK(object.get()); + + if (object->HasChildren()) { + ObjectVector children; + object->GetChildren(children); + ObjectVector::const_iterator it = children.begin(); + for (; it != children.end(); ++it) + AddChild((*it)->Duplicate()); + } + + if (object->HasAttributes()) { + AttributeMap attributes; + object->GetAttributes(attributes); + AttributeMap::const_iterator it = attributes.begin(); + for (; it != attributes.end(); ++it) { + if (overwriteAttributes || !HasAttribute(it->first)) + SetAttributeValue(it->first, it->second); + } + } +} + +CefRefPtr CefXmlObject::Duplicate() { + CefRefPtr new_obj; + { + base::AutoLock lock_scope(lock_); + new_obj = new CefXmlObject(name_); + new_obj->Append(this, true); + } + return new_obj; +} + +void CefXmlObject::Clear() { + ClearChildren(); + ClearAttributes(); +} + +CefString CefXmlObject::GetName() { + CefString name; + { + base::AutoLock lock_scope(lock_); + name = name_; + } + return name; +} + +bool CefXmlObject::SetName(const CefString& name) { + DCHECK(!name.empty()); + if (name.empty()) + return false; + + base::AutoLock lock_scope(lock_); + name_ = name; + return true; +} + +bool CefXmlObject::HasParent() { + base::AutoLock lock_scope(lock_); + return (parent_ != NULL); +} + +CefRefPtr CefXmlObject::GetParent() { + CefRefPtr parent; + { + base::AutoLock lock_scope(lock_); + parent = parent_; + } + return parent; +} + +bool CefXmlObject::HasValue() { + base::AutoLock lock_scope(lock_); + return !value_.empty(); +} + +CefString CefXmlObject::GetValue() { + CefString value; + { + base::AutoLock lock_scope(lock_); + value = value_; + } + return value; +} + +bool CefXmlObject::SetValue(const CefString& value) { + base::AutoLock lock_scope(lock_); + DCHECK(children_.empty()); + if (!children_.empty()) + return false; + value_ = value; + return true; +} + +bool CefXmlObject::HasAttributes() { + base::AutoLock lock_scope(lock_); + return !attributes_.empty(); +} + +size_t CefXmlObject::GetAttributeCount() { + base::AutoLock lock_scope(lock_); + return attributes_.size(); +} + +bool CefXmlObject::HasAttribute(const CefString& name) { + if (name.empty()) + return false; + + base::AutoLock lock_scope(lock_); + AttributeMap::const_iterator it = attributes_.find(name); + return (it != attributes_.end()); +} + +CefString CefXmlObject::GetAttributeValue(const CefString& name) { + DCHECK(!name.empty()); + CefString value; + if (!name.empty()) { + base::AutoLock lock_scope(lock_); + AttributeMap::const_iterator it = attributes_.find(name); + if (it != attributes_.end()) + value = it->second; + } + return value; +} + +bool CefXmlObject::SetAttributeValue(const CefString& name, + const CefString& value) { + DCHECK(!name.empty()); + if (name.empty()) + return false; + + base::AutoLock lock_scope(lock_); + AttributeMap::iterator it = attributes_.find(name); + if (it != attributes_.end()) { + it->second = value; + } else { + attributes_.insert(std::make_pair(name, value)); + } + return true; +} + +size_t CefXmlObject::GetAttributes(AttributeMap& attributes) { + base::AutoLock lock_scope(lock_); + attributes = attributes_; + return attributes_.size(); +} + +void CefXmlObject::ClearAttributes() { + base::AutoLock lock_scope(lock_); + attributes_.clear(); +} + +bool CefXmlObject::HasChildren() { + base::AutoLock lock_scope(lock_); + return !children_.empty(); +} + +size_t CefXmlObject::GetChildCount() { + base::AutoLock lock_scope(lock_); + return children_.size(); +} + +bool CefXmlObject::HasChild(CefRefPtr child) { + DCHECK(child.get()); + + base::AutoLock lock_scope(lock_); + ObjectVector::const_iterator it = children_.begin(); + for (; it != children_.end(); ++it) { + if ((*it).get() == child.get()) + return true; + } + return false; +} + +bool CefXmlObject::AddChild(CefRefPtr child) { + DCHECK(child.get()); + if (!child.get()) + return false; + + CefRefPtr parent = child->GetParent(); + DCHECK(!parent); + if (parent) + return false; + + base::AutoLock lock_scope(lock_); + + children_.push_back(child); + child->SetParent(this); + return true; +} + +bool CefXmlObject::RemoveChild(CefRefPtr child) { + DCHECK(child.get()); + + base::AutoLock lock_scope(lock_); + ObjectVector::iterator it = children_.begin(); + for (; it != children_.end(); ++it) { + if ((*it).get() == child.get()) { + children_.erase(it); + child->SetParent(NULL); + return true; + } + } + return false; +} + +size_t CefXmlObject::GetChildren(ObjectVector& children) { + base::AutoLock lock_scope(lock_); + children = children_; + return children_.size(); +} + +void CefXmlObject::ClearChildren() { + base::AutoLock lock_scope(lock_); + ObjectVector::iterator it = children_.begin(); + for (; it != children_.end(); ++it) + (*it)->SetParent(NULL); + children_.clear(); +} + +CefRefPtr CefXmlObject::FindChild(const CefString& name) { + DCHECK(!name.empty()); + if (name.empty()) + return NULL; + + base::AutoLock lock_scope(lock_); + ObjectVector::const_iterator it = children_.begin(); + for (; it != children_.end(); ++it) { + if ((*it)->GetName() == name) + return (*it); + } + return NULL; +} + +size_t CefXmlObject::FindChildren(const CefString& name, + ObjectVector& children) { + DCHECK(!name.empty()); + if (name.empty()) + return 0; + + size_t ct = 0; + + base::AutoLock lock_scope(lock_); + ObjectVector::const_iterator it = children_.begin(); + for (; it != children_.end(); ++it) { + if ((*it)->GetName() == name) { + children.push_back(*it); + ct++; + } + } + return ct; +} + +void CefXmlObject::SetParent(CefXmlObject* parent) { + base::AutoLock lock_scope(lock_); + if (parent) { + DCHECK(parent_ == NULL); + parent_ = parent; + } else { + DCHECK(parent_ != NULL); + parent_ = NULL; + } +} diff --git a/libcef_dll/wrapper/cef_zip_archive.cc b/libcef_dll/wrapper/cef_zip_archive.cc new file mode 100644 index 000000000..05448a428 --- /dev/null +++ b/libcef_dll/wrapper/cef_zip_archive.cc @@ -0,0 +1,174 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "include/wrapper/cef_zip_archive.h" + +#include + +#include "include/base/cef_logging.h" +#include "include/base/cef_macros.h" +#include "include/base/cef_scoped_ptr.h" +#include "include/cef_stream.h" +#include "include/cef_zip_reader.h" +#include "include/wrapper/cef_byte_read_handler.h" + +#if defined(OS_LINUX) +#include +#endif + +namespace { + +// Convert |str| to lowercase in a Unicode-friendly manner. +CefString ToLower(const CefString& str) { + std::wstring wstr = str; + std::transform(wstr.begin(), wstr.end(), wstr.begin(), towlower); + return wstr; +} + +class CefZipFile : public CefZipArchive::File { + public: + CefZipFile() : data_size_(0) {} + + bool Initialize(size_t data_size) { + data_.reset(new unsigned char[data_size]); + if (data_) { + data_size_ = data_size; + return true; + } else { + DLOG(ERROR) << "Failed to allocate " << data_size << " bytes of memory"; + data_size_ = 0; + return false; + } + } + + virtual const unsigned char* GetData() const OVERRIDE { return data_.get(); } + + virtual size_t GetDataSize() const OVERRIDE { return data_size_; } + + virtual CefRefPtr GetStreamReader() const OVERRIDE { + CefRefPtr handler( + new CefByteReadHandler(data_.get(), data_size_, + const_cast(this))); + return CefStreamReader::CreateForHandler(handler); + } + + unsigned char* data() { return data_.get(); } + + private: + size_t data_size_; + scoped_ptr data_; + + IMPLEMENT_REFCOUNTING(CefZipFile); + DISALLOW_COPY_AND_ASSIGN(CefZipFile); +}; + +} // namespace + +// CefZipArchive implementation + +CefZipArchive::CefZipArchive() { +} + +CefZipArchive::~CefZipArchive() { +} + +size_t CefZipArchive::Load(CefRefPtr stream, + const CefString& password, + bool overwriteExisting) { + base::AutoLock lock_scope(lock_); + + CefRefPtr reader(CefZipReader::Create(stream)); + if (!reader.get()) + return 0; + + if (!reader->MoveToFirstFile()) + return 0; + + CefRefPtr contents; + FileMap::iterator it; + size_t count = 0; + + do { + const size_t size = static_cast(reader->GetFileSize()); + if (size == 0) { + // Skip directories and empty files. + continue; + } + + if (!reader->OpenFile(password)) + break; + + const CefString& name = ToLower(reader->GetFileName()); + + it = contents_.find(name); + if (it != contents_.end()) { + if (overwriteExisting) + contents_.erase(it); + else // Skip files that already exist. + continue; + } + + CefRefPtr contents = new CefZipFile(); + if (!contents->Initialize(size)) + continue; + unsigned char* data = contents->data(); + size_t offset = 0; + + // Read the file contents. + do { + offset += reader->ReadFile(data + offset, size - offset); + } while (offset < size && !reader->Eof()); + + DCHECK(offset == size); + + reader->CloseFile(); + count++; + + // Add the file to the map. + contents_.insert(std::make_pair(name, contents.get())); + } while (reader->MoveToNextFile()); + + return count; +} + +void CefZipArchive::Clear() { + base::AutoLock lock_scope(lock_); + contents_.clear(); +} + +size_t CefZipArchive::GetFileCount() const { + base::AutoLock lock_scope(lock_); + return contents_.size(); +} + +bool CefZipArchive::HasFile(const CefString& fileName) const { + base::AutoLock lock_scope(lock_); + FileMap::const_iterator it = contents_.find(ToLower(fileName)); + return (it != contents_.end()); +} + +CefRefPtr CefZipArchive::GetFile( + const CefString& fileName) const { + base::AutoLock lock_scope(lock_); + FileMap::const_iterator it = contents_.find(ToLower(fileName)); + if (it != contents_.end()) + return it->second; + return NULL; +} + +bool CefZipArchive::RemoveFile(const CefString& fileName) { + base::AutoLock lock_scope(lock_); + FileMap::iterator it = contents_.find(ToLower(fileName)); + if (it != contents_.end()) { + contents_.erase(it); + return true; + } + return false; +} + +size_t CefZipArchive::GetFiles(FileMap& map) const { + base::AutoLock lock_scope(lock_); + map = contents_; + return contents_.size(); +} diff --git a/libcef_dll/wrapper/libcef_dll_wrapper.cc b/libcef_dll/wrapper/libcef_dll_wrapper.cc new file mode 100644 index 000000000..a3cfa30cf --- /dev/null +++ b/libcef_dll/wrapper/libcef_dll_wrapper.cc @@ -0,0 +1,737 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "include/cef_app.h" +#include "include/capi/cef_app_capi.h" +#include "include/cef_geolocation.h" +#include "include/capi/cef_geolocation_capi.h" +#include "include/cef_origin_whitelist.h" +#include "include/capi/cef_origin_whitelist_capi.h" +#include "include/cef_path_util.h" +#include "include/capi/cef_path_util_capi.h" +#include "include/cef_process_util.h" +#include "include/capi/cef_process_util_capi.h" +#include "include/cef_scheme.h" +#include "include/capi/cef_scheme_capi.h" +#include "include/cef_task.h" +#include "include/capi/cef_task_capi.h" +#include "include/cef_trace.h" +#include "include/capi/cef_trace_capi.h" +#include "include/cef_url.h" +#include "include/capi/cef_url_capi.h" +#include "include/cef_v8.h" +#include "include/capi/cef_v8_capi.h" +#include "include/cef_web_plugin.h" +#include "include/capi/cef_web_plugin_capi.h" +#include "include/cef_version.h" +#include "libcef_dll/cpptoc/app_cpptoc.h" +#include "libcef_dll/cpptoc/browser_process_handler_cpptoc.h" +#include "libcef_dll/cpptoc/completion_callback_cpptoc.h" +#include "libcef_dll/cpptoc/context_menu_handler_cpptoc.h" +#include "libcef_dll/cpptoc/cookie_visitor_cpptoc.h" +#include "libcef_dll/cpptoc/domvisitor_cpptoc.h" +#include "libcef_dll/cpptoc/dialog_handler_cpptoc.h" +#include "libcef_dll/cpptoc/display_handler_cpptoc.h" +#include "libcef_dll/cpptoc/download_handler_cpptoc.h" +#include "libcef_dll/cpptoc/drag_handler_cpptoc.h" +#include "libcef_dll/cpptoc/end_tracing_callback_cpptoc.h" +#include "libcef_dll/cpptoc/find_handler_cpptoc.h" +#include "libcef_dll/cpptoc/focus_handler_cpptoc.h" +#include "libcef_dll/cpptoc/geolocation_handler_cpptoc.h" +#include "libcef_dll/cpptoc/get_geolocation_callback_cpptoc.h" +#include "libcef_dll/cpptoc/jsdialog_handler_cpptoc.h" +#include "libcef_dll/cpptoc/keyboard_handler_cpptoc.h" +#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h" +#include "libcef_dll/cpptoc/load_handler_cpptoc.h" +#include "libcef_dll/cpptoc/navigation_entry_visitor_cpptoc.h" +#include "libcef_dll/cpptoc/print_handler_cpptoc.h" +#include "libcef_dll/cpptoc/read_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_process_handler_cpptoc.h" +#include "libcef_dll/cpptoc/request_handler_cpptoc.h" +#include "libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h" +#include "libcef_dll/cpptoc/resource_handler_cpptoc.h" +#include "libcef_dll/cpptoc/run_file_dialog_callback_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h" +#include "libcef_dll/cpptoc/string_visitor_cpptoc.h" +#include "libcef_dll/cpptoc/task_cpptoc.h" +#include "libcef_dll/cpptoc/urlrequest_client_cpptoc.h" +#include "libcef_dll/cpptoc/v8accessor_cpptoc.h" +#include "libcef_dll/cpptoc/v8handler_cpptoc.h" +#include "libcef_dll/cpptoc/web_plugin_info_visitor_cpptoc.h" +#include "libcef_dll/cpptoc/web_plugin_unstable_callback_cpptoc.h" +#include "libcef_dll/cpptoc/write_handler_cpptoc.h" +#include "libcef_dll/ctocpp/allow_certificate_error_callback_ctocpp.h" +#include "libcef_dll/ctocpp/auth_callback_ctocpp.h" +#include "libcef_dll/ctocpp/before_download_callback_ctocpp.h" +#include "libcef_dll/ctocpp/binary_value_ctocpp.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/browser_host_ctocpp.h" +#include "libcef_dll/ctocpp/callback_ctocpp.h" +#include "libcef_dll/ctocpp/command_line_ctocpp.h" +#include "libcef_dll/ctocpp/context_menu_params_ctocpp.h" +#include "libcef_dll/ctocpp/domdocument_ctocpp.h" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" +#include "libcef_dll/ctocpp/dictionary_value_ctocpp.h" +#include "libcef_dll/ctocpp/download_item_ctocpp.h" +#include "libcef_dll/ctocpp/download_item_callback_ctocpp.h" +#include "libcef_dll/ctocpp/drag_data_ctocpp.h" +#include "libcef_dll/ctocpp/file_dialog_callback_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/geolocation_callback_ctocpp.h" +#include "libcef_dll/ctocpp/jsdialog_callback_ctocpp.h" +#include "libcef_dll/ctocpp/list_value_ctocpp.h" +#include "libcef_dll/ctocpp/menu_model_ctocpp.h" +#include "libcef_dll/ctocpp/navigation_entry_ctocpp.h" +#include "libcef_dll/ctocpp/print_dialog_callback_ctocpp.h" +#include "libcef_dll/ctocpp/print_job_callback_ctocpp.h" +#include "libcef_dll/ctocpp/print_settings_ctocpp.h" +#include "libcef_dll/ctocpp/process_message_ctocpp.h" +#include "libcef_dll/ctocpp/quota_callback_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_registrar_ctocpp.h" +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/stream_writer_ctocpp.h" +#include "libcef_dll/ctocpp/task_runner_ctocpp.h" +#include "libcef_dll/ctocpp/urlrequest_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" +#include "libcef_dll/ctocpp/v8exception_ctocpp.h" +#include "libcef_dll/ctocpp/v8stack_frame_ctocpp.h" +#include "libcef_dll/ctocpp/v8stack_trace_ctocpp.h" +#include "libcef_dll/ctocpp/v8value_ctocpp.h" +#include "libcef_dll/ctocpp/web_plugin_info_ctocpp.h" +#include "libcef_dll/ctocpp/xml_reader_ctocpp.h" +#include "libcef_dll/ctocpp/zip_reader_ctocpp.h" +#include "libcef_dll/transfer_util.h" + +// Define used to facilitate parsing. +#define CEF_GLOBAL + + +// GLOBAL METHODS - Body may be edited by hand. + +CEF_GLOBAL int CefExecuteProcess(const CefMainArgs& args, + CefRefPtr application, void* windows_sandbox_info) { + const char* api_hash = cef_api_hash(0); + if (strcmp(api_hash, CEF_API_HASH_PLATFORM)) { + // The libcef API hash does not match the current header API hash. + NOTREACHED(); + return 0; + } + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: application, windows_sandbox_info + + // Execute + int _retval = cef_execute_process( + &args, + CefAppCppToC::Wrap(application), + windows_sandbox_info); + + // Return type: simple + return _retval; +} + +CEF_GLOBAL bool CefInitialize(const CefMainArgs& args, + const CefSettings& settings, CefRefPtr application, + void* windows_sandbox_info) { + const char* api_hash = cef_api_hash(0); + if (strcmp(api_hash, CEF_API_HASH_PLATFORM)) { + // The libcef API hash does not match the current header API hash. + NOTREACHED(); + return false; + } + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: application, windows_sandbox_info + + // Execute + int _retval = cef_initialize( + &args, + &settings, + CefAppCppToC::Wrap(application), + windows_sandbox_info); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL void CefShutdown() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_shutdown(); + +#ifndef NDEBUG + // Check that all wrapper objects have been destroyed + DCHECK(base::AtomicRefCountIsZero( + &CefAllowCertificateErrorCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefAuthCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefBeforeDownloadCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefBinaryValueCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefBrowserCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefBrowserHostCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefBrowserProcessHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefCompletionCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefContextMenuHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefContextMenuParamsCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefCookieVisitorCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDOMDocumentCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDOMNodeCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDOMVisitorCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDialogHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDictionaryValueCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDisplayHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDownloadHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDownloadItemCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefDownloadItemCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDragDataCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefDragHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefEndTracingCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFileDialogCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFindHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFocusHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefFrameCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefGeolocationCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefGeolocationHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefGetGeolocationCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefJSDialogCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefJSDialogHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefKeyboardHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefLifeSpanHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefListValueCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefLoadHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefMenuModelCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefNavigationEntryCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefNavigationEntryVisitorCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintDialogCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintJobCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefPrintSettingsCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefProcessMessageCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefQuotaCallbackCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefReadHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefRenderHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefRenderProcessHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefRequestHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefResourceBundleHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefResourceHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefRunFileDialogCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefSchemeHandlerFactoryCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefSchemeRegistrarCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefStreamReaderCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefStreamWriterCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefStringVisitorCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefTaskCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefTaskRunnerCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefURLRequestCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefURLRequestClientCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8AccessorCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8ContextCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8ExceptionCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8HandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8StackFrameCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8StackTraceCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefV8ValueCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefWebPluginInfoCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefWebPluginInfoVisitorCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero( + &CefWebPluginUnstableCallbackCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefWriteHandlerCppToC::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefXmlReaderCToCpp::DebugObjCt)); + DCHECK(base::AtomicRefCountIsZero(&CefZipReaderCToCpp::DebugObjCt)); +#endif // !NDEBUG +} + +CEF_GLOBAL void CefDoMessageLoopWork() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_do_message_loop_work(); +} + +CEF_GLOBAL void CefRunMessageLoop() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_run_message_loop(); +} + +CEF_GLOBAL void CefQuitMessageLoop() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_quit_message_loop(); +} + +CEF_GLOBAL void CefSetOSModalLoop(bool osModalLoop) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_set_osmodal_loop( + osModalLoop); +} + +CEF_GLOBAL bool CefGetGeolocation( + CefRefPtr callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return false; + + // Execute + int _retval = cef_get_geolocation( + CefGetGeolocationCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefAddCrossOriginWhitelistEntry(const CefString& source_origin, + const CefString& target_protocol, const CefString& target_domain, + bool allow_target_subdomains) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: source_origin; type: string_byref_const + DCHECK(!source_origin.empty()); + if (source_origin.empty()) + return false; + // Verify param: target_protocol; type: string_byref_const + DCHECK(!target_protocol.empty()); + if (target_protocol.empty()) + return false; + // Unverified params: target_domain + + // Execute + int _retval = cef_add_cross_origin_whitelist_entry( + source_origin.GetStruct(), + target_protocol.GetStruct(), + target_domain.GetStruct(), + allow_target_subdomains); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefRemoveCrossOriginWhitelistEntry( + const CefString& source_origin, const CefString& target_protocol, + const CefString& target_domain, bool allow_target_subdomains) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: source_origin; type: string_byref_const + DCHECK(!source_origin.empty()); + if (source_origin.empty()) + return false; + // Verify param: target_protocol; type: string_byref_const + DCHECK(!target_protocol.empty()); + if (target_protocol.empty()) + return false; + // Unverified params: target_domain + + // Execute + int _retval = cef_remove_cross_origin_whitelist_entry( + source_origin.GetStruct(), + target_protocol.GetStruct(), + target_domain.GetStruct(), + allow_target_subdomains); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefClearCrossOriginWhitelist() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = cef_clear_cross_origin_whitelist(); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefGetPath(PathKey key, CefString& path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = cef_get_path( + key, + path.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefLaunchProcess(CefRefPtr command_line) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: command_line; type: refptr_same + DCHECK(command_line.get()); + if (!command_line.get()) + return false; + + // Execute + int _retval = cef_launch_process( + CefCommandLineCToCpp::Unwrap(command_line)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefRegisterSchemeHandlerFactory(const CefString& scheme_name, + const CefString& domain_name, + CefRefPtr factory) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: scheme_name; type: string_byref_const + DCHECK(!scheme_name.empty()); + if (scheme_name.empty()) + return false; + // Unverified params: domain_name, factory + + // Execute + int _retval = cef_register_scheme_handler_factory( + scheme_name.GetStruct(), + domain_name.GetStruct(), + CefSchemeHandlerFactoryCppToC::Wrap(factory)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefClearSchemeHandlerFactories() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = cef_clear_scheme_handler_factories(); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefCurrentlyOn(CefThreadId threadId) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = cef_currently_on( + threadId); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefPostTask(CefThreadId threadId, CefRefPtr task) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: task; type: refptr_diff + DCHECK(task.get()); + if (!task.get()) + return false; + + // Execute + int _retval = cef_post_task( + threadId, + CefTaskCppToC::Wrap(task)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefPostDelayedTask(CefThreadId threadId, + CefRefPtr task, int64 delay_ms) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: task; type: refptr_diff + DCHECK(task.get()); + if (!task.get()) + return false; + + // Execute + int _retval = cef_post_delayed_task( + threadId, + CefTaskCppToC::Wrap(task), + delay_ms); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefBeginTracing(const CefString& categories, + CefRefPtr callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: categories, callback + + // Execute + int _retval = cef_begin_tracing( + categories.GetStruct(), + CefCompletionCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefEndTracing(const CefString& tracing_file, + CefRefPtr callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: tracing_file, callback + + // Execute + int _retval = cef_end_tracing( + tracing_file.GetStruct(), + CefEndTracingCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL int64 CefNowFromSystemTraceTime() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = cef_now_from_system_trace_time(); + + // Return type: simple + return _retval; +} + +CEF_GLOBAL bool CefParseURL(const CefString& url, CefURLParts& parts) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return false; + + // Execute + int _retval = cef_parse_url( + url.GetStruct(), + &parts); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL bool CefCreateURL(const CefURLParts& parts, CefString& url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = cef_create_url( + &parts, + url.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL CefString CefGetMimeType(const CefString& extension) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: extension; type: string_byref_const + DCHECK(!extension.empty()); + if (extension.empty()) + return CefString(); + + // Execute + cef_string_userfree_t _retval = cef_get_mime_type( + extension.GetStruct()); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CEF_GLOBAL void CefGetExtensionsForMimeType(const CefString& mime_type, + std::vector& extensions) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: mime_type; type: string_byref_const + DCHECK(!mime_type.empty()); + if (mime_type.empty()) + return; + + // Translate param: extensions; type: string_vec_byref + cef_string_list_t extensionsList = cef_string_list_alloc(); + DCHECK(extensionsList); + if (extensionsList) + transfer_string_list_contents(extensions, extensionsList); + + // Execute + cef_get_extensions_for_mime_type( + mime_type.GetStruct(), + extensionsList); + + // Restore param:extensions; type: string_vec_byref + if (extensionsList) { + extensions.clear(); + transfer_string_list_contents(extensionsList, extensions); + cef_string_list_free(extensionsList); + } +} + +CEF_GLOBAL bool CefRegisterExtension(const CefString& extension_name, + const CefString& javascript_code, CefRefPtr handler) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: extension_name; type: string_byref_const + DCHECK(!extension_name.empty()); + if (extension_name.empty()) + return false; + // Verify param: javascript_code; type: string_byref_const + DCHECK(!javascript_code.empty()); + if (javascript_code.empty()) + return false; + // Unverified params: handler + + // Execute + int _retval = cef_register_extension( + extension_name.GetStruct(), + javascript_code.GetStruct(), + CefV8HandlerCppToC::Wrap(handler)); + + // Return type: bool + return _retval?true:false; +} + +CEF_GLOBAL void CefVisitWebPluginInfo( + CefRefPtr visitor) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: visitor; type: refptr_diff + DCHECK(visitor.get()); + if (!visitor.get()) + return; + + // Execute + cef_visit_web_plugin_info( + CefWebPluginInfoVisitorCppToC::Wrap(visitor)); +} + +CEF_GLOBAL void CefRefreshWebPlugins() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_refresh_web_plugins(); +} + +CEF_GLOBAL void CefAddWebPluginPath(const CefString& path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + + // Execute + cef_add_web_plugin_path( + path.GetStruct()); +} + +CEF_GLOBAL void CefAddWebPluginDirectory(const CefString& dir) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: dir; type: string_byref_const + DCHECK(!dir.empty()); + if (dir.empty()) + return; + + // Execute + cef_add_web_plugin_directory( + dir.GetStruct()); +} + +CEF_GLOBAL void CefRemoveWebPluginPath(const CefString& path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + + // Execute + cef_remove_web_plugin_path( + path.GetStruct()); +} + +CEF_GLOBAL void CefUnregisterInternalWebPlugin(const CefString& path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + + // Execute + cef_unregister_internal_web_plugin( + path.GetStruct()); +} + +CEF_GLOBAL void CefForceWebPluginShutdown(const CefString& path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + + // Execute + cef_force_web_plugin_shutdown( + path.GetStruct()); +} + +CEF_GLOBAL void CefRegisterWebPluginCrash(const CefString& path) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + + // Execute + cef_register_web_plugin_crash( + path.GetStruct()); +} + +CEF_GLOBAL void CefIsWebPluginUnstable(const CefString& path, + CefRefPtr callback) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: path; type: string_byref_const + DCHECK(!path.empty()); + if (path.empty()) + return; + // Verify param: callback; type: refptr_diff + DCHECK(callback.get()); + if (!callback.get()) + return; + + // Execute + cef_is_web_plugin_unstable( + path.GetStruct(), + CefWebPluginUnstableCallbackCppToC::Wrap(callback)); +} + diff --git a/libcef_dll/wrapper/libcef_dll_wrapper2.cc b/libcef_dll/wrapper/libcef_dll_wrapper2.cc new file mode 100644 index 000000000..dc8ba7b02 --- /dev/null +++ b/libcef_dll/wrapper/libcef_dll_wrapper2.cc @@ -0,0 +1,4 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + diff --git a/macros.cmake.in b/macros.cmake.in new file mode 100644 index 000000000..b5d74f0b5 --- /dev/null +++ b/macros.cmake.in @@ -0,0 +1,272 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +# +# Shared macros. +# + +# Append platform specific sources to a list of sources. +macro(APPEND_PLATFORM_SOURCES name_of_list) + if(OS_LINUX AND ${name_of_list}_LINUX) + list(APPEND ${name_of_list} ${${name_of_list}_LINUX}) + endif() + if(OS_POSIX AND ${name_of_list}_POSIX) + list(APPEND ${name_of_list} ${${name_of_list}_POSIX}) + endif() + if(OS_WINDOWS AND ${name_of_list}_WINDOWS) + list(APPEND ${name_of_list} ${${name_of_list}_WINDOWS}) + endif() + if(OS_MACOSX AND ${name_of_list}_MACOSX) + list(APPEND ${name_of_list} ${${name_of_list}_MACOSX}) + endif() +endmacro() + +# Add a logical target that can be used to link the specified libraries into an +# executable target. +macro(ADD_LOGICAL_TARGET target debug_lib release_lib) + add_library(${target} ${CEF_LIBTYPE} IMPORTED) + set_target_properties(${target} PROPERTIES + IMPORTED_LOCATION "${release_lib}" + IMPORTED_LOCATION_DEBUG "${debug_lib}" + IMPORTED_LOCATION_RELEASE "${release_lib}" + ) +endmacro() + +# Determine the target output directory based on platform and generator. +macro(SET_CEF_TARGET_OUT_DIR) + if(${CMAKE_GENERATOR} STREQUAL "Ninja") + # Ninja does not create a subdirectory named after the configuration. + set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}") + elseif(OS_LINUX) + set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}") + else() + set(CEF_TARGET_OUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/$") + endif() +endmacro() + +# Copy a list of files from one directory to another. Relative files paths are maintained. +macro(COPY_FILES target file_list source_dir target_dir) + foreach(FILENAME ${file_list}) + set(source_file ${source_dir}/${FILENAME}) + set(target_file ${target_dir}/${FILENAME}) + if(IS_DIRECTORY ${source_file}) + add_custom_command( + TARGET ${target} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_directory "${source_file}" "${target_file}" + VERBATIM + ) + else() + add_custom_command( + TARGET ${target} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${source_file}" "${target_file}" + VERBATIM + ) + endif() + endforeach() +endmacro() + +# Rename a directory replacing the target if it already exists. +macro(RENAME_DIRECTORY target source_dir target_dir) + add_custom_command( + TARGET ${target} + POST_BUILD + # Remove the target directory if it already exists. + COMMAND ${CMAKE_COMMAND} -E remove_directory "${target_dir}" + # Rename the source directory to target directory. + COMMAND ${CMAKE_COMMAND} -E rename "${source_dir}" "${target_dir}" + VERBATIM + ) +endmacro() + + +# +# Linux macros. +# + +if(OS_LINUX) + +# Use pkg-config to find Linux libraries and update compiler/linker variables. +macro(FIND_LINUX_LIBRARIES libraries) + # Read pkg-config info into variables. + execute_process(COMMAND pkg-config --cflags ${libraries} OUTPUT_VARIABLE FLL_CFLAGS) + execute_process(COMMAND pkg-config --libs-only-L --libs-only-other ${libraries} OUTPUT_VARIABLE FLL_LDFLAGS) + execute_process(COMMAND pkg-config --libs-only-l ${libraries} OUTPUT_VARIABLE FLL_LIBS) + + # Strip leading and trailing whitepspace. + STRING(STRIP "${FLL_CFLAGS}" FLL_CFLAGS) + STRING(STRIP "${FLL_LDFLAGS}" FLL_LDFLAGS) + STRING(STRIP "${FLL_LIBS}" FLL_LIBS) + + # Update the variables. + set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${FLL_CFLAGS}") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${FLL_CFLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${FLL_LDFLAGS}") + set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${FLL_LDFLAGS}") + set(CEF_STANDARD_LIBS "${CEF_STANDARD_LIBS} ${FLL_LIBS}") +endmacro() + +# Set SUID permissions on the specified executable. +macro(SET_LINUX_SUID_PERMISSIONS target executable) + add_custom_command( + TARGET ${target} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E echo "" + COMMAND ${CMAKE_COMMAND} -E echo "*** Run the following command manually to set SUID permissions ***" + COMMAND ${CMAKE_COMMAND} -E echo "EXE=\"${executable}\" && sudo -- chown root:root $EXE && sudo -- chmod 4755 $EXE" + COMMAND ${CMAKE_COMMAND} -E echo "" + VERBATIM + ) +endmacro() + +endif(OS_LINUX) + + +# +# Mac OS X macros. +# + +if(OS_MACOSX) + +# Set Xcode target properties. +function(SET_XCODE_TARGET_PROPERTIES target) + set_target_properties(${target} PROPERTIES + XCODE_ATTRIBUTE_ALWAYS_SEARCH_USER_PATHS NO + XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "gnu++11" # -std=gnu++11 + XCODE_ATTRIBUTE_CLANG_LINK_OBJC_RUNTIME NO # -fno-objc-link-runtime + XCODE_ATTRIBUTE_CLANG_WARN_OBJC_MISSING_PROPERTY_SYNTHESIS YES # -Wobjc-missing-property-synthesis + XCODE_ATTRIBUTE_COPY_PHASE_STRIP NO + XCODE_ATTRIBUTE_DEAD_CODE_STRIPPING[variant=Release] YES # -Wl,-dead_strip + XCODE_ATTRIBUTE_GCC_C_LANGUAGE_STANDARD "c99" # -std=c99 + XCODE_ATTRIBUTE_GCC_CW_ASM_SYNTAX NO # No -fasm-blocks + XCODE_ATTRIBUTE_GCC_DYNAMIC_NO_PIC NO + XCODE_ATTRIBUTE_GCC_ENABLE_CPP_EXCEPTIONS NO # -fno-exceptions + XCODE_ATTRIBUTE_GCC_ENABLE_CPP_RTTI NO # -fno-rtti + XCODE_ATTRIBUTE_GCC_ENABLE_PASCAL_STRINGS NO # No -mpascal-strings + XCODE_ATTRIBUTE_GCC_INLINES_ARE_PRIVATE_EXTERN YES # -fvisibility-inlines-hidden + XCODE_ATTRIBUTE_GCC_OBJC_CALL_CXX_CDTORS YES # -fobjc-call-cxx-cdtors + XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN YES # -fvisibility=hidden + XCODE_ATTRIBUTE_GCC_THREADSAFE_STATICS NO # -fno-threadsafe-statics + XCODE_ATTRIBUTE_GCC_TREAT_WARNINGS_AS_ERRORS YES # -Werror + XCODE_ATTRIBUTE_GCC_VERSION "com.apple.compilers.llvm.clang.1_0" + XCODE_ATTRIBUTE_GCC_WARN_ABOUT_MISSING_NEWLINE YES # -Wnewline-eof + XCODE_ATTRIBUTE_USE_HEADERMAP NO + OSX_ARCHITECTURES_DEBUG "${CMAKE_OSX_ARCHITECTURES}" + OSX_ARCHITECTURES_RELEASE "${CMAKE_OSX_ARCHITECTURES}" + ) +endfunction() + +# Override default add_library function. +function(add_library name) + _add_library(${name} ${ARGN}) + SET_XCODE_TARGET_PROPERTIES(${name}) +endfunction() + +# Override default add_executable function. +function(add_executable name) + _add_executable(${name} ${ARGN}) + SET_XCODE_TARGET_PROPERTIES(${name}) +endfunction() + +# Fix the framework link in the helper executable. +macro(FIX_MACOSX_HELPER_FRAMEWORK_LINK target app_path) + add_custom_command(TARGET ${target} + POST_BUILD + COMMAND install_name_tool -change "@executable_path/Chromium Embedded Framework" + "@executable_path/../../../../Frameworks/Chromium Embedded Framework.framework/Chromium Embedded Framework" + "${app_path}/Contents/MacOS/${target}" + VERBATIM + ) +endmacro() + +# Fix the framework link in the main executable. +macro(FIX_MACOSX_MAIN_FRAMEWORK_LINK target app_path) + add_custom_command(TARGET ${target} + POST_BUILD + COMMAND install_name_tool -change "@executable_path/Chromium Embedded Framework" + "@executable_path/../Frameworks/Chromium Embedded Framework.framework/Chromium Embedded Framework" + "${app_path}/Contents/MacOS/${target}" + VERBATIM + ) +endmacro() + +# Make the other helper app bundles. +macro(MAKE_MACOSX_HELPERS target app_path) + add_custom_command(TARGET ${target} + POST_BUILD + # The exported variables need to be set for generators other than Xcode. + COMMAND export BUILT_PRODUCTS_DIR=${app_path} && + export CONTENTS_FOLDER_PATH=/Contents && + tools/make_more_helpers.sh "Frameworks" "${target}" + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + VERBATIM + ) +endmacro() + +# Manually process and copy over resource files. +macro(COPY_MACOSX_RESOURCES resource_list prefix_list target source_dir app_path) + foreach(FILENAME ${resource_list}) + # Remove one or more prefixes from the source paths. + set(TARGET_FILENAME "${FILENAME}") + foreach(PREFIX ${prefix_list}) + string(REGEX REPLACE "^.*${PREFIX}" "" TARGET_FILENAME ${TARGET_FILENAME}) + endforeach() + + # Determine the absolute source and target paths. + set(TARGET_PATH "${app_path}/Contents/Resources/${TARGET_FILENAME}") + if(IS_ABSOLUTE ${FILENAME}) + set(SOURCE_PATH ${FILENAME}) + else() + set(SOURCE_PATH "${source_dir}/${FILENAME}") + endif() + + if(${FILENAME} MATCHES ".xib$") + # Change the target file extension. + string(REGEX REPLACE ".xib$" ".nib" TARGET_PATH ${TARGET_PATH}) + + get_filename_component(TARGET_DIRECTORY ${TARGET_PATH} PATH) + add_custom_command( + TARGET ${target} + POST_BUILD + # Create the target directory. + COMMAND ${CMAKE_COMMAND} -E make_directory "${TARGET_DIRECTORY}" + # Compile the XIB file to a NIB. + COMMAND /usr/bin/ibtool --output-format binary1 --compile "${TARGET_PATH}" "${SOURCE_PATH}" + VERBATIM + ) + elseif(NOT ${TARGET_FILENAME} STREQUAL "Info.plist") + # Copy the file as-is. + add_custom_command( + TARGET ${target} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy "${SOURCE_PATH}" "${TARGET_PATH}" + VERBATIM + ) + endif() + endforeach() +endmacro() + +endif(OS_MACOSX) + + +# +# Windows macros. +# + +if(OS_WINDOWS) + +# Add custom manifest files to an executable target. +macro(ADD_WINDOWS_MANIFEST target) + add_custom_command( + TARGET ${target} + POST_BUILD + COMMAND "mt.exe" -nologo + -manifest \"${CMAKE_CURRENT_SOURCE_DIR}/${target}.exe.manifest\" \"${CMAKE_CURRENT_SOURCE_DIR}/compatibility.manifest\" + -outputresource:"${CEF_TARGET_OUT_DIR}/${target}.exe"\;\#1 + COMMENT "Adding manifest..." + ) +endmacro() + +endif(OS_WINDOWS) diff --git a/patch/README.txt b/patch/README.txt new file mode 100644 index 000000000..f96fe36a4 --- /dev/null +++ b/patch/README.txt @@ -0,0 +1,20 @@ +There may be instances where CEF requires changes to the Chromium/WebKit code +base that are not desired by the Chromium/WebKit projects as a whole. To address +this situation the CEF project adds a patch capability as part of the CEF GYP +project generation step. The patch capability works as follows: + +1. The CEF developer creates one or more patch files containing all required + changes to the Chromium/WebKit code base and places those patch files in the + "patches" subdirectory. +2. The CEF developer adds an entry for each patch file in the "patch.cfg" file. +3. CEF applies the patches to the Chromium/WebKit source tree using the + patcher.py tool in the tools directory. If necessary the patcher.py tool + also rewrites the "patch_state.h" file which defines the CEF_PATCHES_APPLIED + preprocessor value. + +To disable automatic application of patches to the Chromium/WebKit code base +create an empty "NOPATCH" file in the "patch" directory. Sections of the CEF +code base that otherwise require patches will be disabled using the +CEF_PATCHES_APPLIED preprocessor value defined in the "patch_state.h" file. Be +warned that not applying all required patches may break important CEF +functionality. diff --git a/patch/patch.cfg b/patch/patch.cfg new file mode 100644 index 000000000..301725ee9 --- /dev/null +++ b/patch/patch.cfg @@ -0,0 +1,130 @@ +# Each map in the list associates a patch file name with a target path and +# optional condition. All paths in the patch file must be relative to the +# target path. Each map should include a comment linking to the code review +# or bug report that the patch relates to. If a condition is provided the +# patch will only be applied if an environment variable with the specified +# name exists. + +patches = [ + { + # Necessary for grit integration + 'name': 'gritsettings', + 'path': '../tools/gritsettings/', + }, + { + # Fix Xcode 4 build on OS X Lion. + # http://codereview.chromium.org/8086022/ + 'name': 'build', + 'path': '../build/', + }, + { + # Support loading of password protected zip archives. + # http://code.google.com/p/chromiumembedded/issues/detail?id=496 + 'name': 'zlib', + 'path': '../third_party/zlib/', + }, + { + # Avoid MessageLoop assertion on OS X. + # http://code.google.com/p/chromiumembedded/issues/detail?id=443 + 'name': 'message_loop_443', + 'path': '../base/message_loop/', + }, + { + # Fix ninja output for localization directories on OS X. + # http://code.google.com/p/gyp/issues/detail?id=331 + 'name': 'gyp_331', + 'path': '../tools/gyp/pylib/', + }, + { + # Enable popups in offscreen rendering on OS X. + 'name': 'webkit_popups', + 'path': '../third_party/WebKit/', + }, + { + # Fix export of UnderlayOpenGLHostingWindow for 64-bit OS X builds. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1051 + 'name': 'underlay_1051', + 'path': '../ui/base/cocoa/', + }, + { + # Allow specification of a parent window handle for Widget creation. + # https://code.google.com/p/chromiumembedded/issues/detail?id=180 + 'name': 'views_widget_180', + 'path': '../ui/views/widget/', + }, + { + # Allow continued use of ContentRendererClient::HandleNavigation. + # https://code.google.com/p/chromiumembedded/issues/detail?id=1129 + 'name': 'content_nav_1129', + 'path': '../content/', + }, + { + # Allow customization of the background color with Aura. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1161 + # + # Allow specification of a custom WebContentsView. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1257 + 'name': 'public_browser_1161_1257', + 'path': '../content/public/browser/', + }, + { + # Allow creation of a custom SoftwareOutputDevice. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1368 + 'name': 'compositor_1368', + 'path': '../', + }, + { + # Allow specification of a custom WebContentsView. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1257 + 'name': 'browser_web_contents_1257', + 'path': '../content/browser/web_contents/', + }, + { + # Allow specification of a custom WebContentsView. + # This change is required due to chrome_browser_process_stub.h indirectly + # including chrome/browser/ui/browser.h on OS X. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1257 + 'name': 'chrome_browser_1257', + 'path': '../chrome/browser/', + }, + { + # Allow customization of the WebView background color. + # http://code.google.com/p/chromiumembedded/issues/detail?id=1161 + # https://codereview.chromium.org/228603007/ + 'name': 'prefs_content_1161', + 'path': '../content/', + }, + { + # Revert Blink revision 177068 changes due to _web_drawFocusRingWithFrame + # unrecognized selector error during offscreen rendering of popups. + # https://code.google.com/p/chromium/issues/detail?id=328814 + 'name': 'webkit_platform_mac_328814', + 'path': '../third_party/WebKit/Source/platform/mac/', + }, + { + # Fix drag&drop of combined text and URL data on Linux/Aura. + # https://codereview.chromium.org/208313009 + 'name': 'ui_dragdrop_355390', + 'path': '../ui/base/dragdrop/', + }, + { + # Fix AtExitManager assertion on SpellcheckServiceFactory destruction during + # Windows multi-threaded message loop shutdown. + # https://code.google.com/p/chromiumembedded/issues/detail?id=137 + 'name': 'spellcheck_137', + 'path': '../chrome/browser/spellchecker/', + }, + { + # Fix crash when calling LoadURL/Reload from OnRenderProcessTerminated. + # https://code.google.com/p/chromiumembedded/issues/detail?id=1429 + 'name': 'render_process_host_1429', + 'path': '../content/browser/renderer_host/', + }, + { + # Disable scollbar bounce and overlay on OS X. + # http://code.google.com/p/chromiumembedded/issues/detail?id=364 + 'name': 'spi_webcore_364', + 'path': '../third_party/WebKit/Source/', + 'condition': 'CEF_SPI_BUILD', + }, +] diff --git a/patch/patches/browser_web_contents_1257.patch b/patch/patches/browser_web_contents_1257.patch new file mode 100644 index 000000000..2e7e0e7e9 --- /dev/null +++ b/patch/patches/browser_web_contents_1257.patch @@ -0,0 +1,80 @@ +diff --git web_contents_impl.cc web_contents_impl.cc +index f9ba939..5555235 100644 +--- web_contents_impl.cc ++++ web_contents_impl.cc +@@ -1164,22 +1164,29 @@ void WebContentsImpl::Init(const WebContents::CreateParams& params) { + params.browser_context, params.site_instance, params.routing_id, + params.main_frame_routing_id); + +- WebContentsViewDelegate* delegate = +- GetContentClient()->browser()->GetWebContentsViewDelegate(this); +- +- if (browser_plugin_guest_) { +- scoped_ptr platform_view(CreateWebContentsView( +- this, delegate, &render_view_host_delegate_view_)); +- +- WebContentsViewGuest* rv = new WebContentsViewGuest( +- this, browser_plugin_guest_.get(), platform_view.Pass(), +- render_view_host_delegate_view_); +- render_view_host_delegate_view_ = rv; +- view_.reset(rv); +- } else { +- // Regular WebContentsView. +- view_.reset(CreateWebContentsView( +- this, delegate, &render_view_host_delegate_view_)); ++ if (params.view && params.delegate_view) { ++ view_.reset(params.view); ++ render_view_host_delegate_view_ = params.delegate_view; ++ } ++ ++ if (!view_) { ++ WebContentsViewDelegate* delegate = ++ GetContentClient()->browser()->GetWebContentsViewDelegate(this); ++ ++ if (browser_plugin_guest_) { ++ scoped_ptr platform_view(CreateWebContentsView( ++ this, delegate, &render_view_host_delegate_view_)); ++ ++ WebContentsViewGuest* rv = new WebContentsViewGuest( ++ this, browser_plugin_guest_.get(), platform_view.Pass(), ++ render_view_host_delegate_view_); ++ render_view_host_delegate_view_ = rv; ++ view_.reset(rv); ++ } else { ++ // Regular WebContentsView. ++ view_.reset(CreateWebContentsView( ++ this, delegate, &render_view_host_delegate_view_)); ++ } + } + CHECK(render_view_host_delegate_view_); + CHECK(view_.get()); +@@ -1517,6 +1524,9 @@ void WebContentsImpl::CreateNewWindow( + static_cast(session_storage_namespace); + CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context)); + ++ content::WebContentsView* view = NULL; ++ content::RenderViewHostDelegateView* delegate_view = NULL; ++ + if (delegate_ && + !delegate_->ShouldCreateWebContents(this, + route_id, +@@ -1525,7 +1535,9 @@ void WebContentsImpl::CreateNewWindow( + params.frame_name, + params.target_url, + partition_id, +- session_storage_namespace)) { ++ session_storage_namespace, ++ &view, ++ &delegate_view)) { + if (route_id != MSG_ROUTING_NONE && + !RenderViewHost::FromID(render_process_id, route_id)) { + // If the embedder didn't create a WebContents for this route, we need to +@@ -1545,6 +1557,8 @@ void WebContentsImpl::CreateNewWindow( + create_params.main_frame_routing_id = main_frame_route_id; + create_params.opener = this; + create_params.opener_suppressed = params.opener_suppressed; ++ create_params.view = view; ++ create_params.delegate_view = delegate_view; + if (params.disposition == NEW_BACKGROUND_TAB) + create_params.initially_hidden = true; + diff --git a/patch/patches/build.patch b/patch/patches/build.patch new file mode 100644 index 000000000..adea475b1 --- /dev/null +++ b/patch/patches/build.patch @@ -0,0 +1,27 @@ +diff --git common.gypi common.gypi +index f7d7d3b..b188037 100644 +--- common.gypi ++++ common.gypi +@@ -9,6 +9,9 @@ + # Variables expected to be overriden on the GYP command line (-D) or by + # ~/.gyp/include.gypi. + 'variables': { ++ # Directory for CEF source files. This will be set by cef.gypi. ++ 'cef_directory%' : '', ++ + # Putting a variables dict inside another variables dict looks kind of + # weird. This is done so that 'host_arch', 'chromeos', etc are defined as + # variables within the outer variables dict here. This is necessary +diff --git mac/strip_save_dsym mac/strip_save_dsym +index c9cf226..0dedbe3 100755 +--- mac/strip_save_dsym ++++ mac/strip_save_dsym +@@ -48,7 +48,7 @@ def macho_archs(macho): + "bundle"] + macho_types_re = "Mach-O (?:64-bit )?(?:" + "|".join(macho_types) + ")" + +- file_cmd = subprocess.Popen(["/usr/bin/file", "-b", "--", macho], ++ file_cmd = subprocess.Popen(["/usr/bin/file", "-b", "-L", "--", macho], + stdout=subprocess.PIPE) + + archs = [] diff --git a/patch/patches/chrome_browser_1257.patch b/patch/patches/chrome_browser_1257.patch new file mode 100644 index 000000000..3dc01d488 --- /dev/null +++ b/patch/patches/chrome_browser_1257.patch @@ -0,0 +1,30 @@ +diff --git ui/browser.cc ui/browser.cc +index 6c926b9..a809f0f 100644 +--- ui/browser.cc ++++ ui/browser.cc +@@ -1567,7 +1567,9 @@ bool Browser::ShouldCreateWebContents( + const base::string16& frame_name, + const GURL& target_url, + const std::string& partition_id, +- content::SessionStorageNamespace* session_storage_namespace) { ++ content::SessionStorageNamespace* session_storage_namespace, ++ content::WebContentsView** view, ++ content::RenderViewHostDelegateView** delegate_view) { + if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) { + // If a BackgroundContents is created, suppress the normal WebContents. + return !MaybeCreateBackgroundContents(route_id, +diff --git ui/browser.h ui/browser.h +index c9aad25..b682e4e 100644 +--- ui/browser.h ++++ ui/browser.h +@@ -587,7 +587,9 @@ class Browser : public TabStripModelObserver, + const base::string16& frame_name, + const GURL& target_url, + const std::string& partition_id, +- content::SessionStorageNamespace* session_storage_namespace) override; ++ content::SessionStorageNamespace* session_storage_namespace, ++ content::WebContentsView** view, ++ content::RenderViewHostDelegateView** delegate_view) override; + void WebContentsCreated(content::WebContents* source_contents, + int opener_render_frame_id, + const base::string16& frame_name, diff --git a/patch/patches/compositor_1368.patch b/patch/patches/compositor_1368.patch new file mode 100644 index 000000000..e9a1b38c7 --- /dev/null +++ b/patch/patches/compositor_1368.patch @@ -0,0 +1,67 @@ +diff --git content/browser/compositor/gpu_process_transport_factory.cc content/browser/compositor/gpu_process_transport_factory.cc +index c7c867e..5b0ea66 100644 +--- content/browser/compositor/gpu_process_transport_factory.cc ++++ content/browser/compositor/gpu_process_transport_factory.cc +@@ -106,6 +106,13 @@ GpuProcessTransportFactory::CreateOffscreenCommandBufferContext() { + + scoped_ptr CreateSoftwareOutputDevice( + ui::Compositor* compositor) { ++ if (compositor->delegate()) { ++ scoped_ptr output_device = ++ compositor->delegate()->CreateSoftwareOutputDevice(compositor); ++ if (output_device.get()) ++ return output_device; ++ } ++ + #if defined(OS_WIN) + return scoped_ptr(new SoftwareOutputDeviceWin( + compositor)); +diff --git ui/compositor/compositor.h ui/compositor/compositor.h +index 94cd1a91..b13e64fb 100644 +--- ui/compositor/compositor.h ++++ ui/compositor/compositor.h +@@ -13,6 +13,7 @@ + #include "base/observer_list.h" + #include "base/single_thread_task_runner.h" + #include "base/time/time.h" ++#include "cc/output/software_output_device.h" + #include "cc/surfaces/surface_sequence.h" + #include "cc/trees/layer_tree_host_client.h" + #include "cc/trees/layer_tree_host_single_thread_client.h" +@@ -136,6 +137,17 @@ class COMPOSITOR_EXPORT CompositorLock + DISALLOW_COPY_AND_ASSIGN(CompositorLock); + }; + ++class COMPOSITOR_EXPORT CompositorDelegate { ++ public: ++ virtual scoped_ptr CreateSoftwareOutputDevice( ++ ui::Compositor* compositor) { ++ return scoped_ptr(); ++ } ++ ++ protected: ++ virtual ~CompositorDelegate() {} ++}; ++ + // Compositor object to take care of GPU painting. + // A Browser compositor object is responsible for generating the final + // displayable form of pixels comprising a single widget's contents. It draws an +@@ -157,6 +169,9 @@ class COMPOSITOR_EXPORT Compositor + // Schedules a redraw of the layer tree associated with this compositor. + void ScheduleDraw(); + ++ CompositorDelegate* delegate() const { return delegate_; } ++ void SetDelegate(CompositorDelegate* delegate) { delegate_ = delegate; } ++ + // Sets the root of the layer tree drawn by this Compositor. The root layer + // must have no parent. The compositor's root layer is reset if the root layer + // is destroyed. NULL can be passed to reset the root layer, in which case the +@@ -310,6 +325,8 @@ class COMPOSITOR_EXPORT Compositor + + ui::ContextFactory* context_factory_; + ++ CompositorDelegate* delegate_ = nullptr; ++ + // The root of the Layer tree drawn by this compositor. + Layer* root_layer_; + diff --git a/patch/patches/content_nav_1129.patch b/patch/patches/content_nav_1129.patch new file mode 100644 index 000000000..10f7b5b7b --- /dev/null +++ b/patch/patches/content_nav_1129.patch @@ -0,0 +1,60 @@ +diff --git public/renderer/content_renderer_client.cc public/renderer/content_renderer_client.cc +index 79b40ac..4babaa9 100644 +--- public/renderer/content_renderer_client.cc ++++ public/renderer/content_renderer_client.cc +@@ -99,7 +99,6 @@ bool ContentRendererClient::AllowPopup() { + return false; + } + +-#ifdef OS_ANDROID + bool ContentRendererClient::HandleNavigation( + RenderFrame* render_frame, + DocumentState* document_state, +@@ -111,7 +110,6 @@ bool ContentRendererClient::HandleNavigation( + bool is_redirect) { + return false; + } +-#endif + + bool ContentRendererClient::ShouldFork(blink::WebFrame* frame, + const GURL& url, +diff --git public/renderer/content_renderer_client.h public/renderer/content_renderer_client.h +index bd43c62..1d6e189 100644 +--- public/renderer/content_renderer_client.h ++++ public/renderer/content_renderer_client.h +@@ -195,7 +195,6 @@ class CONTENT_EXPORT ContentRendererClient { + // Returns true if a popup window should be allowed. + virtual bool AllowPopup(); + +-#ifdef OS_ANDROID + // TODO(sgurun) This callback is deprecated and will be removed as soon + // as android webview completes implementation of a resource throttle based + // shouldoverrideurl implementation. See crbug.com/325351 +@@ -210,7 +209,6 @@ class CONTENT_EXPORT ContentRendererClient { + blink::WebNavigationType type, + blink::WebNavigationPolicy default_policy, + bool is_redirect); +-#endif + + // Returns true if we should fork a new process for the given navigation. + // If |send_referrer| is set to false (which is the default), no referrer +diff --git renderer/render_frame_impl.cc renderer/render_frame_impl.cc +index 7258dbb..8dba5f3 100644 +--- renderer/render_frame_impl.cc ++++ renderer/render_frame_impl.cc +@@ -3811,7 +3811,6 @@ void RenderFrameImpl::OnCommitNavigation( + WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation( + RenderFrame* render_frame, + const NavigationPolicyInfo& info) { +-#ifdef OS_ANDROID + // The handlenavigation API is deprecated and will be removed once + // crbug.com/325351 is resolved. + if (info.urlRequest.url() != GURL(kSwappedOutURL) && +@@ -3826,7 +3825,6 @@ WebNavigationPolicy RenderFrameImpl::DecidePolicyForNavigation( + info.isRedirect)) { + return blink::WebNavigationPolicyIgnore; + } +-#endif + + Referrer referrer(RenderViewImpl::GetReferrerFromRequest(info.frame, + info.urlRequest)); diff --git a/patch/patches/gritsettings.patch b/patch/patches/gritsettings.patch new file mode 100644 index 000000000..f1e3c30f6 --- /dev/null +++ b/patch/patches/gritsettings.patch @@ -0,0 +1,17 @@ +diff --git resource_ids resource_ids +index efd5760..62dd7b0 100644 +--- resource_ids ++++ resource_ids +@@ -14,6 +14,12 @@ + { + "SRCDIR": "../..", + ++ "cef/libcef/resources/cef_resources.grd": { ++ "includes": [27500], ++ }, ++ "cef/libcef/resources/cef_strings.grd": { ++ "messages": [28000], ++ }, + "chrome/browser/browser_resources.grd": { + "includes": [400], + "structures": [750], diff --git a/patch/patches/gyp_331.patch b/patch/patches/gyp_331.patch new file mode 100644 index 000000000..d6be117e4 --- /dev/null +++ b/patch/patches/gyp_331.patch @@ -0,0 +1,22 @@ +diff --git gyp/generator/ninja.py gyp/generator/ninja.py +index 5cda5c3..bad5ca3 100644 +--- gyp/generator/ninja.py ++++ gyp/generator/ninja.py +@@ -743,7 +743,16 @@ class NinjaWriter(object): + for path in copy['files']: + # Normalize the path so trailing slashes don't confuse us. + path = os.path.normpath(path) +- basename = os.path.split(path)[1] ++ (parent_path, basename) = os.path.split(path) ++ ++ # Xcode uses .lproj directories for localized resources. Add a special ++ # case to maintain the localization directory component if present. ++ if parent_path != '': ++ parent_basename = os.path.basename(parent_path) ++ (parent_root, parent_ext) = os.path.splitext(parent_basename) ++ if parent_ext == '.lproj': ++ basename = os.path.join(parent_basename, basename) ++ + src = self.GypPathToNinja(path, env) + dst = self.GypPathToNinja(os.path.join(copy['destination'], basename), + env) diff --git a/patch/patches/message_loop_443.patch b/patch/patches/message_loop_443.patch new file mode 100644 index 000000000..577a7e72a --- /dev/null +++ b/patch/patches/message_loop_443.patch @@ -0,0 +1,12 @@ +diff --git message_loop.cc message_loop.cc +index 8180733..927f755 100644 +--- message_loop.cc ++++ message_loop.cc +@@ -148,7 +148,6 @@ MessageLoop::MessageLoop(scoped_ptr pump) + MessageLoop::~MessageLoop() { + DCHECK_EQ(this, current()); + +- DCHECK(!run_loop_); + #if defined(OS_WIN) + if (in_high_res_mode_) + Time::ActivateHighResolutionTimer(false); diff --git a/patch/patches/prefs_content_1161.patch b/patch/patches/prefs_content_1161.patch new file mode 100644 index 000000000..7b7cbcd2a --- /dev/null +++ b/patch/patches/prefs_content_1161.patch @@ -0,0 +1,49 @@ +diff --git public/common/common_param_traits_macros.h public/common/common_param_traits_macros.h +index a064d53..8abea71 100644 +--- public/common/common_param_traits_macros.h ++++ public/common/common_param_traits_macros.h +@@ -188,6 +188,7 @@ IPC_STRUCT_TRAITS_BEGIN(content::WebPreferences) + IPC_STRUCT_TRAITS_MEMBER(main_frame_resizes_are_orientation_changes) + IPC_STRUCT_TRAITS_MEMBER(initialize_at_minimum_page_scale) + IPC_STRUCT_TRAITS_MEMBER(smart_insert_delete_enabled) ++ IPC_STRUCT_TRAITS_MEMBER(base_background_color) + IPC_STRUCT_TRAITS_MEMBER(cookie_enabled) + IPC_STRUCT_TRAITS_MEMBER(navigate_on_drag_drop) + IPC_STRUCT_TRAITS_MEMBER(spatial_navigation_enabled) +diff --git public/common/web_preferences.cc public/common/web_preferences.cc +index a5574d3..8e9e391 100644 +--- public/common/web_preferences.cc ++++ public/common/web_preferences.cc +@@ -179,6 +179,7 @@ WebPreferences::WebPreferences() + rubber_banding_on_compositor_thread(false), + use_solid_color_scrollbars(false), + navigate_on_drag_drop(true), ++ base_background_color(0xFFFFFFFF), // Color::white + v8_cache_options(V8_CACHE_OPTIONS_DEFAULT), + v8_script_streaming_enabled(false), + v8_script_streaming_mode(V8_SCRIPT_STREAMING_MODE_ALL), +diff --git public/common/web_preferences.h public/common/web_preferences.h +index 78559f2..028a94e 100644 +--- public/common/web_preferences.h ++++ public/common/web_preferences.h +@@ -169,6 +169,7 @@ struct CONTENT_EXPORT WebPreferences { + bool rubber_banding_on_compositor_thread; + bool use_solid_color_scrollbars; + bool navigate_on_drag_drop; ++ uint32_t base_background_color; + V8CacheOptions v8_cache_options; + bool v8_script_streaming_enabled; + V8ScriptStreamingMode v8_script_streaming_mode; +diff --git renderer/render_view_impl.cc renderer/render_view_impl.cc +index 623cb14..5d21fc5 100644 +--- renderer/render_view_impl.cc ++++ renderer/render_view_impl.cc +@@ -958,6 +958,8 @@ void RenderView::ApplyWebPreferences(const WebPreferences& prefs, + + settings->setJavaEnabled(prefs.java_enabled); + ++ web_view->setBaseBackgroundColor(prefs.base_background_color); ++ + // By default, allow_universal_access_from_file_urls is set to false and thus + // we mitigate attacks from local HTML files by not granting file:// URLs + // universal access. Only test shell will enable this. diff --git a/patch/patches/public_browser_1161_1257.patch b/patch/patches/public_browser_1161_1257.patch new file mode 100644 index 000000000..2d5cf7816 --- /dev/null +++ b/patch/patches/public_browser_1161_1257.patch @@ -0,0 +1,132 @@ +diff --git content_browser_client.cc content_browser_client.cc +index 91c8a4d..10c3b28 100644 +--- content_browser_client.cc ++++ content_browser_client.cc +@@ -278,6 +278,10 @@ bool ContentBrowserClient::IsFastShutdownPossible() { + return true; + } + ++SkColor ContentBrowserClient::GetBaseBackgroundColor(RenderViewHost* rvh) { ++ return SK_ColorWHITE; ++} ++ + base::FilePath ContentBrowserClient::GetDefaultDownloadDirectory() { + return base::FilePath(); + } +diff --git content_browser_client.h content_browser_client.h +index 627353d..e1805f4 100644 +--- content_browser_client.h ++++ content_browser_client.h +@@ -28,6 +28,7 @@ + #include "net/url_request/url_request_interceptor.h" + #include "net/url_request/url_request_job_factory.h" + #include "storage/browser/fileapi/file_system_context.h" ++#include "third_party/skia/include/core/SkColor.h" + #include "ui/base/window_open_disposition.h" + + #if defined(OS_POSIX) && !defined(OS_MACOSX) +@@ -499,6 +500,9 @@ class CONTENT_EXPORT ContentBrowserClient { + // Clears browser cookies. + virtual void ClearCookies(RenderViewHost* rvh) {} + ++ // Returns the base background color. ++ virtual SkColor GetBaseBackgroundColor(RenderViewHost* rvh); ++ + // Returns the default download directory. + // This can be called on any thread. + virtual base::FilePath GetDefaultDownloadDirectory(); +diff --git web_contents.cc web_contents.cc +index 7afc338..c014439 100644 +--- web_contents.cc ++++ web_contents.cc +@@ -17,7 +17,9 @@ WebContents::CreateParams::CreateParams(BrowserContext* context) + main_frame_routing_id(MSG_ROUTING_NONE), + initially_hidden(false), + guest_delegate(NULL), +- context(NULL) {} ++ context(NULL), ++ view(NULL), ++ delegate_view(NULL) {} + + WebContents::CreateParams::CreateParams( + BrowserContext* context, SiteInstance* site) +@@ -29,7 +31,9 @@ WebContents::CreateParams::CreateParams( + main_frame_routing_id(MSG_ROUTING_NONE), + initially_hidden(false), + guest_delegate(NULL), +- context(NULL) {} ++ context(NULL), ++ view(NULL), ++ delegate_view(NULL) {} + + WebContents::CreateParams::~CreateParams() { + } +diff --git web_contents.h web_contents.h +index 87becd6..b66d3fb 100644 +--- web_contents.h ++++ web_contents.h +@@ -52,9 +52,11 @@ class PageState; + class RenderFrameHost; + class RenderProcessHost; + class RenderViewHost; ++class RenderViewHostDelegateView; + class RenderWidgetHostView; + class SiteInstance; + class WebContentsDelegate; ++class WebContentsView; + struct CustomContextMenuContext; + struct DropData; + struct Manifest; +@@ -122,6 +124,10 @@ class WebContents : public PageNavigator, + // Used to specify the location context which display the new view should + // belong. This can be NULL if not needed. + gfx::NativeView context; ++ ++ // Optionally specify the view and delegate view. ++ content::WebContentsView* view; ++ content::RenderViewHostDelegateView* delegate_view; + }; + + // Creates a new WebContents. +diff --git web_contents_delegate.cc web_contents_delegate.cc +index e846041..da3c9e6 100644 +--- web_contents_delegate.cc ++++ web_contents_delegate.cc +@@ -137,7 +137,9 @@ bool WebContentsDelegate::ShouldCreateWebContents( + const base::string16& frame_name, + const GURL& target_url, + const std::string& partition_id, +- SessionStorageNamespace* session_storage_namespace) { ++ SessionStorageNamespace* session_storage_namespace, ++ content::WebContentsView** view, ++ content::RenderViewHostDelegateView** delegate_view) { + return true; + } + +diff --git web_contents_delegate.h web_contents_delegate.h +index 344fbaf..adaa39d 100644 +--- web_contents_delegate.h ++++ web_contents_delegate.h +@@ -36,9 +36,11 @@ class DownloadItem; + class JavaScriptDialogManager; + class PageState; + class RenderViewHost; ++class RenderViewHostDelegateView; + class SessionStorageNamespace; + class WebContents; + class WebContentsImpl; ++class WebContentsView; + struct ColorSuggestion; + struct ContextMenuParams; + struct DropData; +@@ -314,7 +316,9 @@ class CONTENT_EXPORT WebContentsDelegate { + const base::string16& frame_name, + const GURL& target_url, + const std::string& partition_id, +- SessionStorageNamespace* session_storage_namespace); ++ SessionStorageNamespace* session_storage_namespace, ++ content::WebContentsView** view, ++ content::RenderViewHostDelegateView** delegate_view); + + // Notifies the delegate about the creation of a new WebContents. This + // typically happens when popups are created. diff --git a/patch/patches/render_process_host_1429.patch b/patch/patches/render_process_host_1429.patch new file mode 100644 index 000000000..eccd70096 --- /dev/null +++ b/patch/patches/render_process_host_1429.patch @@ -0,0 +1,22 @@ +diff --git render_process_host_impl.cc render_process_host_impl.cc +index c01b1e9..bf2a9e1 100644 +--- render_process_host_impl.cc ++++ render_process_host_impl.cc +@@ -2047,6 +2047,8 @@ void RenderProcessHostImpl::ProcessDied(bool already_dead) { + #endif + RemoveUserData(kSessionStorageHolderKey); + ++ mojo_application_host_.reset(new MojoApplicationHost); ++ + IDMap::iterator iter(&listeners_); + while (!iter.IsAtEnd()) { + iter.GetCurrentValue()->OnMessageReceived( +@@ -2056,8 +2058,6 @@ void RenderProcessHostImpl::ProcessDied(bool already_dead) { + iter.Advance(); + } + +- mojo_application_host_.reset(new MojoApplicationHost); +- + // It's possible that one of the calls out to the observers might have caused + // this object to be no longer needed. + if (delayed_cleanup_needed_) diff --git a/patch/patches/spellcheck_137.patch b/patch/patches/spellcheck_137.patch new file mode 100644 index 000000000..ed458667d --- /dev/null +++ b/patch/patches/spellcheck_137.patch @@ -0,0 +1,49 @@ +diff --git spellcheck_factory.cc spellcheck_factory.cc +index 7d7e1df..b623657 100644 +--- spellcheck_factory.cc ++++ spellcheck_factory.cc +@@ -15,6 +15,13 @@ + #include "content/public/browser/render_process_host.h" + #include "ui/base/l10n/l10n_util.h" + ++namespace { ++ ++static base::LazyInstance::Leaky ++ g_spellcheck_service_factory = LAZY_INSTANCE_INITIALIZER; ++ ++} // namespace ++ + // static + SpellcheckService* SpellcheckServiceFactory::GetForContext( + content::BrowserContext* context) { +@@ -37,7 +44,7 @@ SpellcheckService* SpellcheckServiceFactory::GetForRenderProcessId( + + // static + SpellcheckServiceFactory* SpellcheckServiceFactory::GetInstance() { +- return Singleton::get(); ++ return g_spellcheck_service_factory.Pointer(); + } + + SpellcheckServiceFactory::SpellcheckServiceFactory() +diff --git spellcheck_factory.h spellcheck_factory.h +index 3e4ad0e..d52b881 100644 +--- spellcheck_factory.h ++++ spellcheck_factory.h +@@ -7,7 +7,7 @@ + + #include "base/basictypes.h" + #include "base/gtest_prod_util.h" +-#include "base/memory/singleton.h" ++#include "base/lazy_instance.h" + #include "components/keyed_service/content/browser_context_keyed_service_factory.h" + + class SpellcheckService; +@@ -26,7 +26,7 @@ class SpellcheckServiceFactory : public BrowserContextKeyedServiceFactory { + static SpellcheckServiceFactory* GetInstance(); + + private: +- friend struct DefaultSingletonTraits; ++ friend struct base::DefaultLazyInstanceTraits; + + SpellcheckServiceFactory(); + ~SpellcheckServiceFactory() override; diff --git a/patch/patches/spi_webcore_364.patch b/patch/patches/spi_webcore_364.patch new file mode 100644 index 000000000..09dcc88cb --- /dev/null +++ b/patch/patches/spi_webcore_364.patch @@ -0,0 +1,34 @@ +diff --git core/frame/FrameView.cpp core/frame/FrameView.cpp +index 9b2004d..b9a73c7 100644 +--- core/frame/FrameView.cpp ++++ core/frame/FrameView.cpp +@@ -144,8 +144,10 @@ FrameView::FrameView(LocalFrame* frame) + if (!m_frame->isMainFrame()) + return; + ++#if 0 + ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed); + ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed); ++#endif + } + + PassRefPtrWillBeRawPtr FrameView::create(LocalFrame* frame) +diff --git platform/scroll/ScrollbarThemeMacCommon.mm platform/scroll/ScrollbarThemeMacCommon.mm +index 90abb7c..6bb16c6 100644 +--- platform/scroll/ScrollbarThemeMacCommon.mm ++++ platform/scroll/ScrollbarThemeMacCommon.mm +@@ -354,10 +354,14 @@ NSScrollerStyle ScrollbarThemeMacCommon::recommendedScrollerStyle() + // static + bool ScrollbarThemeMacCommon::isOverlayAPIAvailable() + { ++#if 0 + static bool apiAvailable = + [NSClassFromString(@"NSScrollerImp") respondsToSelector:@selector(scrollerImpWithStyle:controlSize:horizontal:replacingScrollerImp:)] + && [NSClassFromString(@"NSScrollerImpPair") instancesRespondToSelector:@selector(scrollerStyle)]; + return apiAvailable; ++#else ++ return false; ++#endif + } + + } // namespace blink diff --git a/patch/patches/ui_dragdrop_355390.patch b/patch/patches/ui_dragdrop_355390.patch new file mode 100644 index 000000000..03e3caa7b --- /dev/null +++ b/patch/patches/ui_dragdrop_355390.patch @@ -0,0 +1,14 @@ +diff --git os_exchange_data_provider_aurax11.cc os_exchange_data_provider_aurax11.cc +index 714069f..56c7fa5 100644 +--- os_exchange_data_provider_aurax11.cc ++++ os_exchange_data_provider_aurax11.cc +@@ -158,7 +158,8 @@ void OSExchangeDataProviderAuraX11::SetURL(const GURL& url, + format_map_.Insert(atom_cache_.GetAtom(kMimeTypeMozillaURL), mem); + + // Set a string fallback as well. +- SetString(spec); ++ if (!HasString()) ++ SetString(spec); + + // Return early if this drag already contains file contents (this implies + // that file contents must be populated before URLs). Nautilus (and possibly diff --git a/patch/patches/underlay_1051.patch b/patch/patches/underlay_1051.patch new file mode 100644 index 000000000..e507037a6 --- /dev/null +++ b/patch/patches/underlay_1051.patch @@ -0,0 +1,13 @@ +diff --git underlay_opengl_hosting_window.h underlay_opengl_hosting_window.h +index d673c31..806d134 100644 +--- underlay_opengl_hosting_window.h ++++ underlay_opengl_hosting_window.h +@@ -12,7 +12,7 @@ + // Common base class for windows that host a OpenGL surface that renders under + // the window. Previously contained methods related to hole punching, now just + // contains common asserts. +-UI_BASE_EXPORT ++__attribute__((visibility("default"))) + @interface UnderlayOpenGLHostingWindow : NSWindow + @end + diff --git a/patch/patches/views_widget_180.patch b/patch/patches/views_widget_180.patch new file mode 100644 index 000000000..f404be35e --- /dev/null +++ b/patch/patches/views_widget_180.patch @@ -0,0 +1,219 @@ +diff --git desktop_aura/desktop_screen_win.cc desktop_aura/desktop_screen_win.cc +index a8e088c..838b6a0 100644 +--- desktop_aura/desktop_screen_win.cc ++++ desktop_aura/desktop_screen_win.cc +@@ -32,6 +32,8 @@ gfx::Display DesktopScreenWin::GetDisplayMatching( + } + + HWND DesktopScreenWin::GetHWNDFromNativeView(gfx::NativeView window) const { ++ if (!window) ++ return NULL; + aura::WindowTreeHost* host = window->GetHost(); + return host ? host->GetAcceleratedWidget() : NULL; + } +diff --git desktop_aura/desktop_window_tree_host_win.cc desktop_aura/desktop_window_tree_host_win.cc +index b54a643..5a589e5 100644 +--- desktop_aura/desktop_window_tree_host_win.cc ++++ desktop_aura/desktop_window_tree_host_win.cc +@@ -133,7 +133,9 @@ void DesktopWindowTreeHostWin::Init(aura::Window* content_window, + native_widget_delegate_); + + HWND parent_hwnd = NULL; +- if (params.parent && params.parent->GetHost()) ++ if (params.parent_widget) ++ parent_hwnd = params.parent_widget; ++ else if (params.parent && params.parent->GetHost()) + parent_hwnd = params.parent->GetHost()->GetAcceleratedWidget(); + + message_handler_->set_remove_standard_frame(params.remove_standard_frame); +@@ -820,6 +822,7 @@ void DesktopWindowTreeHostWin::HandleFrameChanged() { + + void DesktopWindowTreeHostWin::HandleNativeFocus(HWND last_focused_window) { + // TODO(beng): inform the native_widget_delegate_. ++ GetWidget()->GetNativeWindow()->Focus(); + InputMethod* input_method = GetInputMethod(); + if (input_method) + input_method->OnFocus(); +@@ -827,6 +830,7 @@ void DesktopWindowTreeHostWin::HandleNativeFocus(HWND last_focused_window) { + + void DesktopWindowTreeHostWin::HandleNativeBlur(HWND focused_window) { + // TODO(beng): inform the native_widget_delegate_. ++ GetWidget()->GetNativeWindow()->Blur(); + InputMethod* input_method = GetInputMethod(); + if (input_method) + input_method->OnBlur(); +diff --git desktop_aura/desktop_window_tree_host_x11.cc desktop_aura/desktop_window_tree_host_x11.cc +index 2809f02..9a79223 100644 +--- desktop_aura/desktop_window_tree_host_x11.cc ++++ desktop_aura/desktop_window_tree_host_x11.cc +@@ -152,7 +152,8 @@ DesktopWindowTreeHostX11::DesktopWindowTreeHostX11( + window_shape_(NULL), + custom_window_shape_(false), + urgency_hint_set_(false), +- close_widget_factory_(this) { ++ close_widget_factory_(this), ++ xwindow_destroyed_(false) { + } + + DesktopWindowTreeHostX11::~DesktopWindowTreeHostX11() { +@@ -354,7 +355,8 @@ void DesktopWindowTreeHostX11::CloseNow() { + // Actually free our native resources. + if (ui::PlatformEventSource::GetInstance()) + ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); +- XDestroyWindow(xdisplay_, xwindow_); ++ if (!xwindow_destroyed_) ++ XDestroyWindow(xdisplay_, xwindow_); + xwindow_ = None; + + desktop_native_widget_aura_->OnHostClosed(); +@@ -448,6 +450,8 @@ void DesktopWindowTreeHostX11::GetWindowPlacement( + } + + gfx::Rect DesktopWindowTreeHostX11::GetWindowBoundsInScreen() const { ++ if (!screen_bounds_.IsEmpty()) ++ return screen_bounds_; + return bounds_; + } + +@@ -460,6 +464,8 @@ gfx::Rect DesktopWindowTreeHostX11::GetClientAreaBoundsInScreen() const { + // Attempts to calculate the rect by asking the NonClientFrameView what it + // thought its GetBoundsForClientView() were broke combobox drop down + // placement. ++ if (!screen_bounds_.IsEmpty()) ++ return screen_bounds_; + return bounds_; + } + +@@ -883,6 +889,8 @@ void DesktopWindowTreeHostX11::Hide() { + } + + gfx::Rect DesktopWindowTreeHostX11::GetBounds() const { ++ if (!screen_bounds_.IsEmpty()) ++ return screen_bounds_; + return bounds_; + } + +@@ -938,6 +946,8 @@ void DesktopWindowTreeHostX11::SetBounds(const gfx::Rect& requested_bounds) { + } + + gfx::Point DesktopWindowTreeHostX11::GetLocationOnNativeScreen() const { ++ if (!screen_bounds_.IsEmpty()) ++ return screen_bounds_.origin(); + return bounds_.origin(); + } + +@@ -1057,10 +1067,14 @@ void DesktopWindowTreeHostX11::InitX11Window( + } + } + ++ gfx::AcceleratedWidget parent_widget = params.parent_widget; ++ if (parent_widget == gfx::kNullAcceleratedWidget) ++ parent_widget = x_root_window_; ++ + bounds_ = gfx::Rect(params.bounds.origin(), + AdjustSize(params.bounds.size())); + xwindow_ = XCreateWindow( +- xdisplay_, x_root_window_, ++ xdisplay_, parent_widget, + bounds_.x(), bounds_.y(), + bounds_.width(), bounds_.height(), + 0, // border width +@@ -1697,6 +1711,10 @@ uint32_t DesktopWindowTreeHostX11::DispatchEvent( + } + break; + } ++ case DestroyNotify: ++ xwindow_destroyed_ = true; ++ CloseNow(); ++ break; + case FocusOut: + if (xev->xfocus.mode != NotifyGrab) { + ReleaseCapture(); +diff --git desktop_aura/desktop_window_tree_host_x11.h desktop_aura/desktop_window_tree_host_x11.h +index d6b5cc8..bf20d4c 100644 +--- desktop_aura/desktop_window_tree_host_x11.h ++++ desktop_aura/desktop_window_tree_host_x11.h +@@ -85,6 +85,8 @@ class VIEWS_EXPORT DesktopWindowTreeHostX11 + // Deallocates the internal list of open windows. + static void CleanUpWindowList(); + ++ void set_screen_bounds(const gfx::Rect& bounds) { screen_bounds_ = bounds; } ++ + protected: + // Overridden from DesktopWindowTreeHost: + void Init(aura::Window* content_window, +@@ -253,6 +255,9 @@ class VIEWS_EXPORT DesktopWindowTreeHostX11 + // The bounds of |xwindow_|. + gfx::Rect bounds_; + ++ // Override the screen bounds when the host is a child window. ++ gfx::Rect screen_bounds_; ++ + // Whenever the bounds are set, we keep the previous set of bounds around so + // we can have a better chance of getting the real |restored_bounds_|. Window + // managers tend to send a Configure message with the maximized bounds, and +@@ -337,6 +342,9 @@ class VIEWS_EXPORT DesktopWindowTreeHostX11 + + base::WeakPtrFactory close_widget_factory_; + ++ // True if the xwindow has already been destroyed. ++ bool xwindow_destroyed_; ++ + DISALLOW_COPY_AND_ASSIGN(DesktopWindowTreeHostX11); + }; + +diff --git widget.cc widget.cc +index a24f781..52a1755 100644 +--- widget.cc ++++ widget.cc +@@ -109,6 +109,7 @@ Widget::InitParams::InitParams() + use_system_default_icon(false), + show_state(ui::SHOW_STATE_DEFAULT), + parent(NULL), ++ parent_widget(gfx::kNullAcceleratedWidget), + native_widget(NULL), + desktop_window_tree_host(NULL), + layer_type(aura::WINDOW_LAYER_TEXTURED), +@@ -132,6 +133,7 @@ Widget::InitParams::InitParams(Type type) + use_system_default_icon(false), + show_state(ui::SHOW_STATE_DEFAULT), + parent(NULL), ++ parent_widget(gfx::kNullAcceleratedWidget), + native_widget(NULL), + desktop_window_tree_host(NULL), + layer_type(aura::WINDOW_LAYER_TEXTURED), +@@ -306,7 +308,7 @@ void Widget::Init(const InitParams& in_params) { + InitParams params = in_params; + + params.child |= (params.type == InitParams::TYPE_CONTROL); +- is_top_level_ = !params.child; ++ is_top_level_ = !params.child || params.parent_widget; + + if (params.opacity == views::Widget::InitParams::INFER_OPACITY && + params.type != views::Widget::InitParams::TYPE_WINDOW && +@@ -367,7 +369,12 @@ void Widget::Init(const InitParams& in_params) { + Minimize(); + } else if (params.delegate) { + SetContentsView(params.delegate->GetContentsView()); +- SetInitialBoundsForFramelessWindow(params.bounds); ++ if (params.parent_widget) { ++ // Set the bounds directly instead of applying an inset. ++ SetBounds(params.bounds); ++ } else { ++ SetInitialBoundsForFramelessWindow(params.bounds); ++ } + } + // This must come after SetContentsView() or it might not be able to find + // the correct NativeTheme (on Linux). See http://crbug.com/384492 +diff --git widget.h widget.h +index e0f6180..25f557f 100644 +--- widget.h ++++ widget.h +@@ -235,6 +235,7 @@ class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate, + // Whether the widget should be maximized or minimized. + ui::WindowShowState show_state; + gfx::NativeView parent; ++ gfx::AcceleratedWidget parent_widget; + // Specifies the initial bounds of the Widget. Default is empty, which means + // the NativeWidget may specify a default size. If the parent is specified, + // |bounds| is in the parent's coordinate system. If the parent is not diff --git a/patch/patches/webkit_platform_mac_328814.patch b/patch/patches/webkit_platform_mac_328814.patch new file mode 100644 index 000000000..c9f0f36c3 --- /dev/null +++ b/patch/patches/webkit_platform_mac_328814.patch @@ -0,0 +1,32 @@ +diff --git ThemeMac.mm ThemeMac.mm +index a35aaea..c049569 100644 +--- ThemeMac.mm ++++ ThemeMac.mm +@@ -490,7 +490,7 @@ static void paintButton(ControlPart part, ControlStates states, GraphicsContext* + + [buttonCell drawWithFrame:NSRect(inflatedRect) inView:view]; + #if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING +- if (states & FocusControlState) ++ if (states & FocusState) + [buttonCell _web_drawFocusRingWithFrame:NSRect(inflatedRect) inView:view]; + #endif + [buttonCell setControlView:nil]; +diff --git WebCoreNSCellExtras.h WebCoreNSCellExtras.h +index 8623826..b9f683d 100644 +--- WebCoreNSCellExtras.h ++++ WebCoreNSCellExtras.h +@@ -26,12 +26,12 @@ + #import + #include "platform/PlatformExport.h" + +-#define BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING (!defined(MAC_OS_X_VERSION_10_7) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_7) ++#define BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING 1 + + #if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING + + // FIXME: Might want to use this on Mac once we only support OS X 10.8+ +-@interface NSCell (WebCoreFocusRingDrawing) ++PLATFORM_EXPORT @interface NSCell (WebCoreFocusRingDrawing) + - (void)_web_drawFocusRingWithFrame:(NSRect)cellFrame inView:(NSView *)controlView; + @end + diff --git a/patch/patches/webkit_popups.patch b/patch/patches/webkit_popups.patch new file mode 100644 index 000000000..a931ece62 --- /dev/null +++ b/patch/patches/webkit_popups.patch @@ -0,0 +1,76 @@ +diff --git Source/web/ChromeClientImpl.cpp Source/web/ChromeClientImpl.cpp +index f59cc5f..70add24 100644 +--- Source/web/ChromeClientImpl.cpp ++++ Source/web/ChromeClientImpl.cpp +@@ -741,7 +741,7 @@ bool ChromeClientImpl::hasOpenedPopup() const + + PassRefPtrWillBeRawPtr ChromeClientImpl::createPopupMenu(LocalFrame& frame, PopupMenuClient* client) + { +- if (WebViewImpl::useExternalPopupMenus()) ++ if (m_webView->useExternalPopupMenus()) + return adoptRefWillBeNoop(new ExternalPopupMenu(frame, client, *m_webView)); + + return adoptRefWillBeNoop(new PopupMenuChromium(frame, client)); +diff --git Source/web/WebViewImpl.cpp Source/web/WebViewImpl.cpp +index 8b7320a..75c2644 100644 +--- Source/web/WebViewImpl.cpp ++++ Source/web/WebViewImpl.cpp +@@ -379,6 +379,7 @@ WebViewImpl::WebViewImpl(WebViewClient* client) + , m_fakePageScaleAnimationPageScaleFactor(0) + , m_fakePageScaleAnimationUseAnchor(false) + , m_contextMenuAllowed(false) ++ , m_shouldUseExternalPopupMenus(shouldUseExternalPopupMenus) + , m_doingDragAndDrop(false) + , m_ignoreInputEvents(false) + , m_compositorDeviceScaleFactorOverride(0) +@@ -3971,9 +3972,14 @@ void WebViewImpl::deviceOrPageScaleFactorChanged() + m_page->inspectorController().deviceOrPageScaleFactorChanged(); + } + ++void WebViewImpl::setUseExternalPopupMenusThisInstance(bool useExternalPopupMenus) ++{ ++ m_shouldUseExternalPopupMenus = useExternalPopupMenus; ++} ++ + bool WebViewImpl::useExternalPopupMenus() + { +- return shouldUseExternalPopupMenus; ++ return m_shouldUseExternalPopupMenus; + } + + void WebViewImpl::startDragging(LocalFrame* frame, +diff --git Source/web/WebViewImpl.h Source/web/WebViewImpl.h +index 5264cf5..f49be43 100644 +--- Source/web/WebViewImpl.h ++++ Source/web/WebViewImpl.h +@@ -370,7 +370,8 @@ public: + + // Returns true if popup menus should be rendered by the browser, false if + // they should be rendered by WebKit (which is the default). +- static bool useExternalPopupMenus(); ++ void setUseExternalPopupMenusThisInstance(bool); ++ bool useExternalPopupMenus(); + + bool contextMenuAllowed() const + { +@@ -662,6 +663,8 @@ private: + + bool m_contextMenuAllowed; + ++ bool m_shouldUseExternalPopupMenus; ++ + bool m_doingDragAndDrop; + + bool m_ignoreInputEvents; +diff --git public/web/WebView.h public/web/WebView.h +index 56d3ad8..a5c0f37 100644 +--- public/web/WebView.h ++++ public/web/WebView.h +@@ -405,6 +405,7 @@ public: + + // Sets whether select popup menus should be rendered by the browser. + BLINK_EXPORT static void setUseExternalPopupMenus(bool); ++ virtual void setUseExternalPopupMenusThisInstance(bool) = 0; + + // Hides any popup (suggestions, selects...) that might be showing. + virtual void hidePopups() = 0; diff --git a/patch/patches/zlib.patch b/patch/patches/zlib.patch new file mode 100644 index 000000000..9a3a9c9c1 --- /dev/null +++ b/patch/patches/zlib.patch @@ -0,0 +1,13 @@ +diff --git contrib/minizip/unzip.c contrib/minizip/unzip.c +index af59b80..ee3c0fd 100644 +--- contrib/minizip/unzip.c ++++ contrib/minizip/unzip.c +@@ -69,7 +69,7 @@ + #include + + #ifndef NOUNCRYPT +- #define NOUNCRYPT ++// #define NOUNCRYPT + #endif + + #include "third_party/zlib/zlib.h" diff --git a/tests/cefclient/CMakeLists.txt.in b/tests/cefclient/CMakeLists.txt.in new file mode 100644 index 000000000..382164db3 --- /dev/null +++ b/tests/cefclient/CMakeLists.txt.in @@ -0,0 +1,174 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +# +# Source files. +# + +# cefclient sources. +{{ + 'prefix': 'cefclient', + 'set': 'CEFCLIENT_SRCS', + 'includes': [ + 'cefclient_sources_common', + 'cefclient_bundle_resources_common', + 'cefclient_sources_win:WINDOWS', + 'cefclient_sources_mac:MACOSX', + 'cefclient_sources_linux:LINUX', + ], +}} + +# cefclient helper sources. +{{ + 'prefix': 'cefclient_helper', + 'includes': [ + 'cefclient_sources_mac_helper:MACOSX', + ], +}} + +# cefclient resources. +{{ + 'prefix': 'cefclient_resources', + 'set': 'CEFCLIENT_RESOURCES_SRCS', + 'includes': [ + 'cefclient_bundle_resources_common', + 'cefclient_bundle_resources_mac:MACOSX', + ], +}} + + +# +# Shared configuration. +# + +# Target executable names. +set(CEF_TARGET "cefclient") +if(OS_MACOSX) + set(CEF_HELPER_TARGET "cefclient Helper") +endif() + +# Logical target used to link the libcef library. +ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}") + +# Determine the target output directory. +SET_CEF_TARGET_OUT_DIR() + + +# +# Linux configuration. +# + +if(OS_LINUX) + # Find required libraries and update compiler/linker variables. + FIND_LINUX_LIBRARIES("gmodule-2.0 gtk+-2.0 gthread-2.0 gtk+-unix-print-2.0 gtkglext-1.0") + + # Executable target. + add_executable(${CEF_TARGET} ${CEFCLIENT_SRCS}) + add_dependencies(${CEF_TARGET} libcef_dll_wrapper) + target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + + # Set rpath so that libraries can be placed next to the executable. + set_target_properties(${CEF_TARGET} PROPERTIES INSTALL_RPATH "$ORIGIN") + set_target_properties(${CEF_TARGET} PROPERTIES BUILD_WITH_INSTALL_RPATH TRUE) + set_target_properties(${CEF_TARGET} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CEF_TARGET_OUT_DIR}) + + # Copy CEF binary and resource files to the target output directory. + COPY_FILES("${CEF_TARGET}" "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "${CEF_TARGET_OUT_DIR}") + COPY_FILES("${CEF_TARGET}" "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "${CEF_TARGET_OUT_DIR}") + + # Copy cefclient resource files to the target output directory. + COPY_FILES("${CEF_TARGET}" "${CEFCLIENT_RESOURCES_SRCS}" "${CMAKE_CURRENT_SOURCE_DIR}" "${CEF_TARGET_OUT_DIR}") + # Rename the "res" directory to "files". + RENAME_DIRECTORY("${CEF_TARGET}" "${CEF_TARGET_OUT_DIR}/res" "${CEF_TARGET_OUT_DIR}/files") + + # Set SUID permissions on the chrome-sandbox target. + SET_LINUX_SUID_PERMISSIONS("${CEF_TARGET}" "${CEF_TARGET_OUT_DIR}/chrome-sandbox") +endif() + + +# +# Mac OS X configuration. +# + +if(OS_MACOSX) + # Output paths for the app bundles. + set(CEF_APP "${CEF_TARGET_OUT_DIR}/${CEF_TARGET}.app") + set(CEF_HELPER_APP "${CEF_TARGET_OUT_DIR}/${CEF_HELPER_TARGET}.app") + + # Variable referenced from Info.plist files. + set(PRODUCT_NAME "${CEF_TARGET}") + + # Helper executable target. + add_executable(${CEF_HELPER_TARGET} MACOSX_BUNDLE ${CEFCLIENT_HELPER_SRCS}) + add_dependencies(${CEF_HELPER_TARGET} libcef_dll_wrapper) + target_link_libraries(${CEF_HELPER_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + set_target_properties(${CEF_HELPER_TARGET} PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/mac/helper-Info.plist + ) + + # Fix the framework link in the helper executable. + FIX_MACOSX_HELPER_FRAMEWORK_LINK(${CEF_HELPER_TARGET} ${CEF_HELPER_APP}) + + # Main executable target. + add_executable(${CEF_TARGET} MACOSX_BUNDLE ${CEFCLIENT_RESOURCES_SRCS} ${CEFCLIENT_SRCS}) + add_dependencies(${CEF_TARGET} libcef_dll_wrapper "${CEF_HELPER_TARGET}") + target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS} "-framework OpenGL") + set_target_properties(${CEF_TARGET} PROPERTIES + RESOURCE "${CEFCLIENT_RESOURCES_SRCS}" + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/mac/Info.plist + ) + + # Copy files into the main app bundle. + add_custom_command( + TARGET ${CEF_TARGET} + POST_BUILD + # Copy the helper app bundle into the Frameworks directory. + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${CEF_HELPER_APP}" + "${CEF_APP}/Contents/Frameworks/${CEF_HELPER_TARGET}.app" + # Copy the CEF framework into the Frameworks directory. + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${CEF_BINARY_DIR}/Chromium Embedded Framework.framework" + "${CEF_APP}/Contents/Frameworks/Chromium Embedded Framework.framework" + VERBATIM + ) + + # Fix the framework link in the main executable. + FIX_MACOSX_MAIN_FRAMEWORK_LINK(${CEF_TARGET} ${CEF_APP}) + + # Make the other helper app bundles. + MAKE_MACOSX_HELPERS(${CEF_TARGET} ${CEF_APP}) + + if(NOT ${CMAKE_GENERATOR} STREQUAL "Xcode") + # Manually process and copy over resource files. + # The Xcode generator handles this via the set_target_properties RESOURCE directive. + set(PREFIXES "mac/" "res/") # Remove these prefixes from input file paths. + COPY_MACOSX_RESOURCES("${CEFCLIENT_RESOURCES_SRCS}" "${PREFIXES}" "${CEF_TARGET}" "${CMAKE_CURRENT_SOURCE_DIR}" "${CEF_APP}") + endif() +endif() + + +# +# Windows configuration. +# + +if(OS_WINDOWS) + # Executable target. + add_executable(${CEF_TARGET} WIN32 ${CEFCLIENT_SRCS}) + add_dependencies(${CEF_TARGET} libcef_dll_wrapper) + target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS} "glu32.lib" "opengl32.lib") + + if(USE_SANDBOX) + # Logical target used to link the cef_sandbox library. + ADD_LOGICAL_TARGET("cef_sandbox_lib" "${CEF_SANDBOX_LIB_DEBUG}" "${CEF_SANDBOX_LIB_RELEASE}") + target_link_libraries(${CEF_TARGET} cef_sandbox_lib ${CEF_SANDBOX_STANDARD_LIBS}) + endif() + + # Add the custom manifest files to the executable. + ADD_WINDOWS_MANIFEST("${CEF_TARGET}") + + # Copy CEF binary and resource files to the target output directory. + COPY_FILES("${CEF_TARGET}" "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "${CEF_TARGET_OUT_DIR}") + COPY_FILES("${CEF_TARGET}" "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "${CEF_TARGET_OUT_DIR}") +endif() diff --git a/tests/cefclient/binding_test.cc b/tests/cefclient/binding_test.cc new file mode 100644 index 000000000..5dcebaabf --- /dev/null +++ b/tests/cefclient/binding_test.cc @@ -0,0 +1,57 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/binding_test.h" + +#include +#include + +#include "include/wrapper/cef_stream_resource_handler.h" + +namespace client { +namespace binding_test { + +namespace { + +const char kTestUrl[] = "http://tests/binding"; +const char kTestMessageName[] = "BindingTest"; + +// Handle messages in the browser process. +class Handler : public CefMessageRouterBrowserSide::Handler { + public: + Handler() {} + + // Called due to cefQuery execution in binding.html. + virtual bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) OVERRIDE { + // Only handle messages from the test URL. + const std::string& url = frame->GetURL(); + if (url.find(kTestUrl) != 0) + return false; + + const std::string& message_name = request; + if (message_name.find(kTestMessageName) == 0) { + // Reverse the string and return. + std::string result = message_name.substr(sizeof(kTestMessageName)); + std::reverse(result.begin(), result.end()); + callback->Success(result); + return true; + } + + return false; + } +}; + +} // namespace + +void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers) { + handlers.insert(new Handler()); +} + +} // namespace binding_test +} // namespace client diff --git a/tests/cefclient/binding_test.h b/tests/cefclient/binding_test.h new file mode 100644 index 000000000..d3a67c2b1 --- /dev/null +++ b/tests/cefclient/binding_test.h @@ -0,0 +1,20 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_BINDING_TEST_H_ +#define CEF_TESTS_CEFCLIENT_BINDING_TEST_H_ +#pragma once + +#include "cefclient/test_runner.h" + +namespace client { +namespace binding_test { + +// Handler creation. +void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers); + +} // namespace binding_test +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_BINDING_TEST_H_ diff --git a/tests/cefclient/bytes_write_handler.cc b/tests/cefclient/bytes_write_handler.cc new file mode 100644 index 000000000..778fa8747 --- /dev/null +++ b/tests/cefclient/bytes_write_handler.cc @@ -0,0 +1,98 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/bytes_write_handler.h" + +#include +#include + +#include "include/wrapper/cef_helpers.h" + +namespace client { + +BytesWriteHandler::BytesWriteHandler(size_t grow) + : grow_(grow), + datasize_(grow), + offset_(0) { + DCHECK_GT(grow, 0U); + data_ = malloc(grow); + DCHECK(data_ != NULL); +} + +BytesWriteHandler::~BytesWriteHandler() { + if (data_) + free(data_); +} + +size_t BytesWriteHandler::Write(const void* ptr, size_t size, size_t n) { + base::AutoLock lock_scope(lock_); + size_t rv; + if (offset_ + static_cast(size * n) >= datasize_ && + Grow(size * n) == 0) { + rv = 0; + } else { + memcpy(reinterpret_cast(data_) + offset_, ptr, size * n); + offset_ += size * n; + rv = n; + } + + return rv; +} + +int BytesWriteHandler::Seek(int64 offset, int whence) { + int rv = -1L; + base::AutoLock lock_scope(lock_); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > datasize_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { + int64 offset_abs = std::abs(offset); + if (offset_abs > datasize_) + break; + offset_ = datasize_ - offset_abs; + rv = 0; + break; + } + case SEEK_SET: + if (offset > datasize_ || offset < 0) + break; + offset_ = offset; + rv = 0; + break; + } + + return rv; +} + +int64 BytesWriteHandler::Tell() { + base::AutoLock lock_scope(lock_); + return offset_; +} + +int BytesWriteHandler::Flush() { + return 0; +} + +size_t BytesWriteHandler::Grow(size_t size) { + base::AutoLock lock_scope(lock_); + size_t rv; + size_t s = (size > grow_ ? size : grow_); + void* tmp = realloc(data_, datasize_ + s); + DCHECK(tmp != NULL); + if (tmp) { + data_ = tmp; + datasize_ += s; + rv = datasize_; + } else { + rv = 0; + } + + return rv; +} + +} // namespace client diff --git a/tests/cefclient/bytes_write_handler.h b/tests/cefclient/bytes_write_handler.h new file mode 100644 index 000000000..9c0f8d0a7 --- /dev/null +++ b/tests/cefclient/bytes_write_handler.h @@ -0,0 +1,44 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_BYTES_WRITE_HANDLER_H_ +#define CEF_TESTS_CEFCLIENT_BYTES_WRITE_HANDLER_H_ +#pragma once + +#include "include/base/cef_lock.h" +#include "include/cef_stream.h" + +namespace client { + +class BytesWriteHandler : public CefWriteHandler { + public: + explicit BytesWriteHandler(size_t grow); + ~BytesWriteHandler(); + + size_t Write(const void* ptr, size_t size, size_t n) OVERRIDE; + int Seek(int64 offset, int whence) OVERRIDE; + int64 Tell() OVERRIDE; + int Flush() OVERRIDE; + bool MayBlock() OVERRIDE { return false; } + + void* GetData() { return data_; } + int64 GetDataSize() { return offset_; } + + protected: + size_t Grow(size_t size); + + size_t grow_; + void* data_; + int64 datasize_; + int64 offset_; + + base::Lock lock_; + + IMPLEMENT_REFCOUNTING(BytesWriteHandler); + DISALLOW_COPY_AND_ASSIGN(BytesWriteHandler); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_BYTES_WRITE_HANDLER_H_ diff --git a/tests/cefclient/cefclient.exe.manifest b/tests/cefclient/cefclient.exe.manifest new file mode 100644 index 000000000..d36f084b6 --- /dev/null +++ b/tests/cefclient/cefclient.exe.manifest @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/tests/cefclient/cefclient.rc b/tests/cefclient/cefclient.rc new file mode 100644 index 000000000..6dc96f3d3 --- /dev/null +++ b/tests/cefclient/cefclient.rc @@ -0,0 +1,171 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#define APSTUDIO_HIDDEN_SYMBOLS +#include "windows.h" +#undef APSTUDIO_HIDDEN_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Binary +// + +IDS_BINDING BINARY "res\\binding.html" +IDS_DIALOGS BINARY "res\\dialogs.html" +IDS_LOCALSTORAGE BINARY "res\\localstorage.html" +IDS_LOGO BINARY "res\\logo.png" +IDS_OSRTEST BINARY "res\\osr_test.html" +IDS_OTHER_TESTS BINARY "res\\other_tests.html" +IDS_PERFORMANCE BINARY "res\\performance.html" +IDS_PERFORMANCE2 BINARY "res\\performance2.html" +IDS_TRANSPARENCY BINARY "res\\transparency.html" +IDS_WINDOW BINARY "res\\window.html" +IDS_XMLHTTPREQUEST BINARY "res\\xmlhttprequest.html" + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_CEFCLIENT ICON "res\cefclient.ico" +IDI_SMALL ICON "res\small.ico" + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDC_CEFCLIENT MENU +BEGIN + POPUP "&File" + BEGIN + MENUITEM "&Find...", ID_FIND + MENUITEM SEPARATOR + MENUITEM "E&xit", IDM_EXIT + END + POPUP "&Help" + BEGIN + MENUITEM "&About ...", IDM_ABOUT + END + POPUP "Tests" + BEGIN + MENUITEM "Get Source", ID_TESTS_GETSOURCE + MENUITEM "Get Text", ID_TESTS_GETTEXT + MENUITEM "Popup Window", ID_TESTS_POPUP + MENUITEM "Request", ID_TESTS_REQUEST + MENUITEM "Plugin Info", ID_TESTS_PLUGIN_INFO + MENUITEM "Zoom In", ID_TESTS_ZOOM_IN + MENUITEM "Zoom Out", ID_TESTS_ZOOM_OUT + MENUITEM "Zoom Reset", ID_TESTS_ZOOM_RESET + MENUITEM "Begin Tracing", ID_TESTS_TRACING_BEGIN + MENUITEM "End Tracing", ID_TESTS_TRACING_END + MENUITEM "Print", ID_TESTS_PRINT + MENUITEM "Other Tests", ID_TESTS_OTHER_TESTS + END +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Accelerator +// + +IDC_CEFCLIENT ACCELERATORS +BEGIN + "?", IDM_ABOUT, ASCII, ALT + "/", IDM_ABOUT, ASCII, ALT +END + + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_ABOUTBOX DIALOG 22, 17, 230, 75 +STYLE DS_SETFONT | DS_MODALFRAME | WS_CAPTION | WS_SYSMENU +CAPTION "About" +FONT 8, "System" +BEGIN + ICON IDI_CEFCLIENT,IDC_MYICON,14,9,16,16 + LTEXT "cefclient Version 1.0",IDC_STATIC,49,10,119,8,SS_NOPREFIX + LTEXT "Copyright (C) 2008",IDC_STATIC,49,20,119,8 + DEFPUSHBUTTON "OK",IDOK,195,6,30,11,WS_GROUP +END + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#define APSTUDIO_HIDDEN_SYMBOLS\r\n" + "#include ""windows.h""\r\n" + "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// String Table +// + +STRINGTABLE +BEGIN + IDS_APP_TITLE "cefclient" + IDC_CEFCLIENT "CEFCLIENT" + IDS_OSR_WIDGET_CLASS "CEFCLIENT-OSR-WIDGET" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/tests/cefclient/cefclient_gtk.cc b/tests/cefclient/cefclient_gtk.cc new file mode 100644 index 000000000..4ff14f01f --- /dev/null +++ b/tests/cefclient/cefclient_gtk.cc @@ -0,0 +1,502 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include +#include +#include + +#include +#undef Status // Definition conflicts with cef_urlrequest.h +#undef Success // Definition conflicts with cef_message_router.h + +#include +#include +#include + +#include "include/base/cef_logging.h" +#include "include/base/cef_scoped_ptr.h" +#include "include/cef_app.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/wrapper/cef_helpers.h" +#include "cefclient/client_app.h" +#include "cefclient/client_handler.h" +#include "cefclient/client_switches.h" +#include "cefclient/main_context_impl.h" +#include "cefclient/main_message_loop_std.h" +#include "cefclient/osr_widget_gtk.h" +#include "cefclient/resource.h" +#include "cefclient/test_runner.h" + +namespace client { +namespace { + +// The global ClientHandler reference. +CefRefPtr g_handler; + +// Height of the buttons at the top of the GTK window. +int g_toolbar_height = 0; + +// Height of the integrated menu bar (if any) at the top of the GTK window. +int g_menubar_height = 0; + + +// Used by off-screen rendering to find the associated CefBrowser. +class MainBrowserProvider : public OSRBrowserProvider { + virtual CefRefPtr GetBrowser() { + if (g_handler.get()) + return g_handler->GetBrowser(); + + return NULL; + } +} g_main_browser_provider; + + +int XErrorHandlerImpl(Display *display, XErrorEvent *event) { + LOG(WARNING) + << "X error received: " + << "type " << event->type << ", " + << "serial " << event->serial << ", " + << "error_code " << static_cast(event->error_code) << ", " + << "request_code " << static_cast(event->request_code) << ", " + << "minor_code " << static_cast(event->minor_code); + return 0; +} + +int XIOErrorHandlerImpl(Display *display) { + return 0; +} + +void destroy(GtkWidget* widget, gpointer data) { + // Quitting CEF is handled in ClientHandler::OnBeforeClose(). +} + +gboolean delete_event(GtkWidget* widget, GdkEvent* event, + GtkWindow* window) { + if (g_handler.get() && !g_handler->IsClosing()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) { + // Notify the browser window that we would like to close it. This + // will result in a call to ClientHandler::DoClose() if the + // JavaScript 'onbeforeunload' event handler allows it. + browser->GetHost()->CloseBrowser(false); + + // Cancel the close. + return TRUE; + } + } + + // Allow the close. + return FALSE; +} + +void TerminationSignalHandler(int signatl) { + MainMessageLoop::Get()->Quit(); +} + +void VboxSizeAllocated(GtkWidget* widget, + GtkAllocation* allocation, + void* data) { + if (g_handler) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser && !browser->GetHost()->IsWindowRenderingDisabled()) { + // Size the browser window to match the GTK widget. + ::Display* xdisplay = cef_get_xdisplay(); + ::Window xwindow = browser->GetHost()->GetWindowHandle(); + XWindowChanges changes = {0}; + changes.width = allocation->width; + changes.height = allocation->height - + (g_toolbar_height + g_menubar_height); + changes.y = g_toolbar_height + g_menubar_height; + XConfigureWindow(xdisplay, xwindow, CWHeight | CWWidth | CWY, &changes); + } + } +} + +void ToolbarSizeAllocated(GtkWidget* widget, + GtkAllocation* allocation, + void* data) { + g_toolbar_height = allocation->height; +} + +void MenubarSizeAllocated(GtkWidget* widget, + GtkAllocation* allocation, + void* data) { + g_menubar_height = allocation->height; +} + +gboolean WindowFocusIn(GtkWidget* widget, + GdkEventFocus* event, + gpointer user_data) { + if (g_handler && event->in) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser) { + if (browser->GetHost()->IsWindowRenderingDisabled()) { + // Give focus to the off-screen browser. + browser->GetHost()->SendFocusEvent(true); + } else { + // Give focus to the browser window. + browser->GetHost()->SetFocus(true); + return TRUE; + } + } + } + + return FALSE; +} + +gboolean WindowState(GtkWidget* widget, + GdkEventWindowState* event, + gpointer user_data) { + if (!(event->changed_mask & GDK_WINDOW_STATE_ICONIFIED)) + return TRUE; + + if (!g_handler) + return TRUE; + CefRefPtr browser = g_handler->GetBrowser(); + if (!browser) + return TRUE; + + const bool iconified = (event->new_window_state & GDK_WINDOW_STATE_ICONIFIED); + if (browser->GetHost()->IsWindowRenderingDisabled()) { + // Notify the off-screen browser that it was shown or hidden. + browser->GetHost()->WasHidden(iconified); + } else { + // Forward the state change event to the browser window. + ::Display* xdisplay = cef_get_xdisplay(); + ::Window xwindow = browser->GetHost()->GetWindowHandle(); + + // Retrieve the atoms required by the below XChangeProperty call. + const char* kAtoms[] = { + "_NET_WM_STATE", + "ATOM", + "_NET_WM_STATE_HIDDEN" + }; + Atom atoms[3]; + int result = XInternAtoms(xdisplay, const_cast(kAtoms), 3, false, + atoms); + if (!result) + NOTREACHED(); + + if (iconified) { + // Set the hidden property state value. + scoped_ptr data(new Atom[1]); + data[0] = atoms[2]; + + XChangeProperty(xdisplay, + xwindow, + atoms[0], // name + atoms[1], // type + 32, // size in bits of items in 'value' + PropModeReplace, + reinterpret_cast(data.get()), + 1); // num items + } else { + // Set an empty array of property state values. + XChangeProperty(xdisplay, + xwindow, + atoms[0], // name + atoms[1], // type + 32, // size in bits of items in 'value' + PropModeReplace, + NULL, + 0); // num items + } + } + + return TRUE; +} + +gboolean WindowConfigure(GtkWindow* window, + GdkEvent* event, + gpointer data) { + // Called when size, position or stack order changes. + if (g_handler) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser) { + // Notify the browser of move/resize events so that: + // - Popup windows are displayed in the correct location and dismissed + // when the window moves. + // - Drag&drop areas are updated accordingly. + browser->GetHost()->NotifyMoveOrResizeStarted(); + } + } + + return FALSE; // Don't stop this message. +} + +// Callback for Tests menu items. +gboolean MenuItemActivated(GtkWidget* widget, gpointer data) { + if (g_handler.get() && g_handler->GetBrowserId()) + test_runner::RunTest(g_handler->GetBrowser(), GPOINTER_TO_INT(data)); + + return FALSE; // Don't stop this message. +} + +// Callback for when you click the back button. +void BackButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->GoBack(); +} + +// Callback for when you click the forward button. +void ForwardButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->GoForward(); +} + +// Callback for when you click the stop button. +void StopButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->StopLoad(); +} + +// Callback for when you click the reload button. +void ReloadButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->Reload(); +} + +// Callback for when you press enter in the URL box. +void URLEntryActivate(GtkEntry* entry) { + if (!g_handler.get() || !g_handler->GetBrowserId()) + return; + + const gchar* url = gtk_entry_get_text(entry); + g_handler->GetBrowser()->GetMainFrame()->LoadURL(std::string(url).c_str()); +} + +gboolean URLEntryButtonPress(GtkWidget* widget, + GdkEventButton* event, + gpointer user_data) { + // Give focus to the GTK window. + GtkWidget* window = gtk_widget_get_ancestor(widget, + GTK_TYPE_WINDOW); + GdkWindow* gdk_window = gtk_widget_get_window(window); + ::Display* xdisplay = GDK_WINDOW_XDISPLAY(gdk_window); + ::Window xwindow = GDK_WINDOW_XID(gdk_window); + XSetInputFocus(xdisplay, xwindow, RevertToParent, CurrentTime); + + return FALSE; +} + +// GTK utility functions ---------------------------------------------- + +GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text, int id) { + GtkWidget* entry = gtk_menu_item_new_with_label(text); + g_signal_connect(entry, "activate", G_CALLBACK(MenuItemActivated), + GINT_TO_POINTER(id)); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), entry); + return entry; +} + +GtkWidget* CreateMenu(GtkWidget* menu_bar, const char* text) { + GtkWidget* menu_widget = gtk_menu_new(); + GtkWidget* menu_header = gtk_menu_item_new_with_label(text); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_header), menu_widget); + gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), menu_header); + return menu_widget; +} + +GtkWidget* CreateMenuBar() { + GtkWidget* menu_bar = gtk_menu_bar_new(); + GtkWidget* debug_menu = CreateMenu(menu_bar, "Tests"); + + AddMenuEntry(debug_menu, "Get Source", ID_TESTS_GETSOURCE); + AddMenuEntry(debug_menu, "Get Text", ID_TESTS_GETTEXT); + AddMenuEntry(debug_menu, "Popup Window", ID_TESTS_POPUP); + AddMenuEntry(debug_menu, "Request", ID_TESTS_REQUEST); + AddMenuEntry(debug_menu, "Plugin Info", ID_TESTS_PLUGIN_INFO); + AddMenuEntry(debug_menu, "Zoom In", ID_TESTS_ZOOM_IN); + AddMenuEntry(debug_menu, "Zoom Out", ID_TESTS_ZOOM_OUT); + AddMenuEntry(debug_menu, "Zoom Reset", ID_TESTS_ZOOM_RESET); + AddMenuEntry(debug_menu, "Begin Tracing", ID_TESTS_TRACING_BEGIN); + AddMenuEntry(debug_menu, "End Tracing", ID_TESTS_TRACING_END); + AddMenuEntry(debug_menu, "Print", ID_TESTS_PRINT); + AddMenuEntry(debug_menu, "Other Tests", ID_TESTS_OTHER_TESTS); + return menu_bar; +} + +int RunMain(int argc, char* argv[]) { + // Create a copy of |argv| on Linux because Chromium mangles the value + // internally (see issue #620). + CefScopedArgArray scoped_arg_array(argc, argv); + char** argv_copy = scoped_arg_array.array(); + + CefMainArgs main_args(argc, argv); + CefRefPtr app(new ClientApp); + + // Execute the secondary process, if any. + int exit_code = CefExecuteProcess(main_args, app.get(), NULL); + if (exit_code >= 0) + return exit_code; + + // Create the main context object. + scoped_ptr context(new MainContextImpl(argc, argv)); + + CefSettings settings; + + // Populate the settings based on command line arguments. + context->PopulateSettings(&settings); + + // Install xlib error handlers so that the application won't be terminated + // on non-fatal errors. + XSetErrorHandler(XErrorHandlerImpl); + XSetIOErrorHandler(XIOErrorHandlerImpl); + + // Create the main message loop object. + scoped_ptr message_loop(new MainMessageLoopStd); + + // Initialize CEF. + CefInitialize(main_args, settings, app.get(), NULL); + + // The Chromium sandbox requires that there only be a single thread during + // initialization. Therefore initialize GTK after CEF. + gtk_init(&argc, &argv_copy); + + // Perform gtkglext initialization required by the OSR example. + gtk_gl_init(&argc, &argv_copy); + + // Register scheme handlers. + test_runner::RegisterSchemeHandlers(); + + GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); + g_signal_connect(window, "focus-in-event", + G_CALLBACK(WindowFocusIn), NULL); + g_signal_connect(window, "window-state-event", + G_CALLBACK(WindowState), NULL); + g_signal_connect(G_OBJECT(window), "configure-event", + G_CALLBACK(WindowConfigure), NULL); + + GtkWidget* vbox = gtk_vbox_new(FALSE, 0); + g_signal_connect(vbox, "size-allocate", + G_CALLBACK(VboxSizeAllocated), NULL); + gtk_container_add(GTK_CONTAINER(window), vbox); + + GtkWidget* menu_bar = CreateMenuBar(); + g_signal_connect(menu_bar, "size-allocate", + G_CALLBACK(MenubarSizeAllocated), NULL); + + gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 0); + + GtkWidget* toolbar = gtk_toolbar_new(); + // Turn off the labels on the toolbar buttons. + gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); + g_signal_connect(toolbar, "size-allocate", + G_CALLBACK(ToolbarSizeAllocated), NULL); + + GtkToolItem* back = gtk_tool_button_new_from_stock(GTK_STOCK_GO_BACK); + g_signal_connect(back, "clicked", + G_CALLBACK(BackButtonClicked), NULL); + gtk_toolbar_insert(GTK_TOOLBAR(toolbar), back, -1 /* append */); + + GtkToolItem* forward = gtk_tool_button_new_from_stock(GTK_STOCK_GO_FORWARD); + g_signal_connect(forward, "clicked", + G_CALLBACK(ForwardButtonClicked), NULL); + gtk_toolbar_insert(GTK_TOOLBAR(toolbar), forward, -1 /* append */); + + GtkToolItem* reload = gtk_tool_button_new_from_stock(GTK_STOCK_REFRESH); + g_signal_connect(reload, "clicked", + G_CALLBACK(ReloadButtonClicked), NULL); + gtk_toolbar_insert(GTK_TOOLBAR(toolbar), reload, -1 /* append */); + + GtkToolItem* stop = gtk_tool_button_new_from_stock(GTK_STOCK_STOP); + g_signal_connect(stop, "clicked", + G_CALLBACK(StopButtonClicked), NULL); + gtk_toolbar_insert(GTK_TOOLBAR(toolbar), stop, -1 /* append */); + + GtkWidget* entry = gtk_entry_new(); + g_signal_connect(entry, "activate", + G_CALLBACK(URLEntryActivate), NULL); + g_signal_connect(entry, "button-press-event", + G_CALLBACK(URLEntryButtonPress), NULL); + + GtkToolItem* tool_item = gtk_tool_item_new(); + gtk_container_add(GTK_CONTAINER(tool_item), entry); + gtk_tool_item_set_expand(tool_item, TRUE); + gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool_item, -1); // append + + gtk_box_pack_start(GTK_BOX(vbox), toolbar, FALSE, FALSE, 0); + + g_signal_connect(G_OBJECT(window), "destroy", + G_CALLBACK(destroy), NULL); + g_signal_connect(G_OBJECT(window), "delete_event", + G_CALLBACK(delete_event), window); + + // Create the handler. + g_handler = new ClientHandler(); + g_handler->SetMainWindowHandle(vbox); + g_handler->SetEditWindowHandle(entry); + g_handler->SetButtonWindowHandles(GTK_WIDGET(back), GTK_WIDGET(forward), + GTK_WIDGET(reload), GTK_WIDGET(stop)); + + CefWindowInfo window_info; + CefBrowserSettings browserSettings; + + // Populate the browser settings based on command line arguments. + context->PopulateBrowserSettings(&browserSettings); + + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + if (command_line->HasSwitch(switches::kOffScreenRenderingEnabled)) { + const bool transparent = + command_line->HasSwitch(switches::kTransparentPaintingEnabled); + const bool show_update_rect = + command_line->HasSwitch(switches::kShowUpdateRect); + + // Create the GTKGL surface. + CefRefPtr osr_window = + OSRWindow::Create(&g_main_browser_provider, transparent, + show_update_rect, vbox); + + // Show the GTK window. + gtk_widget_show_all(GTK_WIDGET(window)); + + // The GTK window must be visible before we can retrieve the XID. + ::Window xwindow = + GDK_WINDOW_XID(gtk_widget_get_window(osr_window->GetWindowHandle())); + window_info.SetAsWindowless(xwindow, transparent); + g_handler->SetOSRHandler(osr_window.get()); + } else { + // Show the GTK window. + gtk_widget_show_all(GTK_WIDGET(window)); + + // The GTK window must be visible before we can retrieve the XID. + ::Window xwindow = GDK_WINDOW_XID(gtk_widget_get_window(window)); + window_info.SetAsChild(xwindow, + CefRect(0, g_toolbar_height, 800, 600 - g_toolbar_height)); + } + + // Create the browser window. + CefBrowserHost::CreateBrowserSync( + window_info, g_handler.get(), + g_handler->GetStartupURL(), browserSettings, NULL); + + // Install a signal handler so we clean up after ourselves. + signal(SIGINT, TerminationSignalHandler); + signal(SIGTERM, TerminationSignalHandler); + + // Run the message loop. This will block until Quit() is called. + int result = message_loop->Run(); + + // Shut down CEF. + CefShutdown(); + + // Release objects in reverse order of creation. + message_loop.reset(); + context.reset(); + + return result; +} + +} // namespace +} // namespace client + + +// Program entry point function. +int main(int argc, char* argv[]) { + return client::RunMain(argc, argv); +} diff --git a/tests/cefclient/cefclient_mac.mm b/tests/cefclient/cefclient_mac.mm new file mode 100644 index 000000000..f430b7c1b --- /dev/null +++ b/tests/cefclient/cefclient_mac.mm @@ -0,0 +1,555 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import +#include +#include "include/cef_app.h" +#import "include/cef_application_mac.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/client_app.h" +#include "cefclient/client_handler.h" +#include "cefclient/client_switches.h" +#include "cefclient/main_context_impl.h" +#include "cefclient/main_message_loop_std.h" +#include "cefclient/osr_widget_mac.h" +#include "cefclient/resource.h" +#include "cefclient/resource_util.h" +#include "cefclient/test_runner.h" + +namespace { + +// The global ClientHandler reference. +CefRefPtr g_handler; + +// Used by off-screen rendering to find the associated CefBrowser. +class MainBrowserProvider : public client::OSRBrowserProvider { + virtual CefRefPtr GetBrowser() { + if (g_handler.get()) + return g_handler->GetBrowser(); + + return NULL; + } +} g_main_browser_provider; + + +// Sizes for URL bar layout +#define BUTTON_HEIGHT 22 +#define BUTTON_WIDTH 72 +#define BUTTON_MARGIN 8 +#define URLBAR_HEIGHT 32 + +// Content area size for newly created windows. +const int kWindowWidth = 800; +const int kWindowHeight = 600; + + +NSButton* MakeButton(NSRect* rect, NSString* title, NSView* parent) { + NSButton* button = [[[NSButton alloc] initWithFrame:*rect] autorelease]; + [button setTitle:title]; + [button setBezelStyle:NSSmallSquareBezelStyle]; + [button setAutoresizingMask:(NSViewMaxXMargin | NSViewMinYMargin)]; + [parent addSubview:button]; + rect->origin.x += BUTTON_WIDTH; + return button; +} + +void AddMenuItem(NSMenu *menu, NSString* label, int idval) { + NSMenuItem* item = [menu addItemWithTitle:label + action:@selector(menuItemSelected:) + keyEquivalent:@""]; + [item setTag:idval]; +} + +} // namespace + +// Receives notifications from the application. Will delete itself when done. +@interface ClientAppDelegate : NSObject +- (void)createApplication:(id)object; +- (void)tryToTerminateApplication:(NSApplication*)app; +- (IBAction)menuItemSelected:(id)sender; +@end + +// Provide the CefAppProtocol implementation required by CEF. +@interface ClientApplication : NSApplication { +@private + BOOL handlingSendEvent_; +} +@end + +@implementation ClientApplication +- (BOOL)isHandlingSendEvent { + return handlingSendEvent_; +} + +- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { + handlingSendEvent_ = handlingSendEvent; +} + +- (void)sendEvent:(NSEvent*)event { + CefScopedSendingEvent sendingEventScoper; + [super sendEvent:event]; +} + +// |-terminate:| is the entry point for orderly "quit" operations in Cocoa. This +// includes the application menu's quit menu item and keyboard equivalent, the +// application's dock icon menu's quit menu item, "quit" (not "force quit") in +// the Activity Monitor, and quits triggered by user logout and system restart +// and shutdown. +// +// The default |-terminate:| implementation ends the process by calling exit(), +// and thus never leaves the main run loop. This is unsuitable for Chromium +// since Chromium depends on leaving the main run loop to perform an orderly +// shutdown. We support the normal |-terminate:| interface by overriding the +// default implementation. Our implementation, which is very specific to the +// needs of Chromium, works by asking the application delegate to terminate +// using its |-tryToTerminateApplication:| method. +// +// |-tryToTerminateApplication:| differs from the standard +// |-applicationShouldTerminate:| in that no special event loop is run in the +// case that immediate termination is not possible (e.g., if dialog boxes +// allowing the user to cancel have to be shown). Instead, this method tries to +// close all browsers by calling CloseBrowser(false) via +// ClientHandler::CloseAllBrowsers. Calling CloseBrowser will result in a call +// to ClientHandler::DoClose and execution of |-performClose:| on the NSWindow. +// DoClose sets a flag that is used to differentiate between new close events +// (e.g., user clicked the window close button) and in-progress close events +// (e.g., user approved the close window dialog). The NSWindowDelegate +// |-windowShouldClose:| method checks this flag and either calls +// CloseBrowser(false) in the case of a new close event or destructs the +// NSWindow in the case of an in-progress close event. +// ClientHandler::OnBeforeClose will be called after the CEF NSView hosted in +// the NSWindow is dealloc'ed. +// +// After the final browser window has closed ClientHandler::OnBeforeClose will +// begin actual tear-down of the application by calling CefQuitMessageLoop. +// This ends the NSApplication event loop and execution then returns to the +// main() function for cleanup before application termination. +// +// The standard |-applicationShouldTerminate:| is not supported, and code paths +// leading to it must be redirected. +- (void)terminate:(id)sender { + ClientAppDelegate* delegate = + static_cast([NSApp delegate]); + [delegate tryToTerminateApplication:self]; + // Return, don't exit. The application is responsible for exiting on its own. +} +@end + + +// Receives notifications from controls and the browser window. Will delete +// itself when done. +@interface ClientWindowDelegate : NSObject { + @private + NSWindow* window_; +} +- (id)initWithWindow:(NSWindow*)window; +- (IBAction)goBack:(id)sender; +- (IBAction)goForward:(id)sender; +- (IBAction)reload:(id)sender; +- (IBAction)stopLoading:(id)sender; +- (IBAction)takeURLStringValueFrom:(NSTextField *)sender; +- (void)alert:(NSString*)title withMessage:(NSString*)message; +@end + +@implementation ClientWindowDelegate + +- (id)initWithWindow:(NSWindow*)window { + if (self = [super init]) { + window_ = window; + [window_ setDelegate:self]; + + // Register for application hide/unhide notifications. + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationDidHide:) + name:NSApplicationDidHideNotification + object:nil]; + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(applicationDidUnhide:) + name:NSApplicationDidUnhideNotification + object:nil]; + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [super dealloc]; +} + +- (IBAction)goBack:(id)sender { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->GoBack(); +} + +- (IBAction)goForward:(id)sender { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->GoForward(); +} + +- (IBAction)reload:(id)sender { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->Reload(); +} + +- (IBAction)stopLoading:(id)sender { + if (g_handler.get() && g_handler->GetBrowserId()) + g_handler->GetBrowser()->StopLoad(); +} + +- (IBAction)takeURLStringValueFrom:(NSTextField *)sender { + if (!g_handler.get() || !g_handler->GetBrowserId()) + return; + + NSString *url = [sender stringValue]; + + // if it doesn't already have a prefix, add http. If we can't parse it, + // just don't bother rather than making things worse. + NSURL* tempUrl = [NSURL URLWithString:url]; + if (tempUrl && ![tempUrl scheme]) + url = [@"http://" stringByAppendingString:url]; + + std::string urlStr = [url UTF8String]; + g_handler->GetBrowser()->GetMainFrame()->LoadURL(urlStr); +} + +- (void)alert:(NSString*)title withMessage:(NSString*)message { + NSAlert *alert = [NSAlert alertWithMessageText:title + defaultButton:@"OK" + alternateButton:nil + otherButton:nil + informativeTextWithFormat:@"%@", message]; + [alert runModal]; +} + +// Called when we are activated (when we gain focus). +- (void)windowDidBecomeKey:(NSNotification*)notification { + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) { + if (CefCommandLine::GetGlobalCommandLine()->HasSwitch( + client::switches::kOffScreenRenderingEnabled)) { + browser->GetHost()->SendFocusEvent(true); + } else { + browser->GetHost()->SetFocus(true); + } + } + } +} + +// Called when we are deactivated (when we lose focus). +- (void)windowDidResignKey:(NSNotification*)notification { + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) { + if (CefCommandLine::GetGlobalCommandLine()->HasSwitch( + client::switches::kOffScreenRenderingEnabled)) { + browser->GetHost()->SendFocusEvent(false); + } else { + browser->GetHost()->SetFocus(false); + } + } + } +} + +// Called when we have been minimized. +- (void)windowDidMiniaturize:(NSNotification *)notification { + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) + browser->GetHost()->SetWindowVisibility(false); + } +} + +// Called when we have been unminimized. +- (void)windowDidDeminiaturize:(NSNotification *)notification { + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) + browser->GetHost()->SetWindowVisibility(true); + } +} + +// Called when the application has been hidden. +- (void)applicationDidHide:(NSNotification *)notification { + // If the window is miniaturized then nothing has really changed. + if (![window_ isMiniaturized]) { + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) + browser->GetHost()->SetWindowVisibility(false); + } + } +} + +// Called when the application has been unhidden. +- (void)applicationDidUnhide:(NSNotification *)notification { + // If the window is miniaturized then nothing has really changed. + if (![window_ isMiniaturized]) { + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) + browser->GetHost()->SetWindowVisibility(true); + } + } +} + +// Called when the window is about to close. Perform the self-destruction +// sequence by getting rid of the window. By returning YES, we allow the window +// to be removed from the screen. +- (BOOL)windowShouldClose:(id)window { + if (g_handler.get() && !g_handler->IsClosing()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) { + // Notify the browser window that we would like to close it. This + // will result in a call to ClientHandler::DoClose() if the + // JavaScript 'onbeforeunload' event handler allows it. + browser->GetHost()->CloseBrowser(false); + + // Cancel the close. + return NO; + } + } + + // Try to make the window go away. + [window autorelease]; + + // Clean ourselves up after clearing the stack of anything that might have the + // window on it. + [self performSelectorOnMainThread:@selector(cleanup:) + withObject:window + waitUntilDone:NO]; + + // Allow the close. + return YES; +} + +// Deletes itself. +- (void)cleanup:(id)window { + [self release]; +} + +@end + + +@implementation ClientAppDelegate + +// Create the application on the UI thread. +- (void)createApplication:(id)object { + [NSApplication sharedApplication]; + [NSBundle loadNibNamed:@"MainMenu" owner:NSApp]; + + // Set the delegate for application events. + [NSApp setDelegate:self]; + + // Add the Tests menu. + NSMenu* menubar = [NSApp mainMenu]; + NSMenuItem *testItem = [[[NSMenuItem alloc] initWithTitle:@"Tests" + action:nil + keyEquivalent:@""] autorelease]; + NSMenu *testMenu = [[[NSMenu alloc] initWithTitle:@"Tests"] autorelease]; + AddMenuItem(testMenu, @"Get Text", ID_TESTS_GETSOURCE); + AddMenuItem(testMenu, @"Get Source", ID_TESTS_GETTEXT); + AddMenuItem(testMenu, @"Popup Window", ID_TESTS_POPUP); + AddMenuItem(testMenu, @"Request", ID_TESTS_REQUEST); + AddMenuItem(testMenu, @"Plugin Info", ID_TESTS_PLUGIN_INFO); + AddMenuItem(testMenu, @"Zoom In", ID_TESTS_ZOOM_IN); + AddMenuItem(testMenu, @"Zoom Out", ID_TESTS_ZOOM_OUT); + AddMenuItem(testMenu, @"Zoom Reset", ID_TESTS_ZOOM_RESET); + AddMenuItem(testMenu, @"Begin Tracing", ID_TESTS_TRACING_BEGIN); + AddMenuItem(testMenu, @"End Tracing", ID_TESTS_TRACING_END); + AddMenuItem(testMenu, @"Print", ID_TESTS_PRINT); + AddMenuItem(testMenu, @"Other Tests", ID_TESTS_OTHER_TESTS); + [testItem setSubmenu:testMenu]; + [menubar addItem:testItem]; + + // Create the main application window. + NSRect screen_rect = [[NSScreen mainScreen] visibleFrame]; + NSRect window_rect = { {0, screen_rect.size.height - kWindowHeight}, + {kWindowWidth, kWindowHeight} }; + NSWindow* mainWnd = [[UnderlayOpenGLHostingWindow alloc] + initWithContentRect:window_rect + styleMask:(NSTitledWindowMask | + NSClosableWindowMask | + NSMiniaturizableWindowMask | + NSResizableWindowMask ) + backing:NSBackingStoreBuffered + defer:NO]; + [mainWnd setTitle:@"cefclient"]; + + // Create the delegate for control and browser window events. + ClientWindowDelegate* delegate = + [[ClientWindowDelegate alloc] initWithWindow:mainWnd]; + + // Rely on the window delegate to clean us up rather than immediately + // releasing when the window gets closed. We use the delegate to do + // everything from the autorelease pool so the window isn't on the stack + // during cleanup (ie, a window close from javascript). + [mainWnd setReleasedWhenClosed:NO]; + + NSView* contentView = [mainWnd contentView]; + + // Create the buttons. + NSRect button_rect = [contentView bounds]; + button_rect.origin.y = window_rect.size.height - URLBAR_HEIGHT + + (URLBAR_HEIGHT - BUTTON_HEIGHT) / 2; + button_rect.size.height = BUTTON_HEIGHT; + button_rect.origin.x += BUTTON_MARGIN; + button_rect.size.width = BUTTON_WIDTH; + + NSButton* button = MakeButton(&button_rect, @"Back", contentView); + [button setTarget:delegate]; + [button setAction:@selector(goBack:)]; + + button = MakeButton(&button_rect, @"Forward", contentView); + [button setTarget:delegate]; + [button setAction:@selector(goForward:)]; + + button = MakeButton(&button_rect, @"Reload", contentView); + [button setTarget:delegate]; + [button setAction:@selector(reload:)]; + + button = MakeButton(&button_rect, @"Stop", contentView); + [button setTarget:delegate]; + [button setAction:@selector(stopLoading:)]; + + // Create the URL text field. + button_rect.origin.x += BUTTON_MARGIN; + button_rect.size.width = [contentView bounds].size.width - + button_rect.origin.x - BUTTON_MARGIN; + NSTextField* editWnd = [[NSTextField alloc] initWithFrame:button_rect]; + [contentView addSubview:editWnd]; + [editWnd setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)]; + [editWnd setTarget:delegate]; + [editWnd setAction:@selector(takeURLStringValueFrom:)]; + [[editWnd cell] setWraps:NO]; + [[editWnd cell] setScrollable:YES]; + + // Create the handler. + g_handler = new client::ClientHandler(); + g_handler->SetMainWindowHandle(contentView); + g_handler->SetEditWindowHandle(editWnd); + + // Create the browser view. + CefWindowInfo window_info; + CefBrowserSettings settings; + + // Populate the browser settings based on command line arguments. + client::MainContext::Get()->PopulateBrowserSettings(&settings); + + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + if (command_line->HasSwitch(client::switches::kOffScreenRenderingEnabled)) { + const bool transparent = + command_line->HasSwitch(client::switches::kTransparentPaintingEnabled); + const bool show_update_rect = + command_line->HasSwitch(client::switches::kShowUpdateRect); + + CefRefPtr osr_window = + client::OSRWindow::Create(&g_main_browser_provider, transparent, + show_update_rect, contentView, + CefRect(0, 0, kWindowWidth, kWindowHeight)); + window_info.SetAsWindowless(osr_window->GetWindowHandle(), transparent); + g_handler->SetOSRHandler(osr_window->GetRenderHandler().get()); + } else { + // Initialize window info to the defaults for a child window. + window_info.SetAsChild(contentView, 0, 0, kWindowWidth, kWindowHeight); + } + + CefBrowserHost::CreateBrowser(window_info, g_handler.get(), + g_handler->GetStartupURL(), settings, NULL); + + // Show the window. + [mainWnd makeKeyAndOrderFront: nil]; + + // Size the window. + NSRect r = [mainWnd contentRectForFrameRect:[mainWnd frame]]; + r.size.width = kWindowWidth; + r.size.height = kWindowHeight + URLBAR_HEIGHT; + [mainWnd setFrame:[mainWnd frameRectForContentRect:r] display:YES]; +} + +- (void)tryToTerminateApplication:(NSApplication*)app { + if (g_handler.get() && !g_handler->IsClosing()) + g_handler->CloseAllBrowsers(false); +} + +- (IBAction)menuItemSelected:(id)sender { + NSMenuItem *item = (NSMenuItem*)sender; + if (g_handler.get() && g_handler->GetBrowserId()) + client::test_runner::RunTest(g_handler->GetBrowser(), [item tag]); +} + +- (NSApplicationTerminateReply)applicationShouldTerminate: + (NSApplication *)sender { + return NSTerminateNow; +} + +@end + + +namespace client { +namespace { + +int RunMain(int argc, char* argv[]) { + CefMainArgs main_args(argc, argv); + CefRefPtr app(new ClientApp); + + // Initialize the AutoRelease pool. + NSAutoreleasePool* autopool = [[NSAutoreleasePool alloc] init]; + + // Initialize the ClientApplication instance. + [ClientApplication sharedApplication]; + + // Create the main context object. + scoped_ptr context(new MainContextImpl(argc, argv)); + + CefSettings settings; + + // Populate the settings based on command line arguments. + context->PopulateSettings(&settings); + + // Create the main message loop object. + scoped_ptr message_loop(new MainMessageLoopStd); + + // Initialize CEF. + CefInitialize(main_args, settings, app.get(), NULL); + + // Register scheme handlers. + test_runner::RegisterSchemeHandlers(); + + // Create the application delegate and window. + NSObject* delegate = [[ClientAppDelegate alloc] init]; + [delegate performSelectorOnMainThread:@selector(createApplication:) + withObject:nil + waitUntilDone:NO]; + + // Run the message loop. This will block until Quit() is called. + int result = message_loop->Run(); + + // Shut down CEF. + CefShutdown(); + + // Release objects in reverse order of creation. + g_handler = NULL; + [delegate release]; + message_loop.reset(); + context.reset(); + [autopool release]; + + return result; +} + +} // namespace +} // namespace client + + +// Program entry point function. +int main(int argc, char* argv[]) { + return client::RunMain(argc, argv); +} diff --git a/tests/cefclient/cefclient_win.cc b/tests/cefclient/cefclient_win.cc new file mode 100644 index 000000000..1534e8536 --- /dev/null +++ b/tests/cefclient/cefclient_win.cc @@ -0,0 +1,620 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include +#include +#include +#include +#include +#include + +#include "include/base/cef_bind.h" +#include "include/cef_app.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_sandbox_win.h" +#include "include/wrapper/cef_closure_task.h" +#include "cefclient/client_app.h" +#include "cefclient/client_handler.h" +#include "cefclient/client_switches.h" +#include "cefclient/main_context_impl.h" +#include "cefclient/main_message_loop_multithreaded_win.h" +#include "cefclient/main_message_loop_std.h" +#include "cefclient/osr_widget_win.h" +#include "cefclient/resource.h" +#include "cefclient/test_runner.h" +#include "cefclient/util_win.h" + + +// When generating projects with CMake the CEF_USE_SANDBOX value will be defined +// automatically if using the required compiler version. Pass -DUSE_SANDBOX=OFF +// to the CMake command-line to disable use of the sandbox. +// Uncomment this line to manually enable sandbox support. +// #define CEF_USE_SANDBOX 1 + +#if defined(CEF_USE_SANDBOX) +// The cef_sandbox.lib static library is currently built with VS2013. It may not +// link successfully with other VS versions. +#pragma comment(lib, "cef_sandbox.lib") +#endif + +namespace client { +namespace { + +#define MAX_LOADSTRING 100 +#define MAX_URL_LENGTH 255 +#define BUTTON_WIDTH 72 +#define URLBAR_HEIGHT 24 + +// Global Variables: +HINSTANCE hInst; // current instance +TCHAR szTitle[MAX_LOADSTRING]; // The title bar text +TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name +TCHAR szOSRWindowClass[MAX_LOADSTRING]; // the OSR window class name +UINT uFindMsg; // Message identifier for find events. +HWND hFindDlg = NULL; // Handle for the find dialog. + +// Forward declarations of functions included in this code module. +ATOM RegisterMainClass(HINSTANCE hInstance); +BOOL CreateMainWindow(HINSTANCE, int); +LRESULT CALLBACK MainWndProc(HWND, UINT, WPARAM, LPARAM); +LRESULT CALLBACK FindWndProc(HWND, UINT, WPARAM, LPARAM); +INT_PTR CALLBACK AboutWndProc(HWND, UINT, WPARAM, LPARAM); + +// The global ClientHandler reference. +CefRefPtr g_handler; + +// Used by off-screen rendering to find the associated CefBrowser. +class MainBrowserProvider : public OSRBrowserProvider { + virtual CefRefPtr GetBrowser() { + if (g_handler.get()) + return g_handler->GetBrowser(); + + return NULL; + } +} g_main_browser_provider; + + +int RunMain(HINSTANCE hInstance, int nCmdShow) { + void* sandbox_info = NULL; + +#if defined(CEF_USE_SANDBOX) + // Manage the life span of the sandbox information object. This is necessary + // for sandbox support on Windows. See cef_sandbox_win.h for complete details. + CefScopedSandboxInfo scoped_sandbox; + sandbox_info = scoped_sandbox.sandbox_info(); +#endif + + CefMainArgs main_args(hInstance); + CefRefPtr app(new ClientApp); + + // Execute the secondary process, if any. + int exit_code = CefExecuteProcess(main_args, app.get(), sandbox_info); + if (exit_code >= 0) + return exit_code; + + // Create the main context object. + scoped_ptr context(new MainContextImpl(0, NULL)); + + CefSettings settings; + +#if !defined(CEF_USE_SANDBOX) + settings.no_sandbox = true; +#endif + + // Populate the settings based on command line arguments. + context->PopulateSettings(&settings); + + // Create the main message loop object. + scoped_ptr message_loop; + if (settings.multi_threaded_message_loop) + message_loop.reset(new MainMessageLoopMultithreadedWin); + else + message_loop.reset(new MainMessageLoopStd); + + // Initialize CEF. + CefInitialize(main_args, settings, app.get(), sandbox_info); + + // Register scheme handlers. + test_runner::RegisterSchemeHandlers(); + + // Initialize global strings + LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); + LoadString(hInstance, IDC_CEFCLIENT, szWindowClass, MAX_LOADSTRING); + LoadString(hInstance, IDS_OSR_WIDGET_CLASS, szOSRWindowClass, MAX_LOADSTRING); + RegisterMainClass(hInstance); + + // Perform application initialization + if (!CreateMainWindow(hInstance, nCmdShow)) + return FALSE; + + // Register the find event message. + uFindMsg = RegisterWindowMessage(FINDMSGSTRING); + + // Run the message loop. This will block until Quit() is called. + int result = message_loop->Run(); + + // Shut down CEF. + CefShutdown(); + + // Release objects in reverse order of creation. + message_loop.reset(); + context.reset(); + + return result; +} + +// Register the main window class. +ATOM RegisterMainClass(HINSTANCE hInstance) { + WNDCLASSEX wcex; + + wcex.cbSize = sizeof(WNDCLASSEX); + + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = MainWndProc; + wcex.cbClsExtra = 0; + wcex.cbWndExtra = 0; + wcex.hInstance = hInstance; + wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CEFCLIENT)); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); + wcex.lpszMenuName = MAKEINTRESOURCE(IDC_CEFCLIENT); + wcex.lpszClassName = szWindowClass; + wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); + + return RegisterClassEx(&wcex); +} + +// Create and show the main window. +BOOL CreateMainWindow(HINSTANCE hInstance, int nCmdShow) { + HWND hWnd; + + hInst = hInstance; // Store instance handle in our global variable + + hWnd = CreateWindow(szWindowClass, szTitle, + WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, + CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); + + if (!hWnd) + return FALSE; + + ShowWindow(hWnd, nCmdShow); + UpdateWindow(hWnd); + + return TRUE; +} + +// Set focus to |browser| on the UI thread. +static void SetFocusToBrowser(CefRefPtr browser) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, base::Bind(&SetFocusToBrowser, browser)); + return; + } + + if (!g_handler) + return; + + if (CefCommandLine::GetGlobalCommandLine()->HasSwitch( + switches::kOffScreenRenderingEnabled)) { + // Give focus to the OSR window. + CefRefPtr osr_window = + static_cast(g_handler->GetOSRHandler().get()); + if (osr_window) + ::SetFocus(osr_window->hwnd()); + } else { + // Give focus to the browser. + browser->GetHost()->SetFocus(true); + } +} + +// Window procedure for the main window. +LRESULT CALLBACK MainWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam) { + static HWND backWnd = NULL, forwardWnd = NULL, reloadWnd = NULL, + stopWnd = NULL, editWnd = NULL; + static WNDPROC editWndOldProc = NULL; + + // Static members used for the find dialog. + static FINDREPLACE fr; + static WCHAR szFindWhat[80] = {0}; + static WCHAR szLastFindWhat[80] = {0}; + static bool findNext = false; + static bool lastMatchCase = false; + + int wmId, wmEvent; + PAINTSTRUCT ps; + HDC hdc; + + if (hWnd == editWnd) { + // Callback for the edit window + switch (message) { + case WM_CHAR: + if (wParam == VK_RETURN && g_handler.get()) { + // When the user hits the enter key load the URL + CefRefPtr browser = g_handler->GetBrowser(); + wchar_t strPtr[MAX_URL_LENGTH+1] = {0}; + *((LPWORD)strPtr) = MAX_URL_LENGTH; + LRESULT strLen = SendMessage(hWnd, EM_GETLINE, 0, (LPARAM)strPtr); + if (strLen > 0) { + strPtr[strLen] = 0; + browser->GetMainFrame()->LoadURL(strPtr); + } + + return 0; + } + } + + return (LRESULT)CallWindowProc(editWndOldProc, hWnd, message, wParam, + lParam); + } else if (message == uFindMsg) { + // Find event. + LPFINDREPLACE lpfr = (LPFINDREPLACE)lParam; + + if (lpfr->Flags & FR_DIALOGTERM) { + // The find dialog box has been dismissed so invalidate the handle and + // reset the search results. + hFindDlg = NULL; + if (g_handler.get()) { + g_handler->GetBrowser()->GetHost()->StopFinding(true); + szLastFindWhat[0] = 0; + findNext = false; + } + return 0; + } + + if ((lpfr->Flags & FR_FINDNEXT) && g_handler.get()) { + // Search for the requested string. + bool matchCase = (lpfr->Flags & FR_MATCHCASE?true:false); + if (matchCase != lastMatchCase || + (matchCase && wcsncmp(szFindWhat, szLastFindWhat, + sizeof(szLastFindWhat)/sizeof(WCHAR)) != 0) || + (!matchCase && _wcsnicmp(szFindWhat, szLastFindWhat, + sizeof(szLastFindWhat)/sizeof(WCHAR)) != 0)) { + // The search string has changed, so reset the search results. + if (szLastFindWhat[0] != 0) { + g_handler->GetBrowser()->GetHost()->StopFinding(true); + findNext = false; + } + lastMatchCase = matchCase; + wcscpy_s(szLastFindWhat, sizeof(szLastFindWhat)/sizeof(WCHAR), + szFindWhat); + } + + g_handler->GetBrowser()->GetHost()->Find(0, lpfr->lpstrFindWhat, + (lpfr->Flags & FR_DOWN)?true:false, matchCase, findNext); + if (!findNext) + findNext = true; + } + + return 0; + } else { + // Callback for the main window + switch (message) { + case WM_CREATE: { + // Create the single static handler class instance + g_handler = new ClientHandler(); + g_handler->SetMainWindowHandle(hWnd); + + // Create the child windows used for navigation + RECT rect; + int x = 0; + + GetClientRect(hWnd, &rect); + + backWnd = CreateWindow(L"BUTTON", L"Back", + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON + | WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT, + hWnd, (HMENU) IDC_NAV_BACK, hInst, 0); + x += BUTTON_WIDTH; + + forwardWnd = CreateWindow(L"BUTTON", L"Forward", + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON + | WS_DISABLED, x, 0, BUTTON_WIDTH, + URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_FORWARD, + hInst, 0); + x += BUTTON_WIDTH; + + reloadWnd = CreateWindow(L"BUTTON", L"Reload", + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON + | WS_DISABLED, x, 0, BUTTON_WIDTH, + URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_RELOAD, + hInst, 0); + x += BUTTON_WIDTH; + + stopWnd = CreateWindow(L"BUTTON", L"Stop", + WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON + | WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT, + hWnd, (HMENU) IDC_NAV_STOP, hInst, 0); + x += BUTTON_WIDTH; + + editWnd = CreateWindow(L"EDIT", 0, + WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | + ES_AUTOVSCROLL | ES_AUTOHSCROLL| WS_DISABLED, + x, 0, rect.right - BUTTON_WIDTH * 4, + URLBAR_HEIGHT, hWnd, 0, hInst, 0); + + // Assign the edit window's WNDPROC to this function so that we can + // capture the enter key + editWndOldProc = + reinterpret_cast(GetWindowLongPtr(editWnd, GWLP_WNDPROC)); + SetWindowLongPtr(editWnd, GWLP_WNDPROC, + reinterpret_cast(MainWndProc)); + g_handler->SetEditWindowHandle(editWnd); + g_handler->SetButtonWindowHandles( + backWnd, forwardWnd, reloadWnd, stopWnd); + + rect.top += URLBAR_HEIGHT; + + CefWindowInfo info; + CefBrowserSettings settings; + + // Populate the browser settings based on command line arguments. + MainContext::Get()->PopulateBrowserSettings(&settings); + + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + if (command_line->HasSwitch(switches::kOffScreenRenderingEnabled)) { + const bool transparent = + command_line->HasSwitch(switches::kTransparentPaintingEnabled); + const bool show_update_rect = + command_line->HasSwitch(switches::kShowUpdateRect); + + CefRefPtr osr_window = + OSRWindow::Create(&g_main_browser_provider, transparent, + show_update_rect); + osr_window->CreateWidget(hWnd, rect, hInst, szOSRWindowClass); + info.SetAsWindowless(osr_window->hwnd(), transparent); + g_handler->SetOSRHandler(osr_window.get()); + } else { + // Initialize window info to the defaults for a child window. + info.SetAsChild(hWnd, rect); + } + + // Creat the new child browser window + CefBrowserHost::CreateBrowser(info, g_handler.get(), + g_handler->GetStartupURL(), settings, NULL); + + return 0; + } + + case WM_COMMAND: { + CefRefPtr browser; + if (g_handler.get()) + browser = g_handler->GetBrowser(); + + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + + if (wmId >= ID_TESTS_FIRST && wmId <= ID_TESTS_LAST) { + test_runner::RunTest(browser, wmId); + return 0; + } + + // Parse the menu selections: + switch (wmId) { + case IDM_ABOUT: + DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, AboutWndProc); + return 0; + case IDM_EXIT: + if (g_handler.get()) + g_handler->CloseAllBrowsers(false); + return 0; + case ID_FIND: + if (!hFindDlg) { + // Create the find dialog. + ZeroMemory(&fr, sizeof(fr)); + fr.lStructSize = sizeof(fr); + fr.hwndOwner = hWnd; + fr.lpstrFindWhat = szFindWhat; + fr.wFindWhatLen = sizeof(szFindWhat); + fr.Flags = FR_HIDEWHOLEWORD | FR_DOWN; + + hFindDlg = FindText(&fr); + + // Override the dialog's window procedure. + WNDPROC wndproc_old = SetWndProcPtr(hFindDlg, FindWndProc); + + // Associate |wndproc_old| with the dialog. + SetUserDataPtr(hFindDlg, wndproc_old); + } else { + // Give focus to the existing find dialog. + ::SetFocus(hFindDlg); + } + return 0; + case IDC_NAV_BACK: // Back button + if (browser.get()) + browser->GoBack(); + return 0; + case IDC_NAV_FORWARD: // Forward button + if (browser.get()) + browser->GoForward(); + return 0; + case IDC_NAV_RELOAD: // Reload button + if (browser.get()) + browser->Reload(); + return 0; + case IDC_NAV_STOP: // Stop button + if (browser.get()) + browser->StopLoad(); + return 0; + } + break; + } + + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + EndPaint(hWnd, &ps); + return 0; + + case WM_SETFOCUS: + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser) + SetFocusToBrowser(browser); + } + return 0; + + case WM_SIZE: { + if (!g_handler.get()) + break; + + // For off-screen browsers when the frame window is minimized set the + // browser as hidden to reduce resource usage. + const bool offscreen = CefCommandLine::GetGlobalCommandLine()->HasSwitch( + switches::kOffScreenRenderingEnabled); + if (offscreen) { + CefRefPtr osr_window = + static_cast(g_handler->GetOSRHandler().get()); + if (osr_window) + osr_window->WasHidden(wParam == SIZE_MINIMIZED); + } + + if (g_handler->GetBrowser()) { + // Retrieve the window handle (parent window with off-screen rendering). + CefWindowHandle hwnd = + g_handler->GetBrowser()->GetHost()->GetWindowHandle(); + if (hwnd) { + if (wParam == SIZE_MINIMIZED) { + // For windowed browsers when the frame window is minimized set the + // browser window size to 0x0 to reduce resource usage. + if (!offscreen) { + SetWindowPos(hwnd, NULL, + 0, 0, 0, 0, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); + } + } else { + // Resize the window and address bar to match the new frame size. + RECT rect; + GetClientRect(hWnd, &rect); + rect.top += URLBAR_HEIGHT; + + int urloffset = rect.left + BUTTON_WIDTH * 4; + + HDWP hdwp = BeginDeferWindowPos(1); + hdwp = DeferWindowPos(hdwp, editWnd, NULL, urloffset, + 0, rect.right - urloffset, URLBAR_HEIGHT, SWP_NOZORDER); + hdwp = DeferWindowPos(hdwp, hwnd, NULL, + rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, SWP_NOZORDER); + EndDeferWindowPos(hdwp); + } + } + } + } break; + + case WM_MOVING: + case WM_MOVE: + // Notify the browser of move events so that popup windows are displayed + // in the correct location and dismissed when the window moves. + if (g_handler.get() && g_handler->GetBrowser()) + g_handler->GetBrowser()->GetHost()->NotifyMoveOrResizeStarted(); + return 0; + + case WM_ERASEBKGND: + if (g_handler.get() && g_handler->GetBrowser()) { + CefWindowHandle hwnd = + g_handler->GetBrowser()->GetHost()->GetWindowHandle(); + if (hwnd) { + // Dont erase the background if the browser window has been loaded + // (this avoids flashing) + return 0; + } + } + break; + + case WM_ENTERMENULOOP: + if (!wParam) { + // Entering the menu loop for the application menu. + CefSetOSModalLoop(true); + } + break; + + case WM_EXITMENULOOP: + if (!wParam) { + // Exiting the menu loop for the application menu. + CefSetOSModalLoop(false); + } + break; + + case WM_CLOSE: + if (g_handler.get() && !g_handler->IsClosing()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) { + // Notify the browser window that we would like to close it. This + // will result in a call to ClientHandler::DoClose() if the + // JavaScript 'onbeforeunload' event handler allows it. + browser->GetHost()->CloseBrowser(false); + + // Cancel the close. + return 0; + } + } + + // Allow the close. + break; + + case WM_DESTROY: + // Quitting CEF is handled in ClientHandler::OnBeforeClose(). + return 0; + } + + return DefWindowProc(hWnd, message, wParam, lParam); + } +} + +// Window procedure for the find dialog. +LRESULT CALLBACK FindWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam) { + REQUIRE_MAIN_THREAD(); + + WNDPROC old_wndproc = GetUserDataPtr(hWnd); + DCHECK(old_wndproc); + + switch (message) { + case WM_ACTIVATE: + // Set this dialog as current when activated. + MainMessageLoop::Get()->SetCurrentModelessDialog( + wParam == 0 ? NULL : hWnd); + return FALSE; + case WM_NCDESTROY: + // Clear the reference to |old_wndproc|. + SetUserDataPtr(hWnd, NULL); + break; + } + + return CallWindowProc(old_wndproc, hWnd, message, wParam, lParam); +} + +// Window procedure for the about dialog. +INT_PTR CALLBACK AboutWndProc(HWND hDlg, UINT message, WPARAM wParam, + LPARAM lParam) { + UNREFERENCED_PARAMETER(lParam); + switch (message) { + case WM_INITDIALOG: + return (INT_PTR)TRUE; + + case WM_COMMAND: + if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { + EndDialog(hDlg, LOWORD(wParam)); + return (INT_PTR)TRUE; + } + break; + } + return (INT_PTR)FALSE; +} + +} // namespace +} // namespace client + + +// Program entry point function. +int APIENTRY wWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + return client::RunMain(hInstance, nCmdShow); +} diff --git a/tests/cefclient/client_app.cc b/tests/cefclient/client_app.cc new file mode 100644 index 000000000..c23371f60 --- /dev/null +++ b/tests/cefclient/client_app.cc @@ -0,0 +1,164 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// This file is shared by cefclient and cef_unittests so don't include using +// a qualified path. +#include "client_app.h" // NOLINT(build/include) + +#include + +#include "include/cef_cookie.h" +#include "include/cef_process_message.h" +#include "include/cef_task.h" +#include "include/cef_v8.h" +#include "include/wrapper/cef_helpers.h" + +namespace client { + +ClientApp::ClientApp() { +} + +void ClientApp::OnRegisterCustomSchemes( + CefRefPtr registrar) { + // Default schemes that support cookies. + cookieable_schemes_.push_back("http"); + cookieable_schemes_.push_back("https"); + + RegisterCustomSchemes(registrar, cookieable_schemes_); +} + +void ClientApp::OnContextInitialized() { + CreateBrowserDelegates(browser_delegates_); + + // Register cookieable schemes with the global cookie manager. + CefRefPtr manager = CefCookieManager::GetGlobalManager(); + DCHECK(manager.get()); + manager->SetSupportedSchemes(cookieable_schemes_); + + print_handler_ = CreatePrintHandler(); + + BrowserDelegateSet::iterator it = browser_delegates_.begin(); + for (; it != browser_delegates_.end(); ++it) + (*it)->OnContextInitialized(this); +} + +void ClientApp::OnBeforeChildProcessLaunch( + CefRefPtr command_line) { + BrowserDelegateSet::iterator it = browser_delegates_.begin(); + for (; it != browser_delegates_.end(); ++it) + (*it)->OnBeforeChildProcessLaunch(this, command_line); +} + +void ClientApp::OnRenderProcessThreadCreated( + CefRefPtr extra_info) { + BrowserDelegateSet::iterator it = browser_delegates_.begin(); + for (; it != browser_delegates_.end(); ++it) + (*it)->OnRenderProcessThreadCreated(this, extra_info); +} + +void ClientApp::OnRenderThreadCreated(CefRefPtr extra_info) { + CreateRenderDelegates(render_delegates_); + + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnRenderThreadCreated(this, extra_info); +} + +void ClientApp::OnWebKitInitialized() { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnWebKitInitialized(this); +} + +void ClientApp::OnBrowserCreated(CefRefPtr browser) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnBrowserCreated(this, browser); +} + +void ClientApp::OnBrowserDestroyed(CefRefPtr browser) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnBrowserDestroyed(this, browser); +} + +CefRefPtr ClientApp::GetLoadHandler() { + CefRefPtr load_handler; + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end() && !load_handler.get(); ++it) + load_handler = (*it)->GetLoadHandler(this); + + return load_handler; +} + +bool ClientApp::OnBeforeNavigation(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavigationType navigation_type, + bool is_redirect) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) { + if ((*it)->OnBeforeNavigation(this, browser, frame, request, + navigation_type, is_redirect)) { + return true; + } + } + + return false; +} + +void ClientApp::OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnContextCreated(this, browser, frame, context); +} + +void ClientApp::OnContextReleased(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnContextReleased(this, browser, frame, context); +} + +void ClientApp::OnUncaughtException(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context, + CefRefPtr exception, + CefRefPtr stackTrace) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) { + (*it)->OnUncaughtException(this, browser, frame, context, exception, + stackTrace); + } +} + +void ClientApp::OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) { + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end(); ++it) + (*it)->OnFocusedNodeChanged(this, browser, frame, node); +} + +bool ClientApp::OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) { + DCHECK_EQ(source_process, PID_BROWSER); + + bool handled = false; + + RenderDelegateSet::iterator it = render_delegates_.begin(); + for (; it != render_delegates_.end() && !handled; ++it) { + handled = (*it)->OnProcessMessageReceived(this, browser, source_process, + message); + } + + return handled; +} + +} // namespace client diff --git a/tests/cefclient/client_app.h b/tests/cefclient/client_app.h new file mode 100644 index 000000000..c95ca35fc --- /dev/null +++ b/tests/cefclient/client_app.h @@ -0,0 +1,191 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_CLIENT_APP_H_ +#define CEF_TESTS_CEFCLIENT_CLIENT_APP_H_ +#pragma once + +#include +#include +#include +#include +#include +#include "include/cef_app.h" + +namespace client { + +class ClientApp : public CefApp, + public CefBrowserProcessHandler, + public CefRenderProcessHandler { + public: + // Interface for browser delegates. All BrowserDelegates must be returned via + // CreateBrowserDelegates. Do not perform work in the BrowserDelegate + // constructor. See CefBrowserProcessHandler for documentation. + class BrowserDelegate : public virtual CefBase { + public: + virtual void OnContextInitialized(CefRefPtr app) {} + + virtual void OnBeforeChildProcessLaunch( + CefRefPtr app, + CefRefPtr command_line) {} + + virtual void OnRenderProcessThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) {} + }; + + typedef std::set > BrowserDelegateSet; + + // Interface for renderer delegates. All RenderDelegates must be returned via + // CreateRenderDelegates. Do not perform work in the RenderDelegate + // constructor. See CefRenderProcessHandler for documentation. + class RenderDelegate : public virtual CefBase { + public: + virtual void OnRenderThreadCreated(CefRefPtr app, + CefRefPtr extra_info) {} + + virtual void OnWebKitInitialized(CefRefPtr app) {} + + virtual void OnBrowserCreated(CefRefPtr app, + CefRefPtr browser) {} + + virtual void OnBrowserDestroyed(CefRefPtr app, + CefRefPtr browser) {} + + virtual CefRefPtr GetLoadHandler(CefRefPtr app) { + return NULL; + } + + virtual bool OnBeforeNavigation(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + cef_navigation_type_t navigation_type, + bool is_redirect) { + return false; + } + + virtual void OnContextCreated(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) {} + + virtual void OnContextReleased(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) {} + + virtual void OnUncaughtException(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context, + CefRefPtr exception, + CefRefPtr stackTrace) {} + + virtual void OnFocusedNodeChanged(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) {} + + // Called when a process message is received. Return true if the message was + // handled and should not be passed on to other handlers. RenderDelegates + // should check for unique message names to avoid interfering with each + // other. + virtual bool OnProcessMessageReceived( + CefRefPtr app, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) { + return false; + } + }; + + typedef std::set > RenderDelegateSet; + + ClientApp(); + + private: + // Creates all of the BrowserDelegate objects. Implemented in + // client_app_delegates. + static void CreateBrowserDelegates(BrowserDelegateSet& delegates); + + // Creates all of the RenderDelegate objects. Implemented in + // client_app_delegates. + static void CreateRenderDelegates(RenderDelegateSet& delegates); + + // Registers custom schemes. Implemented in client_app_delegates. + static void RegisterCustomSchemes(CefRefPtr registrar, + std::vector& cookiable_schemes); + + // Create the Linux print handler. Implemented in client_app_delegates. + static CefRefPtr CreatePrintHandler(); + + // CefApp methods. + void OnRegisterCustomSchemes( + CefRefPtr registrar) OVERRIDE; + CefRefPtr GetBrowserProcessHandler() OVERRIDE { + return this; + } + CefRefPtr GetRenderProcessHandler() OVERRIDE { + return this; + } + + // CefBrowserProcessHandler methods. + void OnContextInitialized() OVERRIDE; + void OnBeforeChildProcessLaunch( + CefRefPtr command_line) OVERRIDE; + void OnRenderProcessThreadCreated( + CefRefPtr extra_info) OVERRIDE; + CefRefPtr GetPrintHandler() OVERRIDE { + return print_handler_; + } + + // CefRenderProcessHandler methods. + void OnRenderThreadCreated(CefRefPtr extra_info) OVERRIDE; + void OnWebKitInitialized() OVERRIDE; + void OnBrowserCreated(CefRefPtr browser) OVERRIDE; + void OnBrowserDestroyed(CefRefPtr browser) OVERRIDE; + CefRefPtr GetLoadHandler() OVERRIDE; + bool OnBeforeNavigation(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavigationType navigation_type, + bool is_redirect) OVERRIDE; + void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE; + void OnContextReleased(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE; + void OnUncaughtException(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context, + CefRefPtr exception, + CefRefPtr stackTrace) OVERRIDE; + void OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) OVERRIDE; + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) OVERRIDE; + + // Set of supported BrowserDelegates. Only used in the browser process. + BrowserDelegateSet browser_delegates_; + + // Set of supported RenderDelegates. Only used in the renderer process. + RenderDelegateSet render_delegates_; + + // Schemes that will be registered with the global cookie manager. Used in + // both the browser and renderer process. + std::vector cookieable_schemes_; + + CefRefPtr print_handler_; + + IMPLEMENT_REFCOUNTING(ClientApp); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_CLIENT_APP_H_ diff --git a/tests/cefclient/client_app_delegates.cc b/tests/cefclient/client_app_delegates.cc new file mode 100644 index 000000000..1339b0d53 --- /dev/null +++ b/tests/cefclient/client_app_delegates.cc @@ -0,0 +1,42 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/client_app.h" +#include "cefclient/client_renderer.h" +#include "cefclient/performance_test.h" +#include "cefclient/scheme_test.h" + +#if defined(OS_LINUX) +#include "cefclient/print_handler_gtk.h" +#endif + +namespace client { + +// static +void ClientApp::CreateBrowserDelegates(BrowserDelegateSet& delegates) { +} + +// static +void ClientApp::CreateRenderDelegates(RenderDelegateSet& delegates) { + renderer::CreateRenderDelegates(delegates); + performance_test::CreateRenderDelegates(delegates); +} + +// static +void ClientApp::RegisterCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes) { + scheme_test::RegisterCustomSchemes(registrar, cookiable_schemes); +} + +// static +CefRefPtr ClientApp::CreatePrintHandler() { +#if defined(OS_LINUX) + return new ClientPrintHandlerGtk(); +#else + return NULL; +#endif +} + +} // namespace client diff --git a/tests/cefclient/client_handler.cc b/tests/cefclient/client_handler.cc new file mode 100644 index 000000000..2861dd6da --- /dev/null +++ b/tests/cefclient/client_handler.cc @@ -0,0 +1,739 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/client_handler.h" +#include +#include +#include +#include +#include +#include + +#include "include/base/cef_bind.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_path_util.h" +#include "include/cef_process_util.h" +#include "include/cef_trace.h" +#include "include/cef_url.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_stream_resource_handler.h" +#include "cefclient/client_renderer.h" +#include "cefclient/client_switches.h" +#include "cefclient/main_context.h" +#include "cefclient/main_message_loop.h" +#include "cefclient/resource_util.h" +#include "cefclient/test_runner.h" + +#if defined(OS_LINUX) +#include "cefclient/dialog_handler_gtk.h" +#endif + +namespace client { + +#if defined(OS_WIN) +#define NEWLINE "\r\n" +#else +#define NEWLINE "\n" +#endif + +namespace { + +// Custom menu command Ids. +enum client_menu_ids { + CLIENT_ID_SHOW_DEVTOOLS = MENU_ID_USER_FIRST, + CLIENT_ID_CLOSE_DEVTOOLS, + CLIENT_ID_INSPECT_ELEMENT, + CLIENT_ID_TESTMENU_SUBMENU, + CLIENT_ID_TESTMENU_CHECKITEM, + CLIENT_ID_TESTMENU_RADIOITEM1, + CLIENT_ID_TESTMENU_RADIOITEM2, + CLIENT_ID_TESTMENU_RADIOITEM3, +}; + +} // namespace + +int ClientHandler::browser_count_ = 0; + +ClientHandler::ClientHandler() + : startup_url_(MainContext::Get()->GetMainURL()), + browser_id_(0), + is_closing_(false), + main_handle_(NULL), + edit_handle_(NULL), + back_handle_(NULL), + forward_handle_(NULL), + stop_handle_(NULL), + reload_handle_(NULL), + console_log_file_(MainContext::Get()->GetConsoleLogPath()), + first_console_message_(true), + focus_on_editable_field_(false) { + DCHECK(!console_log_file_.empty()); + +#if defined(OS_LINUX) + // Provide the GTK-based dialog implementation on Linux. + CefRefPtr dialog_handler = + new ClientDialogHandlerGtk(); + dialog_handler_ = dialog_handler.get(); + jsdialog_handler_ = dialog_handler.get(); +#endif + + // Read command line settings. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + mouse_cursor_change_disabled_ = + command_line->HasSwitch(switches::kMouseCursorChangeDisabled); +} + +ClientHandler::~ClientHandler() { +} + +bool ClientHandler::OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) { + CEF_REQUIRE_UI_THREAD(); + + if (message_router_->OnProcessMessageReceived(browser, source_process, + message)) { + return true; + } + + // Check for messages from the client renderer. + std::string message_name = message->GetName(); + if (message_name == renderer::kFocusedNodeChangedMessage) { + // A message is sent from ClientRenderDelegate to tell us whether the + // currently focused DOM node is editable. Use of |focus_on_editable_field_| + // is redundant with CefKeyEvent.focus_on_editable_field in OnPreKeyEvent + // but is useful for demonstration purposes. + focus_on_editable_field_ = message->GetArgumentList()->GetBool(0); + return true; + } + + return false; +} + +void ClientHandler::OnBeforeContextMenu( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + CefRefPtr model) { + CEF_REQUIRE_UI_THREAD(); + + if ((params->GetTypeFlags() & (CM_TYPEFLAG_PAGE | CM_TYPEFLAG_FRAME)) != 0) { + // Add a separator if the menu already has items. + if (model->GetCount() > 0) + model->AddSeparator(); + + // Add DevTools items to all context menus. + model->AddItem(CLIENT_ID_SHOW_DEVTOOLS, "&Show DevTools"); + model->AddItem(CLIENT_ID_CLOSE_DEVTOOLS, "Close DevTools"); + model->AddSeparator(); + model->AddItem(CLIENT_ID_INSPECT_ELEMENT, "Inspect Element"); + + // Test context menu features. + BuildTestMenu(model); + } +} + +bool ClientHandler::OnContextMenuCommand( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + int command_id, + EventFlags event_flags) { + CEF_REQUIRE_UI_THREAD(); + + switch (command_id) { + case CLIENT_ID_SHOW_DEVTOOLS: + ShowDevTools(browser, CefPoint()); + return true; + case CLIENT_ID_CLOSE_DEVTOOLS: + CloseDevTools(browser); + return true; + case CLIENT_ID_INSPECT_ELEMENT: + ShowDevTools(browser, CefPoint(params->GetXCoord(), params->GetYCoord())); + return true; + default: // Allow default handling, if any. + return ExecuteTestMenu(command_id); + } +} + +bool ClientHandler::OnConsoleMessage(CefRefPtr browser, + const CefString& message, + const CefString& source, + int line) { + CEF_REQUIRE_UI_THREAD(); + + FILE* file = fopen(console_log_file_.c_str(), "a"); + if (file) { + std::stringstream ss; + ss << "Message: " << message.ToString() << NEWLINE << + "Source: " << source.ToString() << NEWLINE << + "Line: " << line << NEWLINE << + "-----------------------" << NEWLINE; + fputs(ss.str().c_str(), file); + fclose(file); + + if (first_console_message_) { + test_runner::Alert( + browser, "Console messages written to \"" + console_log_file_ + "\""); + first_console_message_ = false; + } + } + + return false; +} + +void ClientHandler::OnBeforeDownload( + CefRefPtr browser, + CefRefPtr download_item, + const CefString& suggested_name, + CefRefPtr callback) { + CEF_REQUIRE_UI_THREAD(); + + // Continue the download and show the "Save As" dialog. + callback->Continue(MainContext::Get()->GetDownloadPath(suggested_name), true); +} + +void ClientHandler::OnDownloadUpdated( + CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) { + CEF_REQUIRE_UI_THREAD(); + + if (download_item->IsComplete()) { + test_runner::Alert( + browser, + "File \"" + download_item->GetFullPath().ToString() + + "\" downloaded successfully."); + } +} + +bool ClientHandler::OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, + CefDragHandler::DragOperationsMask mask) { + CEF_REQUIRE_UI_THREAD(); + + // Forbid dragging of link URLs. + if (mask & DRAG_OPERATION_LINK) + return true; + + return false; +} + +bool ClientHandler::OnRequestGeolocationPermission( + CefRefPtr browser, + const CefString& requesting_url, + int request_id, + CefRefPtr callback) { + CEF_REQUIRE_UI_THREAD(); + + // Allow geolocation access from all websites. + callback->Continue(true); + return true; +} + +bool ClientHandler::OnPreKeyEvent(CefRefPtr browser, + const CefKeyEvent& event, + CefEventHandle os_event, + bool* is_keyboard_shortcut) { + CEF_REQUIRE_UI_THREAD(); + + if (!event.focus_on_editable_field && event.windows_key_code == 0x20) { + // Special handling for the space character when an input element does not + // have focus. Handling the event in OnPreKeyEvent() keeps the event from + // being processed in the renderer. If we instead handled the event in the + // OnKeyEvent() method the space key would cause the window to scroll in + // addition to showing the alert box. + if (event.type == KEYEVENT_RAWKEYDOWN) { + browser->GetMainFrame()->ExecuteJavaScript( + "alert('You pressed the space bar!');", "", 0); + } + return true; + } + + return false; +} + +bool ClientHandler::OnBeforePopup(CefRefPtr browser, + CefRefPtr frame, + const CefString& target_url, + const CefString& target_frame_name, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + CefRefPtr& client, + CefBrowserSettings& settings, + bool* no_javascript_access) { + CEF_REQUIRE_IO_THREAD(); + + if (browser->GetHost()->IsWindowRenderingDisabled()) { + // Cancel popups in off-screen rendering mode. + return true; + } + return false; +} + +void ClientHandler::OnAfterCreated(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + if (!message_router_) { + // Create the browser-side router for query handling. + CefMessageRouterConfig config; + message_router_ = CefMessageRouterBrowserSide::Create(config); + + // Register handlers with the router. + test_runner::CreateMessageHandlers(message_handler_set_); + MessageHandlerSet::const_iterator it = message_handler_set_.begin(); + for (; it != message_handler_set_.end(); ++it) + message_router_->AddHandler(*(it), false); + } + + // Disable mouse cursor change if requested via the command-line flag. + if (mouse_cursor_change_disabled_) + browser->GetHost()->SetMouseCursorChangeDisabled(true); + + if (!GetBrowser()) { + base::AutoLock lock_scope(lock_); + // We need to keep the main child window, but not popup windows + browser_ = browser; + browser_id_ = browser->GetIdentifier(); + } else if (browser->IsPopup()) { + // Add to the list of popup browsers. + popup_browsers_.push_back(browser); + + // Give focus to the popup browser. Perform asynchronously because the + // parent window may attempt to keep focus after launching the popup. + CefPostTask(TID_UI, + base::Bind(&CefBrowserHost::SetFocus, browser->GetHost().get(), true)); + } + + browser_count_++; +} + +bool ClientHandler::DoClose(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + // Closing the main window requires special handling. See the DoClose() + // documentation in the CEF header for a detailed destription of this + // process. + if (GetBrowserId() == browser->GetIdentifier()) { + base::AutoLock lock_scope(lock_); + // Set a flag to indicate that the window close should be allowed. + is_closing_ = true; + } + + // Allow the close. For windowed browsers this will result in the OS close + // event being sent. + return false; +} + +void ClientHandler::OnBeforeClose(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + message_router_->OnBeforeClose(browser); + + if (GetBrowserId() == browser->GetIdentifier()) { + { + base::AutoLock lock_scope(lock_); + // Free the browser pointer so that the browser can be destroyed + browser_ = NULL; + } + + if (osr_handler_.get()) { + osr_handler_->OnBeforeClose(browser); + osr_handler_ = NULL; + } + } else if (browser->IsPopup()) { + // Remove from the browser popup list. + BrowserList::iterator bit = popup_browsers_.begin(); + for (; bit != popup_browsers_.end(); ++bit) { + if ((*bit)->IsSame(browser)) { + popup_browsers_.erase(bit); + break; + } + } + } + + if (--browser_count_ == 0) { + // All browser windows have closed. + // Remove and delete message router handlers. + MessageHandlerSet::const_iterator it = message_handler_set_.begin(); + for (; it != message_handler_set_.end(); ++it) { + message_router_->RemoveHandler(*(it)); + delete *(it); + } + message_handler_set_.clear(); + message_router_ = NULL; + + // Quit the application message loop. + MainMessageLoop::Get()->Quit(); + } +} + +void ClientHandler::OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) { + CEF_REQUIRE_UI_THREAD(); + + SetLoading(isLoading); + SetNavState(canGoBack, canGoForward); +} + +void ClientHandler::OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) { + CEF_REQUIRE_UI_THREAD(); + + // Don't display an error for downloaded files. + if (errorCode == ERR_ABORTED) + return; + + // Don't display an error for external protocols that we allow the OS to + // handle. See OnProtocolExecution(). + if (errorCode == ERR_UNKNOWN_URL_SCHEME) { + std::string urlStr = frame->GetURL(); + if (urlStr.find("spotify:") == 0) + return; + } + + // Display a load error message. + std::stringstream ss; + ss << "" + "

Failed to load URL " << std::string(failedUrl) << + " with error " << std::string(errorText) << " (" << errorCode << + ").

"; + frame->LoadString(ss.str(), failedUrl); +} + +bool ClientHandler::OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) { + CEF_REQUIRE_UI_THREAD(); + + message_router_->OnBeforeBrowse(browser, frame); + return false; +} + +CefRefPtr ClientHandler::GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) { + CEF_REQUIRE_IO_THREAD(); + return test_runner::GetResourceHandler(browser, frame, request); +} + +bool ClientHandler::OnQuotaRequest(CefRefPtr browser, + const CefString& origin_url, + int64 new_size, + CefRefPtr callback) { + CEF_REQUIRE_IO_THREAD(); + + static const int64 max_size = 1024 * 1024 * 20; // 20mb. + + // Grant the quota request if the size is reasonable. + callback->Continue(new_size <= max_size); + return true; +} + +void ClientHandler::OnProtocolExecution(CefRefPtr browser, + const CefString& url, + bool& allow_os_execution) { + CEF_REQUIRE_UI_THREAD(); + + std::string urlStr = url; + + // Allow OS execution of Spotify URIs. + if (urlStr.find("spotify:") == 0) + allow_os_execution = true; +} + +void ClientHandler::OnRenderProcessTerminated(CefRefPtr browser, + TerminationStatus status) { + CEF_REQUIRE_UI_THREAD(); + + message_router_->OnRenderProcessTerminated(browser); + + // Load the startup URL if that's not the website that we terminated on. + CefRefPtr frame = browser->GetMainFrame(); + std::string url = frame->GetURL(); + std::transform(url.begin(), url.end(), url.begin(), tolower); + + std::string startupURL = GetStartupURL(); + if (startupURL != "chrome://crash" && !url.empty() && + url.find(startupURL) != 0) { + frame->LoadURL(startupURL); + } +} + +bool ClientHandler::GetRootScreenRect(CefRefPtr browser, + CefRect& rect) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return false; + return osr_handler_->GetRootScreenRect(browser, rect); +} + +bool ClientHandler::GetViewRect(CefRefPtr browser, CefRect& rect) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return false; + return osr_handler_->GetViewRect(browser, rect); +} + +bool ClientHandler::GetScreenPoint(CefRefPtr browser, + int viewX, + int viewY, + int& screenX, + int& screenY) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return false; + return osr_handler_->GetScreenPoint(browser, viewX, viewY, screenX, screenY); +} + +bool ClientHandler::GetScreenInfo(CefRefPtr browser, + CefScreenInfo& screen_info) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return false; + return osr_handler_->GetScreenInfo(browser, screen_info); +} + +void ClientHandler::OnPopupShow(CefRefPtr browser, + bool show) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return; + return osr_handler_->OnPopupShow(browser, show); +} + +void ClientHandler::OnPopupSize(CefRefPtr browser, + const CefRect& rect) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return; + return osr_handler_->OnPopupSize(browser, rect); +} + +void ClientHandler::OnPaint(CefRefPtr browser, + PaintElementType type, + const RectList& dirtyRects, + const void* buffer, + int width, + int height) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return; + osr_handler_->OnPaint(browser, type, dirtyRects, buffer, width, height); +} + +void ClientHandler::OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor, + CursorType type, + const CefCursorInfo& custom_cursor_info) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return; + osr_handler_->OnCursorChange(browser, cursor, type, custom_cursor_info); +} + +bool ClientHandler::StartDragging(CefRefPtr browser, + CefRefPtr drag_data, + CefRenderHandler::DragOperationsMask allowed_ops, + int x, int y) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return false; + return osr_handler_->StartDragging(browser, drag_data, allowed_ops, x, y); +} + +void ClientHandler::UpdateDragCursor(CefRefPtr browser, + CefRenderHandler::DragOperation operation) { + CEF_REQUIRE_UI_THREAD(); + if (!osr_handler_.get()) + return; + osr_handler_->UpdateDragCursor(browser, operation); +} + +void ClientHandler::SetMainWindowHandle(ClientWindowHandle handle) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&ClientHandler::SetMainWindowHandle, this, handle)); + return; + } + + main_handle_ = handle; + +#if defined(OS_LINUX) + // Associate |handle| with the GTK dialog handler. + static_cast(dialog_handler_.get())->set_parent( + handle); +#endif +} + +ClientWindowHandle ClientHandler::GetMainWindowHandle() const { + CEF_REQUIRE_UI_THREAD(); + return main_handle_; +} + +void ClientHandler::SetEditWindowHandle(ClientWindowHandle handle) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&ClientHandler::SetEditWindowHandle, this, handle)); + return; + } + + edit_handle_ = handle; +} + +void ClientHandler::SetButtonWindowHandles(ClientWindowHandle backHandle, + ClientWindowHandle forwardHandle, + ClientWindowHandle reloadHandle, + ClientWindowHandle stopHandle) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&ClientHandler::SetButtonWindowHandles, this, + backHandle, forwardHandle, reloadHandle, stopHandle)); + return; + } + + back_handle_ = backHandle; + forward_handle_ = forwardHandle; + reload_handle_ = reloadHandle; + stop_handle_ = stopHandle; +} + +void ClientHandler::SetOSRHandler(CefRefPtr handler) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&ClientHandler::SetOSRHandler, this, handler)); + return; + } + + osr_handler_ = handler; +} + +CefRefPtr ClientHandler::GetOSRHandler() const { + return osr_handler_; +} + +CefRefPtr ClientHandler::GetBrowser() const { + base::AutoLock lock_scope(lock_); + return browser_; +} + +int ClientHandler::GetBrowserId() const { + base::AutoLock lock_scope(lock_); + return browser_id_; +} + +void ClientHandler::CloseAllBrowsers(bool force_close) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&ClientHandler::CloseAllBrowsers, this, force_close)); + return; + } + + if (!popup_browsers_.empty()) { + // Request that any popup browsers close. + BrowserList::const_iterator it = popup_browsers_.begin(); + for (; it != popup_browsers_.end(); ++it) + (*it)->GetHost()->CloseBrowser(force_close); + } + + if (browser_.get()) { + // Request that the main browser close. + browser_->GetHost()->CloseBrowser(force_close); + } +} + +bool ClientHandler::IsClosing() const { + base::AutoLock lock_scope(lock_); + return is_closing_; +} + +void ClientHandler::ShowDevTools(CefRefPtr browser, + const CefPoint& inspect_element_at) { + CefWindowInfo windowInfo; + CefBrowserSettings settings; + +#if defined(OS_WIN) + windowInfo.SetAsPopup(browser->GetHost()->GetWindowHandle(), "DevTools"); +#endif + + browser->GetHost()->ShowDevTools(windowInfo, this, settings, + inspect_element_at); +} + +void ClientHandler::CloseDevTools(CefRefPtr browser) { + browser->GetHost()->CloseDevTools(); +} + +std::string ClientHandler::GetStartupURL() const { + return startup_url_; +} + +bool ClientHandler::Save(const std::string& path, const std::string& data) { + FILE* f = fopen(path.c_str(), "w"); + if (!f) + return false; + size_t total = 0; + do { + size_t write = fwrite(data.c_str() + total, 1, data.size() - total, f); + if (write == 0) + break; + total += write; + } while (total < data.size()); + fclose(f); + return true; +} + +void ClientHandler::BuildTestMenu(CefRefPtr model) { + if (model->GetCount() > 0) + model->AddSeparator(); + + // Build the sub menu. + CefRefPtr submenu = + model->AddSubMenu(CLIENT_ID_TESTMENU_SUBMENU, "Context Menu Test"); + submenu->AddCheckItem(CLIENT_ID_TESTMENU_CHECKITEM, "Check Item"); + submenu->AddRadioItem(CLIENT_ID_TESTMENU_RADIOITEM1, "Radio Item 1", 0); + submenu->AddRadioItem(CLIENT_ID_TESTMENU_RADIOITEM2, "Radio Item 2", 0); + submenu->AddRadioItem(CLIENT_ID_TESTMENU_RADIOITEM3, "Radio Item 3", 0); + + // Check the check item. + if (test_menu_state_.check_item) + submenu->SetChecked(CLIENT_ID_TESTMENU_CHECKITEM, true); + + // Check the selected radio item. + submenu->SetChecked( + CLIENT_ID_TESTMENU_RADIOITEM1 + test_menu_state_.radio_item, true); +} + +bool ClientHandler::ExecuteTestMenu(int command_id) { + if (command_id == CLIENT_ID_TESTMENU_CHECKITEM) { + // Toggle the check item. + test_menu_state_.check_item ^= 1; + return true; + } else if (command_id >= CLIENT_ID_TESTMENU_RADIOITEM1 && + command_id <= CLIENT_ID_TESTMENU_RADIOITEM3) { + // Store the selected radio item. + test_menu_state_.radio_item = (command_id - CLIENT_ID_TESTMENU_RADIOITEM1); + return true; + } + + // Allow default handling to proceed. + return false; +} + +} // namespace client diff --git a/tests/cefclient/client_handler.h b/tests/cefclient/client_handler.h new file mode 100644 index 000000000..901b39a01 --- /dev/null +++ b/tests/cefclient/client_handler.h @@ -0,0 +1,349 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_ +#define CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_ +#pragma once + +#include +#include +#include +#include + +#include "include/base/cef_lock.h" +#include "include/cef_client.h" +#include "include/wrapper/cef_helpers.h" +#include "include/wrapper/cef_message_router.h" + +#if defined(OS_LINUX) +// The Linux client uses GTK instead of the underlying platform type (X11). +#include +#define ClientWindowHandle GtkWidget* +#else +#define ClientWindowHandle CefWindowHandle +#endif + +// Define this value to redirect all popup URLs to the main application browser +// window. +// #define TEST_REDIRECT_POPUP_URLS + +namespace client { + +// ClientHandler implementation. +class ClientHandler : public CefClient, + public CefContextMenuHandler, + public CefDisplayHandler, + public CefDownloadHandler, + public CefDragHandler, + public CefGeolocationHandler, + public CefKeyboardHandler, + public CefLifeSpanHandler, + public CefLoadHandler, + public CefRenderHandler, + public CefRequestHandler { + public: + // Interface implemented to handle off-screen rendering. + class RenderHandler : public CefRenderHandler { + public: + virtual void OnBeforeClose(CefRefPtr browser) =0; + }; + + typedef std::set MessageHandlerSet; + + ClientHandler(); + ~ClientHandler(); + + // CefClient methods + CefRefPtr GetContextMenuHandler() OVERRIDE { + return this; + } + CefRefPtr GetDialogHandler() OVERRIDE { + return dialog_handler_; + } + CefRefPtr GetDisplayHandler() OVERRIDE { + return this; + } + CefRefPtr GetDownloadHandler() OVERRIDE { + return this; + } + CefRefPtr GetDragHandler() OVERRIDE { + return this; + } + CefRefPtr GetGeolocationHandler() OVERRIDE { + return this; + } + CefRefPtr GetJSDialogHandler() OVERRIDE { + return jsdialog_handler_; + } + CefRefPtr GetKeyboardHandler() OVERRIDE { + return this; + } + CefRefPtr GetLifeSpanHandler() OVERRIDE { + return this; + } + CefRefPtr GetLoadHandler() OVERRIDE { + return this; + } + CefRefPtr GetRenderHandler() OVERRIDE { + return this; + } + CefRefPtr GetRequestHandler() OVERRIDE { + return this; + } + bool OnProcessMessageReceived(CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) OVERRIDE; + + // CefContextMenuHandler methods + void OnBeforeContextMenu(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + CefRefPtr model) OVERRIDE; + bool OnContextMenuCommand(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + int command_id, + EventFlags event_flags) OVERRIDE; + + // CefDisplayHandler methods + void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) OVERRIDE; + void OnTitleChange(CefRefPtr browser, + const CefString& title) OVERRIDE; + bool OnConsoleMessage(CefRefPtr browser, + const CefString& message, + const CefString& source, + int line) OVERRIDE; + + // CefDownloadHandler methods + void OnBeforeDownload( + CefRefPtr browser, + CefRefPtr download_item, + const CefString& suggested_name, + CefRefPtr callback) OVERRIDE; + void OnDownloadUpdated( + CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) OVERRIDE; + + // CefDragHandler methods + bool OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, + CefDragHandler::DragOperationsMask mask) OVERRIDE; + + // CefGeolocationHandler methods + bool OnRequestGeolocationPermission( + CefRefPtr browser, + const CefString& requesting_url, + int request_id, + CefRefPtr callback) OVERRIDE; + + // CefKeyboardHandler methods + bool OnPreKeyEvent(CefRefPtr browser, + const CefKeyEvent& event, + CefEventHandle os_event, + bool* is_keyboard_shortcut) OVERRIDE; + + // CefLifeSpanHandler methods + bool OnBeforePopup(CefRefPtr browser, + CefRefPtr frame, + const CefString& target_url, + const CefString& target_frame_name, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + CefRefPtr& client, + CefBrowserSettings& settings, + bool* no_javascript_access) OVERRIDE; + void OnAfterCreated(CefRefPtr browser) OVERRIDE; + bool DoClose(CefRefPtr browser) OVERRIDE; + void OnBeforeClose(CefRefPtr browser) OVERRIDE; + + // CefLoadHandler methods + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) OVERRIDE; + void OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) OVERRIDE; + + // CefRequestHandler methods + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) OVERRIDE; + CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) OVERRIDE; + bool OnQuotaRequest(CefRefPtr browser, + const CefString& origin_url, + int64 new_size, + CefRefPtr callback) OVERRIDE; + void OnProtocolExecution(CefRefPtr browser, + const CefString& url, + bool& allow_os_execution) OVERRIDE; + void OnRenderProcessTerminated(CefRefPtr browser, + TerminationStatus status) OVERRIDE; + + // CefRenderHandler methods + bool GetRootScreenRect(CefRefPtr browser, + CefRect& rect) OVERRIDE; + bool GetViewRect(CefRefPtr browser, + CefRect& rect) OVERRIDE; + bool GetScreenPoint(CefRefPtr browser, + int viewX, + int viewY, + int& screenX, + int& screenY) OVERRIDE; + bool GetScreenInfo(CefRefPtr browser, + CefScreenInfo& screen_info) OVERRIDE; + void OnPopupShow(CefRefPtr browser, bool show) OVERRIDE; + void OnPopupSize(CefRefPtr browser, + const CefRect& rect) OVERRIDE; + void OnPaint(CefRefPtr browser, + PaintElementType type, + const RectList& dirtyRects, + const void* buffer, + int width, + int height) OVERRIDE; + void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor, + CursorType type, + const CefCursorInfo& custom_cursor_info) OVERRIDE; + bool StartDragging(CefRefPtr browser, + CefRefPtr drag_data, + CefRenderHandler::DragOperationsMask allowed_ops, + int x, int y) OVERRIDE; + void UpdateDragCursor(CefRefPtr browser, + CefRenderHandler::DragOperation operation) OVERRIDE; + + void SetMainWindowHandle(ClientWindowHandle handle); + ClientWindowHandle GetMainWindowHandle() const; + void SetEditWindowHandle(ClientWindowHandle handle); + void SetButtonWindowHandles(ClientWindowHandle backHandle, + ClientWindowHandle forwardHandle, + ClientWindowHandle reloadHandle, + ClientWindowHandle stopHandle); + + void SetOSRHandler(CefRefPtr handler); + CefRefPtr GetOSRHandler() const; + + CefRefPtr GetBrowser() const; + int GetBrowserId() const; + + // Request that all existing browser windows close. + void CloseAllBrowsers(bool force_close); + + // Returns true if the main browser window is currently closing. Used in + // combination with DoClose() and the OS close notification to properly handle + // 'onbeforeunload' JavaScript events during window close. + bool IsClosing() const; + + void ShowDevTools(CefRefPtr browser, + const CefPoint& inspect_element_at); + void CloseDevTools(CefRefPtr browser); + + // Returns the startup URL. + std::string GetStartupURL() const; + + bool Save(const std::string& path, const std::string& data); + + private: + void SetLoading(bool isLoading); + void SetNavState(bool canGoBack, bool canGoForward); + + // Test context menu creation. + void BuildTestMenu(CefRefPtr model); + bool ExecuteTestMenu(int command_id); + struct TestMenuState { + TestMenuState() : check_item(true), radio_item(0) {} + bool check_item; + int radio_item; + } test_menu_state_; + + // START THREAD SAFE MEMBERS + // The following members are thread-safe because they're initialized during + // object construction and not changed thereafter. + + // The startup URL. + std::string startup_url_; + + // True if mouse cursor change is disabled. + bool mouse_cursor_change_disabled_; + + CefRefPtr dialog_handler_; + CefRefPtr jsdialog_handler_; + // END THREAD SAFE MEMBERS + + // Lock used to protect members accessed on multiple threads. Make it mutable + // so that it can be used from const methods. + mutable base::Lock lock_; + + // START LOCK PROTECTED MEMBERS + // The following members are accessed on multiple threads and must be + // protected by |lock_|. + + // The child browser window. + CefRefPtr browser_; + + // The child browser id. + int browser_id_; + + // True if the main browser window is currently closing. + bool is_closing_; + // END LOCK PROTECTED MEMBERS + + // START UI THREAD ACCESS ONLY MEMBERS + // The following members will only be accessed on the CEF UI thread. + + // List of any popup browser windows. + typedef std::list > BrowserList; + BrowserList popup_browsers_; + + // The main frame window handle. + ClientWindowHandle main_handle_; + + // The edit window handle. + ClientWindowHandle edit_handle_; + + // The button window handles. + ClientWindowHandle back_handle_; + ClientWindowHandle forward_handle_; + ClientWindowHandle stop_handle_; + ClientWindowHandle reload_handle_; + + // The handler for off-screen rendering, if any. + CefRefPtr osr_handler_; + + // Used for console logging purposes. + const std::string console_log_file_; + bool first_console_message_; + + // True if an editable field currently has focus. + bool focus_on_editable_field_; + + // Handles the browser side of query routing. The renderer side is handled + // in client_renderer.cc. + CefRefPtr message_router_; + + // Set of Handlers registered with the message router. + MessageHandlerSet message_handler_set_; + + // Number of currently existing browser windows. The application will exit + // when the number of windows reaches 0. + static int browser_count_; + + // END UI THREAD ACCESS ONLY MEMBERS + + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(ClientHandler); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_ diff --git a/tests/cefclient/client_handler_gtk.cc b/tests/cefclient/client_handler_gtk.cc new file mode 100644 index 000000000..ec447a1a9 --- /dev/null +++ b/tests/cefclient/client_handler_gtk.cc @@ -0,0 +1,104 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include +#include +#include +#undef Success // Definition conflicts with cef_message_router.h + +#include + +#include "cefclient/client_handler.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" + +namespace client { + +void ClientHandler::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) { + CEF_REQUIRE_UI_THREAD(); + + if (GetBrowserId() == browser->GetIdentifier() && frame->IsMain()) { + // Set the edit window text + std::string urlStr(url); + gtk_entry_set_text(GTK_ENTRY(edit_handle_), urlStr.c_str()); + } +} + +void ClientHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + CEF_REQUIRE_UI_THREAD(); + + std::string titleStr(title); + + if (!browser->IsPopup()) { + // Set the GTK parent window title. + GtkWidget* window = gtk_widget_get_ancestor(main_handle_, + GTK_TYPE_WINDOW); + gtk_window_set_title(GTK_WINDOW(window), titleStr.c_str()); + } else { + // Retrieve the X11 display shared with Chromium. + ::Display* display = cef_get_xdisplay(); + DCHECK(display); + + // Retrieve the X11 window handle for the browser. + ::Window window = browser->GetHost()->GetWindowHandle(); + DCHECK(window != kNullWindowHandle); + + // Retrieve the atoms required by the below XChangeProperty call. + const char* kAtoms[] = { + "_NET_WM_NAME", + "UTF8_STRING" + }; + Atom atoms[2]; + int result = XInternAtoms(display, const_cast(kAtoms), 2, false, + atoms); + if (!result) + NOTREACHED(); + + // Set the window title. + XChangeProperty(display, + window, + atoms[0], + atoms[1], + 8, + PropModeReplace, + reinterpret_cast(titleStr.c_str()), + titleStr.size()); + + // TODO(erg): This is technically wrong. So XStoreName and friends expect + // this in Host Portable Character Encoding instead of UTF-8, which I + // believe is Compound Text. This shouldn't matter 90% of the time since + // this is the fallback to the UTF8 property above. + XStoreName(display, browser->GetHost()->GetWindowHandle(), + titleStr.c_str()); + } +} + +void ClientHandler::SetLoading(bool isLoading) { + CEF_REQUIRE_UI_THREAD(); + + if (isLoading) + gtk_widget_set_sensitive(GTK_WIDGET(stop_handle_), true); + else + gtk_widget_set_sensitive(GTK_WIDGET(stop_handle_), false); +} + +void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { + CEF_REQUIRE_UI_THREAD(); + + if (canGoBack) + gtk_widget_set_sensitive(GTK_WIDGET(back_handle_), true); + else + gtk_widget_set_sensitive(GTK_WIDGET(back_handle_), false); + + if (canGoForward) + gtk_widget_set_sensitive(GTK_WIDGET(forward_handle_), true); + else + gtk_widget_set_sensitive(GTK_WIDGET(forward_handle_), false); +} + +} // namespace client diff --git a/tests/cefclient/client_handler_mac.mm b/tests/cefclient/client_handler_mac.mm new file mode 100644 index 000000000..f80bbe424 --- /dev/null +++ b/tests/cefclient/client_handler_mac.mm @@ -0,0 +1,47 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#import + +#include "cefclient/client_handler.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" + +namespace client { + +void ClientHandler::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) { + CEF_REQUIRE_UI_THREAD(); + + if (GetBrowserId() == browser->GetIdentifier() && frame->IsMain()) { + // Set the edit window text + NSTextField* textField = (NSTextField*)edit_handle_; + std::string urlStr(url); + NSString* str = [NSString stringWithUTF8String:urlStr.c_str()]; + [textField setStringValue:str]; + } +} + +void ClientHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + CEF_REQUIRE_UI_THREAD(); + + // Set the frame window title bar + NSView* view = (NSView*)browser->GetHost()->GetWindowHandle(); + NSWindow* window = [view window]; + std::string titleStr(title); + NSString* str = [NSString stringWithUTF8String:titleStr.c_str()]; + [window setTitle:str]; +} + +void ClientHandler::SetLoading(bool isLoading) { + // TODO(port): Change button status. +} + +void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { + // TODO(port): Change button status. +} + +} // namespace client diff --git a/tests/cefclient/client_handler_win.cc b/tests/cefclient/client_handler_win.cc new file mode 100644 index 000000000..9dbb455eb --- /dev/null +++ b/tests/cefclient/client_handler_win.cc @@ -0,0 +1,54 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/client_handler.h" + +#include +#include + +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/resource.h" + +namespace client { + +void ClientHandler::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) { + CEF_REQUIRE_UI_THREAD(); + + if (GetBrowserId() == browser->GetIdentifier() && frame->IsMain()) { + // Set the edit window text + SetWindowText(edit_handle_, std::wstring(url).c_str()); + } +} + +void ClientHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + CEF_REQUIRE_UI_THREAD(); + + // Set the frame window title bar + CefWindowHandle hwnd = browser->GetHost()->GetWindowHandle(); + if (GetBrowserId() == browser->GetIdentifier()) { + // The frame window will be the parent of the browser window + hwnd = GetParent(hwnd); + } + SetWindowText(hwnd, std::wstring(title).c_str()); +} + +void ClientHandler::SetLoading(bool isLoading) { + DCHECK(edit_handle_ != NULL && reload_handle_ != NULL && + stop_handle_ != NULL); + EnableWindow(edit_handle_, TRUE); + EnableWindow(reload_handle_, !isLoading); + EnableWindow(stop_handle_, isLoading); +} + +void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { + DCHECK(back_handle_ != NULL && forward_handle_ != NULL); + EnableWindow(back_handle_, canGoBack); + EnableWindow(forward_handle_, canGoForward); +} + +} // namespace client diff --git a/tests/cefclient/client_renderer.cc b/tests/cefclient/client_renderer.cc new file mode 100644 index 000000000..1128a99bb --- /dev/null +++ b/tests/cefclient/client_renderer.cc @@ -0,0 +1,87 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/client_renderer.h" + +#include +#include + +#include "include/cef_dom.h" +#include "include/wrapper/cef_helpers.h" +#include "include/wrapper/cef_message_router.h" + +namespace client { +namespace renderer { + +const char kFocusedNodeChangedMessage[] = "ClientRenderer.FocusedNodeChanged"; + +namespace { + +class ClientRenderDelegate : public ClientApp::RenderDelegate { + public: + ClientRenderDelegate() + : last_node_is_editable_(false) { + } + + virtual void OnWebKitInitialized(CefRefPtr app) OVERRIDE { + // Create the renderer-side router for query handling. + CefMessageRouterConfig config; + message_router_ = CefMessageRouterRendererSide::Create(config); + } + + virtual void OnContextCreated(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE { + message_router_->OnContextCreated(browser, frame, context); + } + + virtual void OnContextReleased(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE { + message_router_->OnContextReleased(browser, frame, context); + } + + virtual void OnFocusedNodeChanged(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) OVERRIDE { + bool is_editable = (node.get() && node->IsEditable()); + if (is_editable != last_node_is_editable_) { + // Notify the browser of the change in focused element type. + last_node_is_editable_ = is_editable; + CefRefPtr message = + CefProcessMessage::Create(kFocusedNodeChangedMessage); + message->GetArgumentList()->SetBool(0, is_editable); + browser->SendProcessMessage(PID_BROWSER, message); + } + } + + virtual bool OnProcessMessageReceived( + CefRefPtr app, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) OVERRIDE { + return message_router_->OnProcessMessageReceived( + browser, source_process, message); + } + + private: + bool last_node_is_editable_; + + // Handles the renderer side of query routing. + CefRefPtr message_router_; + + IMPLEMENT_REFCOUNTING(ClientRenderDelegate); +}; + +} // namespace + +void CreateRenderDelegates(ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new ClientRenderDelegate); +} + +} // namespace renderer +} // namespace client diff --git a/tests/cefclient/client_renderer.h b/tests/cefclient/client_renderer.h new file mode 100644 index 000000000..07c4d7cf6 --- /dev/null +++ b/tests/cefclient/client_renderer.h @@ -0,0 +1,24 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_CLIENT_RENDERER_H_ +#define CEF_TESTS_CEFCLIENT_CLIENT_RENDERER_H_ +#pragma once + +#include "include/cef_base.h" +#include "cefclient/client_app.h" + +namespace client { +namespace renderer { + +// Message sent when the focused node changes. +extern const char kFocusedNodeChangedMessage[]; + +// Create the render delegate. +void CreateRenderDelegates(ClientApp::RenderDelegateSet& delegates); + +} // namespace renderer +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_CLIENT_RENDERER_H_ diff --git a/tests/cefclient/client_switches.cc b/tests/cefclient/client_switches.cc new file mode 100644 index 000000000..161959dda --- /dev/null +++ b/tests/cefclient/client_switches.cc @@ -0,0 +1,32 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// This file is shared by cefclient and cef_unittests so don't include using +// a qualified path. +#include "client_switches.h" // NOLINT(build/include) + +namespace client { +namespace switches { + +// CEF and Chromium support a wide range of command-line switches. This file +// only contains command-line switches specific to the cefclient application. +// View CEF/Chromium documentation or search for *_switches.cc files in the +// Chromium source code to identify other existing command-line switches. +// Below is a partial listing of relevant *_switches.cc files: +// base/base_switches.cc +// cef/libcef/common/cef_switches.cc +// chrome/common/chrome_switches.cc (not all apply) +// content/public/common/content_switches.cc + +const char kMultiThreadedMessageLoop[] = "multi-threaded-message-loop"; +const char kCachePath[] = "cache-path"; +const char kUrl[] = "url"; +const char kOffScreenRenderingEnabled[] = "off-screen-rendering-enabled"; +const char kOffScreenFrameRate[] = "off-screen-frame-rate"; +const char kTransparentPaintingEnabled[] = "transparent-painting-enabled"; +const char kShowUpdateRect[] = "show-update-rect"; +const char kMouseCursorChangeDisabled[] = "mouse-cursor-change-disabled"; + +} // namespace switches +} // namespace client diff --git a/tests/cefclient/client_switches.h b/tests/cefclient/client_switches.h new file mode 100644 index 000000000..224b138a0 --- /dev/null +++ b/tests/cefclient/client_switches.h @@ -0,0 +1,26 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Defines all of the command line switches used by cefclient. + +#ifndef CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_ +#define CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_ +#pragma once + +namespace client { +namespace switches { + +extern const char kMultiThreadedMessageLoop[]; +extern const char kCachePath[]; +extern const char kUrl[]; +extern const char kOffScreenRenderingEnabled[]; +extern const char kOffScreenFrameRate[]; +extern const char kTransparentPaintingEnabled[]; +extern const char kShowUpdateRect[]; +extern const char kMouseCursorChangeDisabled[]; + +} // namespace switches +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_ diff --git a/tests/cefclient/dialog_handler_gtk.cc b/tests/cefclient/dialog_handler_gtk.cc new file mode 100644 index 000000000..e99591a85 --- /dev/null +++ b/tests/cefclient/dialog_handler_gtk.cc @@ -0,0 +1,402 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/dialog_handler_gtk.h" +#include "include/cef_browser.h" +#include "include/cef_url.h" +#include "include/wrapper/cef_helpers.h" + +namespace client { + +namespace { + +const char kPromptTextId[] = "cef_prompt_text"; + +// If there's a text entry in the dialog, get the text from the first one and +// return it. +std::string GetPromptText(GtkDialog* dialog) { + GtkWidget* widget = static_cast( + g_object_get_data(G_OBJECT(dialog), kPromptTextId)); + if (widget) + return gtk_entry_get_text(GTK_ENTRY(widget)); + return std::string(); +} + +std::string GetDescriptionFromMimeType(const std::string& mime_type) { + // Check for wild card mime types and return an appropriate description. + static const struct { + const char* mime_type; + const char* label; + } kWildCardMimeTypes[] = { + { "audio", "Audio Files" }, + { "image", "Image Files" }, + { "text", "Text Files" }, + { "video", "Video Files" }, + }; + + for (size_t i = 0; + i < sizeof(kWildCardMimeTypes) / sizeof(kWildCardMimeTypes[0]); ++i) { + if (mime_type == std::string(kWildCardMimeTypes[i].mime_type) + "/*") + return std::string(kWildCardMimeTypes[i].label); + } + + return std::string(); +} + +void AddFilters(GtkFileChooser* chooser, + const std::vector& accept_filters, + bool include_all_files, + std::vector* filters) { + bool has_filter = false; + + for (size_t i = 0; i < accept_filters.size(); ++i) { + const std::string& filter = accept_filters[i]; + if (filter.empty()) + continue; + + std::vector extensions; + std::string description; + + size_t sep_index = filter.find('|'); + if (sep_index != std::string::npos) { + // Treat as a filter of the form "Filter Name|.ext1;.ext2;.ext3". + description = filter.substr(0, sep_index); + + const std::string& exts = filter.substr(sep_index + 1); + size_t last = 0; + size_t size = exts.size(); + for (size_t i = 0; i <= size; ++i) { + if (i == size || exts[i] == ';') { + std::string ext(exts, last, i - last); + if (!ext.empty() && ext[0] == '.') + extensions.push_back(ext); + last = i + 1; + } + } + } else if (filter[0] == '.') { + // Treat as an extension beginning with the '.' character. + extensions.push_back(filter); + } else { + // Otherwise convert mime type to one or more extensions. + description = GetDescriptionFromMimeType(filter); + + std::vector ext; + CefGetExtensionsForMimeType(filter, ext); + for (size_t x = 0; x < ext.size(); ++x) + extensions.push_back("." + ext[x].ToString()); + } + + if (extensions.empty()) + continue; + + GtkFileFilter* gtk_filter = gtk_file_filter_new(); + + std::string ext_str; + for (size_t x = 0; x < extensions.size(); ++x) { + const std::string& pattern = "*" + extensions[x]; + if (x != 0) + ext_str += ";"; + ext_str += pattern; + gtk_file_filter_add_pattern(gtk_filter, pattern.c_str()); + } + + if (description.empty()) + description = ext_str; + else + description += " (" + ext_str + ")"; + + gtk_file_filter_set_name(gtk_filter, description.c_str()); + gtk_file_chooser_add_filter(chooser, gtk_filter); + if (!has_filter) + has_filter = true; + + filters->push_back(gtk_filter); + } + + // Add the *.* filter, but only if we have added other filters (otherwise it + // is implied). + if (include_all_files && has_filter) { + GtkFileFilter* filter = gtk_file_filter_new(); + gtk_file_filter_add_pattern(filter, "*"); + gtk_file_filter_set_name(filter, "All Files (*)"); + gtk_file_chooser_add_filter(chooser, filter); + } +} + +} // namespace + + +ClientDialogHandlerGtk::ClientDialogHandlerGtk() + : gtk_parent_(NULL), + gtk_dialog_(NULL) { +} + +bool ClientDialogHandlerGtk::OnFileDialog( + CefRefPtr browser, + FileDialogMode mode, + const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, + int selected_accept_filter, + CefRefPtr callback) { + std::vector files; + + GtkFileChooserAction action; + const gchar* accept_button; + + // Remove any modifier flags. + FileDialogMode mode_type = + static_cast(mode & FILE_DIALOG_TYPE_MASK); + + if (mode_type == FILE_DIALOG_OPEN || mode_type == FILE_DIALOG_OPEN_MULTIPLE) { + action = GTK_FILE_CHOOSER_ACTION_OPEN; + accept_button = GTK_STOCK_OPEN; + } else if (mode_type == FILE_DIALOG_OPEN_FOLDER) { + action = GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER; + accept_button = GTK_STOCK_OPEN; + } else if (mode_type == FILE_DIALOG_SAVE) { + action = GTK_FILE_CHOOSER_ACTION_SAVE; + accept_button = GTK_STOCK_SAVE; + } else { + NOTREACHED(); + return false; + } + + std::string title_str; + if (!title.empty()) { + title_str = title; + } else { + switch (mode) { + case FILE_DIALOG_OPEN: + title_str = "Open File"; + break; + case FILE_DIALOG_OPEN_MULTIPLE: + title_str = "Open Files"; + break; + case FILE_DIALOG_OPEN_FOLDER: + title_str = "Open Folder"; + break; + case FILE_DIALOG_SAVE: + title_str = "Save File"; + break; + default: + break; + } + } + + DCHECK(gtk_parent_); + GtkWidget* window = gtk_widget_get_ancestor( + GTK_WIDGET(gtk_parent_), GTK_TYPE_WINDOW); + GtkWidget* dialog = gtk_file_chooser_dialog_new( + title_str.c_str(), + GTK_WINDOW(window), + action, + GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, + accept_button, GTK_RESPONSE_ACCEPT, + NULL); + + if (mode_type == FILE_DIALOG_OPEN_MULTIPLE) + gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(dialog), TRUE); + + if (mode_type == FILE_DIALOG_SAVE) { + gtk_file_chooser_set_do_overwrite_confirmation( + GTK_FILE_CHOOSER(dialog), + !!(mode & FILE_DIALOG_OVERWRITEPROMPT_FLAG)); + } + + gtk_file_chooser_set_show_hidden(GTK_FILE_CHOOSER(dialog), + !(mode & FILE_DIALOG_HIDEREADONLY_FLAG)); + + if (!default_file_path.empty()) { + gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(dialog), + default_file_path.ToString().c_str()); + } + + std::vector filters; + AddFilters(GTK_FILE_CHOOSER(dialog), accept_filters, true, &filters); + if (selected_accept_filter < static_cast(filters.size())) { + gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), + filters[selected_accept_filter]); + } + + bool success = false; + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) { + if (mode_type == FILE_DIALOG_OPEN || mode_type == FILE_DIALOG_OPEN_FOLDER || + mode_type == FILE_DIALOG_SAVE) { + char* filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); + files.push_back(std::string(filename)); + success = true; + } else if (mode_type == FILE_DIALOG_OPEN_MULTIPLE) { + GSList* filenames = + gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog)); + if (filenames) { + for (GSList* iter = filenames; iter != NULL; + iter = g_slist_next(iter)) { + std::string path(static_cast(iter->data)); + g_free(iter->data); + files.push_back(path); + } + g_slist_free(filenames); + success = true; + } + } + } + + int filter_index = selected_accept_filter; + if (success) { + GtkFileFilter* selected_filter = + gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog)); + if (selected_filter != NULL) { + for (size_t x = 0; x < filters.size(); ++x) { + if (filters[x] == selected_filter) { + filter_index = x; + break; + } + } + } + } + + gtk_widget_destroy(dialog); + + if (success) + callback->Continue(filter_index, files); + else + callback->Cancel(); + + return true; +} + +bool ClientDialogHandlerGtk::OnJSDialog( + CefRefPtr browser, + const CefString& origin_url, + const CefString& accept_lang, + JSDialogType dialog_type, + const CefString& message_text, + const CefString& default_prompt_text, + CefRefPtr callback, + bool& suppress_message) { + CEF_REQUIRE_UI_THREAD(); + + GtkButtonsType buttons = GTK_BUTTONS_NONE; + GtkMessageType gtk_message_type = GTK_MESSAGE_OTHER; + std::string title; + + switch (dialog_type) { + case JSDIALOGTYPE_ALERT: + buttons = GTK_BUTTONS_NONE; + gtk_message_type = GTK_MESSAGE_WARNING; + title = "JavaScript Alert"; + break; + + case JSDIALOGTYPE_CONFIRM: + buttons = GTK_BUTTONS_CANCEL; + gtk_message_type = GTK_MESSAGE_QUESTION; + title = "JavaScript Confirm"; + break; + + case JSDIALOGTYPE_PROMPT: + buttons = GTK_BUTTONS_CANCEL; + gtk_message_type = GTK_MESSAGE_QUESTION; + title = "JavaScript Prompt"; + break; + } + + js_dialog_callback_ = callback; + + if (!origin_url.empty()) { + title += " - "; + title += origin_url.ToString(); + } + + DCHECK(gtk_parent_); + GtkWidget* window = gtk_widget_get_ancestor( + GTK_WIDGET(gtk_parent_), GTK_TYPE_WINDOW); + gtk_dialog_ = gtk_message_dialog_new(GTK_WINDOW(window), + GTK_DIALOG_MODAL, + gtk_message_type, + buttons, + "%s", + message_text.ToString().c_str()); + g_signal_connect(gtk_dialog_, + "delete-event", + G_CALLBACK(gtk_widget_hide_on_delete), + NULL); + + gtk_window_set_title(GTK_WINDOW(gtk_dialog_), title.c_str()); + + GtkWidget* ok_button = gtk_dialog_add_button(GTK_DIALOG(gtk_dialog_), + GTK_STOCK_OK, + GTK_RESPONSE_OK); + + if (dialog_type != JSDIALOGTYPE_PROMPT) + gtk_widget_grab_focus(ok_button); + + if (dialog_type == JSDIALOGTYPE_PROMPT) { + GtkWidget* content_area = + gtk_dialog_get_content_area(GTK_DIALOG(gtk_dialog_)); + GtkWidget* text_box = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(text_box), + default_prompt_text.ToString().c_str()); + gtk_box_pack_start(GTK_BOX(content_area), text_box, TRUE, TRUE, 0); + g_object_set_data(G_OBJECT(gtk_dialog_), kPromptTextId, text_box); + gtk_entry_set_activates_default(GTK_ENTRY(text_box), TRUE); + } + + gtk_dialog_set_default_response(GTK_DIALOG(gtk_dialog_), GTK_RESPONSE_OK); + g_signal_connect(gtk_dialog_, "response", G_CALLBACK(OnDialogResponse), this); + gtk_widget_show_all(GTK_WIDGET(gtk_dialog_)); + + return true; +} + +bool ClientDialogHandlerGtk::OnBeforeUnloadDialog( + CefRefPtr browser, + const CefString& message_text, + bool is_reload, + CefRefPtr callback) { + CEF_REQUIRE_UI_THREAD(); + + const std::string& new_message_text = + message_text.ToString() + "\n\nIs it OK to leave/reload this page?"; + bool suppress_message = false; + + return OnJSDialog(browser, CefString(), CefString(), JSDIALOGTYPE_CONFIRM, + new_message_text, CefString(), callback, suppress_message); +} + +void ClientDialogHandlerGtk::OnResetDialogState(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + if (!gtk_dialog_) + return; + gtk_widget_destroy(gtk_dialog_); + gtk_dialog_ = NULL; + js_dialog_callback_ = NULL; +} + +// static +void ClientDialogHandlerGtk::OnDialogResponse(GtkDialog* dialog, + gint response_id, + ClientDialogHandlerGtk* handler) { + CEF_REQUIRE_UI_THREAD(); + + DCHECK_EQ(dialog, GTK_DIALOG(handler->gtk_dialog_)); + switch (response_id) { + case GTK_RESPONSE_OK: + handler->js_dialog_callback_->Continue(true, GetPromptText(dialog)); + break; + case GTK_RESPONSE_CANCEL: + case GTK_RESPONSE_DELETE_EVENT: + handler->js_dialog_callback_->Continue(false, CefString()); + break; + default: + NOTREACHED(); + } + + handler->OnResetDialogState(NULL); +} + +} // namespace client + diff --git a/tests/cefclient/dialog_handler_gtk.h b/tests/cefclient/dialog_handler_gtk.h new file mode 100644 index 000000000..fa772c299 --- /dev/null +++ b/tests/cefclient/dialog_handler_gtk.h @@ -0,0 +1,65 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_DIALOG_HANDLER_GTK_H_ +#define CEF_TESTS_CEFCLIENT_DIALOG_HANDLER_GTK_H_ +#pragma once + +#include + +#include "include/cef_dialog_handler.h" +#include "include/cef_jsdialog_handler.h" + +namespace client { + +class ClientDialogHandlerGtk : public CefDialogHandler, + public CefJSDialogHandler { + public: + ClientDialogHandlerGtk(); + + // CefDialogHandler methods. + bool OnFileDialog(CefRefPtr browser, + FileDialogMode mode, + const CefString& title, + const CefString& default_file_path, + const std::vector& accept_filters, + int selected_accept_filter, + CefRefPtr callback) OVERRIDE; + + // CefJSDialogHandler methods. + bool OnJSDialog(CefRefPtr browser, + const CefString& origin_url, + const CefString& accept_lang, + JSDialogType dialog_type, + const CefString& message_text, + const CefString& default_prompt_text, + CefRefPtr callback, + bool& suppress_message) OVERRIDE; + bool OnBeforeUnloadDialog( + CefRefPtr browser, + const CefString& message_text, + bool is_reload, + CefRefPtr callback) OVERRIDE; + void OnResetDialogState(CefRefPtr browser) OVERRIDE; + + void set_parent(GtkWidget* parent) { + gtk_parent_ = parent; + } + + private: + static void OnDialogResponse(GtkDialog *dialog, + gint response_id, + ClientDialogHandlerGtk* handler); + + GtkWidget* gtk_parent_; + GtkWidget* gtk_dialog_; + CefRefPtr js_dialog_callback_; + + IMPLEMENT_REFCOUNTING(ClientDialogHandlerGtk); + DISALLOW_COPY_AND_ASSIGN(ClientDialogHandlerGtk); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_DIALOG_HANDLER_GTK_H_ diff --git a/tests/cefclient/dialog_test.cc b/tests/cefclient/dialog_test.cc new file mode 100644 index 000000000..7c3f6c9ec --- /dev/null +++ b/tests/cefclient/dialog_test.cc @@ -0,0 +1,187 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/dialog_test.h" + +#include + +#include "include/cef_browser.h" +#include "include/wrapper/cef_helpers.h" + +namespace client { +namespace dialog_test { + +namespace { + +const char kTestUrl[] = "http://tests/dialogs"; +const char kFileOpenMessageName[] = "DialogTest.FileOpen"; +const char kFileOpenMultipleMessageName[] = "DialogTest.FileOpenMultiple"; +const char kFileOpenFolderMessageName[] = "DialogTest.FileOpenFolder"; +const char kFileSaveMessageName[] = "DialogTest.FileSave"; + +#if defined(OS_WIN) +#define PATH_SEP '\\' +#else +#define PATH_SEP '/' +#endif + +// Store persistent dialog state information. +class DialogState : public base::RefCountedThreadSafe { + public: + DialogState() + : mode_(FILE_DIALOG_OPEN), + last_selected_filter_(0), + pending_(false) {} + + cef_file_dialog_mode_t mode_; + int last_selected_filter_; + CefString last_file_; + bool pending_; + + DISALLOW_COPY_AND_ASSIGN(DialogState); +}; + +// Callback executed when the file dialog is dismissed. +class DialogCallback : public CefRunFileDialogCallback { + public: + DialogCallback( + CefRefPtr router_callback, + scoped_refptr dialog_state) + : router_callback_(router_callback), + dialog_state_(dialog_state) { + } + + virtual void OnFileDialogDismissed( + int last_selected_filter, + const std::vector& file_paths) OVERRIDE { + CEF_REQUIRE_UI_THREAD(); + DCHECK(dialog_state_->pending_); + + if (!file_paths.empty()) { + if (dialog_state_->mode_ != FILE_DIALOG_OPEN_FOLDER) + dialog_state_->last_selected_filter_ = last_selected_filter; + + dialog_state_->last_file_ = file_paths[0]; + if (dialog_state_->mode_ == FILE_DIALOG_OPEN_FOLDER) { + std::string last_file = dialog_state_->last_file_; + if (last_file[last_file.length() - 1] != PATH_SEP) { + // Add a trailing slash so we know it's a directory. Otherwise, file + // dialogs will think the last path component is a file name. + last_file += PATH_SEP; + dialog_state_->last_file_ = last_file; + } + } + } + + // Send a message back to the render process with the list of file paths. + std::string response; + for (int i = 0; i < static_cast(file_paths.size()); ++i) { + if (!response.empty()) + response += "|"; // Use a delimiter disallowed in file paths. + response += file_paths[i]; + } + + router_callback_->Success(response); + router_callback_ = NULL; + + dialog_state_->pending_ = false; + dialog_state_ = NULL; + } + + private: + CefRefPtr router_callback_; + scoped_refptr dialog_state_; + + IMPLEMENT_REFCOUNTING(DialogCallback); + DISALLOW_COPY_AND_ASSIGN(DialogCallback); +}; + +// Handle messages in the browser process. +class Handler : public CefMessageRouterBrowserSide::Handler { + public: + Handler() {} + + // Called due to cefQuery execution in dialogs.html. + virtual bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) OVERRIDE { + CEF_REQUIRE_UI_THREAD(); + + // Only handle messages from the test URL. + const std::string& url = frame->GetURL(); + if (url.find(kTestUrl) != 0) + return false; + + if (!dialog_state_.get()) + dialog_state_ = new DialogState; + + // Make sure we're only running one dialog at a time. + DCHECK(!dialog_state_->pending_); + + std::vector accept_filters; + std::string title; + + const std::string& message_name = request; + if (message_name == kFileOpenMessageName) { + dialog_state_->mode_ = FILE_DIALOG_OPEN; + title = "My Open Dialog"; + } else if (message_name == kFileOpenMultipleMessageName) { + dialog_state_->mode_ = FILE_DIALOG_OPEN_MULTIPLE; + title = "My Open Multiple Dialog"; + } else if (message_name == kFileOpenFolderMessageName) { + dialog_state_->mode_ = FILE_DIALOG_OPEN_FOLDER; + title = "My Open Folder Dialog"; + } else if (message_name == kFileSaveMessageName) { + dialog_state_->mode_ = static_cast( + FILE_DIALOG_SAVE | FILE_DIALOG_OVERWRITEPROMPT_FLAG); + title = "My Save Dialog"; + } else { + NOTREACHED(); + return true; + } + + if (dialog_state_->mode_ != FILE_DIALOG_OPEN_FOLDER) { + // Build filters based on mime time. + accept_filters.push_back("text/*"); + + // Build filters based on file extension. + accept_filters.push_back(".log"); + accept_filters.push_back(".patch"); + + // Add specific filters as-is. + accept_filters.push_back("Document Files|.doc;.odt"); + accept_filters.push_back("Image Files|.png;.jpg;.gif"); + accept_filters.push_back("PDF Files|.pdf"); + } + + dialog_state_->pending_ = true; + + browser->GetHost()->RunFileDialog( + dialog_state_->mode_, + title, + dialog_state_->last_file_, + accept_filters, + dialog_state_->last_selected_filter_, + new DialogCallback(callback, dialog_state_)); + + return true; + } + + private: + scoped_refptr dialog_state_; + + DISALLOW_COPY_AND_ASSIGN(Handler); +}; + +} // namespace + +void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers) { + handlers.insert(new Handler()); +} + +} // namespace dialog_test +} // namespace client diff --git a/tests/cefclient/dialog_test.h b/tests/cefclient/dialog_test.h new file mode 100644 index 000000000..09d18b3ff --- /dev/null +++ b/tests/cefclient/dialog_test.h @@ -0,0 +1,20 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_DIALOG_TEST_H_ +#define CEF_TESTS_CEFCLIENT_DIALOG_TEST_H_ +#pragma once + +#include "cefclient/test_runner.h" + +namespace client { +namespace dialog_test { + +/// Handler creation. +void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers); + +} // namespace dialog_test +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_DIALOG_TEST_H_ diff --git a/tests/cefclient/mac/English.lproj/InfoPlist.strings b/tests/cefclient/mac/English.lproj/InfoPlist.strings new file mode 100644 index 000000000..fe2abe11b --- /dev/null +++ b/tests/cefclient/mac/English.lproj/InfoPlist.strings @@ -0,0 +1,3 @@ +/* Localized versions of Info.plist keys */ + +NSHumanReadableCopyright = "© Chromium Embedded Framework Authors, 2010"; diff --git a/tests/cefclient/mac/English.lproj/MainMenu.xib b/tests/cefclient/mac/English.lproj/MainMenu.xib new file mode 100644 index 000000000..e4f7c1fc3 --- /dev/null +++ b/tests/cefclient/mac/English.lproj/MainMenu.xib @@ -0,0 +1,2880 @@ + + + + 1050 + 10F569 + 820 + 1038.29 + 461.00 + + com.apple.InterfaceBuilder.CocoaPlugin + 820 + + + YES + + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + + + PluginDependencyRecalculationVersion + + + + YES + + NSApplication + + + FirstResponder + + + NSApplication + + + AMainMenu + + YES + + + cefclient + + 1048576 + 2147483647 + + NSImage + NSMenuCheckmark + + + NSImage + NSMenuMixedState + + submenuAction: + + TestShell + + YES + + + About cefclient + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Preferences… + , + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Services + + 1048576 + 2147483647 + + + submenuAction: + + Services + + YES + + _NSServicesMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Hide cefclient + h + 1048576 + 2147483647 + + + + + + Hide Others + h + 1572864 + 2147483647 + + + + + + Show All + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Quit cefclient + q + 1048576 + 2147483647 + + + + + _NSAppleMenu + + + + + File + + 1048576 + 2147483647 + + + submenuAction: + + File + + YES + + + New + n + 1048576 + 2147483647 + + + + + + Open… + o + 1048576 + 2147483647 + + + + + + Open Recent + + 1048576 + 2147483647 + + + submenuAction: + + Open Recent + + YES + + + Clear Menu + + 1048576 + 2147483647 + + + + + _NSRecentDocumentsMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Close + w + 1048576 + 2147483647 + + + + + + Save + s + 1048576 + 2147483647 + + + + + + Save As… + S + 1179648 + 2147483647 + + + + + + Revert to Saved + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Page Setup... + P + 1179648 + 2147483647 + + + + + + + Print… + p + 1048576 + 2147483647 + + + + + + + + + Edit + + 1048576 + 2147483647 + + + submenuAction: + + Edit + + YES + + + Undo + z + 1048576 + 2147483647 + + + + + + Redo + Z + 1179648 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Cut + x + 1048576 + 2147483647 + + + + + + Copy + c + 1048576 + 2147483647 + + + + + + Paste + v + 1048576 + 2147483647 + + + + + + Delete + + 1048576 + 2147483647 + + + + + + Select All + a + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Find + + 1048576 + 2147483647 + + + submenuAction: + + Find + + YES + + + Find… + f + 1048576 + 2147483647 + + + 1 + + + + Find Next + g + 1048576 + 2147483647 + + + 2 + + + + Find Previous + G + 1179648 + 2147483647 + + + 3 + + + + Use Selection for Find + e + 1048576 + 2147483647 + + + 7 + + + + Jump to Selection + j + 1048576 + 2147483647 + + + + + + + + + Spelling and Grammar + + 1048576 + 2147483647 + + + submenuAction: + + Spelling and Grammar + + YES + + + Show Spelling… + : + 1048576 + 2147483647 + + + + + + Check Spelling + ; + 1048576 + 2147483647 + + + + + + Check Spelling While Typing + + 1048576 + 2147483647 + + + + + + Check Grammar With Spelling + + 1048576 + 2147483647 + + + + + + + + + Substitutions + + 1048576 + 2147483647 + + + submenuAction: + + Substitutions + + YES + + + Smart Copy/Paste + f + 1048576 + 2147483647 + + + 1 + + + + Smart Quotes + g + 1048576 + 2147483647 + + + 2 + + + + Smart Links + G + 1179648 + 2147483647 + + + 3 + + + + + + + Speech + + 1048576 + 2147483647 + + + submenuAction: + + Speech + + YES + + + Start Speaking + + 1048576 + 2147483647 + + + + + + Stop Speaking + + 1048576 + 2147483647 + + + + + + + + + + + + Format + + 1048576 + 2147483647 + + + submenuAction: + + Format + + YES + + + Show Fonts + t + 1048576 + 2147483647 + + + + + + Show Colors + C + 1179648 + 2147483647 + + + + + + + + + View + + 1048576 + 2147483647 + + + submenuAction: + + View + + YES + + + Show Toolbar + t + 1572864 + 2147483647 + + + + + + Customize Toolbar… + + 1048576 + 2147483647 + + + + + + + + + Window + + 1048576 + 2147483647 + + + submenuAction: + + Window + + YES + + + Minimize + m + 1048576 + 2147483647 + + + + + + Zoom + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Bring All to Front + + 1048576 + 2147483647 + + + + + _NSWindowsMenu + + + + + Help + + 1048576 + 2147483647 + + + submenuAction: + + Help + + YES + + + cefclient Help + ? + 1048576 + 2147483647 + + + + + + + + _NSMainMenu + + + YES + + + + + YES + + + performMiniaturize: + + + + 37 + + + + arrangeInFront: + + + + 39 + + + + print: + + + + 86 + + + + runPageLayout: + + + + 87 + + + + clearRecentDocuments: + + + + 127 + + + + orderFrontStandardAboutPanel: + + + + 142 + + + + performClose: + + + + 193 + + + + toggleContinuousSpellChecking: + + + + 222 + + + + undo: + + + + 223 + + + + copy: + + + + 224 + + + + checkSpelling: + + + + 225 + + + + paste: + + + + 226 + + + + stopSpeaking: + + + + 227 + + + + cut: + + + + 228 + + + + showGuessPanel: + + + + 230 + + + + redo: + + + + 231 + + + + selectAll: + + + + 232 + + + + startSpeaking: + + + + 233 + + + + delete: + + + + 235 + + + + performZoom: + + + + 240 + + + + performFindPanelAction: + + + + 241 + + + + centerSelectionInVisibleArea: + + + + 245 + + + + toggleGrammarChecking: + + + + 347 + + + + toggleSmartInsertDelete: + + + + 355 + + + + toggleAutomaticQuoteSubstitution: + + + + 356 + + + + toggleAutomaticLinkDetection: + + + + 357 + + + + showHelp: + + + + 360 + + + + orderFrontColorPanel: + + + + 361 + + + + saveDocument: + + + + 362 + + + + saveDocumentAs: + + + + 363 + + + + revertDocumentToSaved: + + + + 364 + + + + runToolbarCustomizationPalette: + + + + 365 + + + + toggleToolbarShown: + + + + 366 + + + + hide: + + + + 367 + + + + hideOtherApplications: + + + + 368 + + + + terminate: + + + + 369 + + + + unhideAllApplications: + + + + 370 + + + + newDocument: + + + + 373 + + + + openDocument: + + + + 374 + + + + + YES + + 0 + + YES + + + + + + -2 + + + File's Owner + + + -1 + + + First Responder + + + -3 + + + Application + + + 29 + + + YES + + + + + + + + + + MainMenu + + + 19 + + + YES + + + + + + 56 + + + YES + + + + + + 103 + + + YES + + + + 1 + + + 217 + + + YES + + + + + + 83 + + + YES + + + + + + 81 + + + YES + + + + + + + + + + + + + + + + 75 + + + 3 + + + 80 + + + 8 + + + 78 + + + 6 + + + 72 + + + + + 82 + + + 9 + + + 124 + + + YES + + + + + + 77 + + + 5 + + + 73 + + + 1 + + + 79 + + + 7 + + + 112 + + + 10 + + + 74 + + + 2 + + + 125 + + + YES + + + + + + 126 + + + + + 205 + + + YES + + + + + + + + + + + + + + + + + + 202 + + + + + 198 + + + + + 207 + + + + + 214 + + + + + 199 + + + + + 203 + + + + + 197 + + + + + 206 + + + + + 215 + + + + + 218 + + + YES + + + + + + 216 + + + YES + + + + + + 200 + + + YES + + + + + + + + + 219 + + + + + 201 + + + + + 204 + + + + + 220 + + + YES + + + + + + + + + + 213 + + + + + 210 + + + + + 221 + + + + + 208 + + + + + 209 + + + + + 106 + + + YES + + + + 2 + + + 111 + + + + + 57 + + + YES + + + + + + + + + + + + + + + + 58 + + + + + 134 + + + + + 150 + + + + + 136 + + + 1111 + + + 144 + + + + + 129 + + + 121 + + + 143 + + + + + 236 + + + + + 131 + + + YES + + + + + + 149 + + + + + 145 + + + + + 130 + + + + + 24 + + + YES + + + + + + + + + 92 + + + + + 5 + + + + + 239 + + + + + 23 + + + + + 295 + + + YES + + + + + + 296 + + + YES + + + + + + + 297 + + + + + 298 + + + + + 299 + + + YES + + + + + + 300 + + + YES + + + + + + + 344 + + + + + 345 + + + + + 211 + + + YES + + + + + + 212 + + + YES + + + + + + + 195 + + + + + 196 + + + + + 346 + + + + + 348 + + + YES + + + + + + 349 + + + YES + + + + + + + + 350 + + + + + 351 + + + + + 354 + + + + + 389 + + + + + + + YES + + YES + -3.IBPluginDependency + 103.IBPluginDependency + 103.ImportedFromIB2 + 106.IBEditorWindowLastContentRect + 106.IBPluginDependency + 106.ImportedFromIB2 + 106.editorWindowContentRectSynchronizationRect + 111.IBPluginDependency + 111.ImportedFromIB2 + 112.IBPluginDependency + 112.ImportedFromIB2 + 124.IBPluginDependency + 124.ImportedFromIB2 + 125.IBPluginDependency + 125.ImportedFromIB2 + 125.editorWindowContentRectSynchronizationRect + 126.IBPluginDependency + 126.ImportedFromIB2 + 129.IBPluginDependency + 129.ImportedFromIB2 + 130.IBPluginDependency + 130.ImportedFromIB2 + 130.editorWindowContentRectSynchronizationRect + 131.IBPluginDependency + 131.ImportedFromIB2 + 134.IBPluginDependency + 134.ImportedFromIB2 + 136.IBPluginDependency + 136.ImportedFromIB2 + 143.IBPluginDependency + 143.ImportedFromIB2 + 144.IBPluginDependency + 144.ImportedFromIB2 + 145.IBPluginDependency + 145.ImportedFromIB2 + 149.IBPluginDependency + 149.ImportedFromIB2 + 150.IBPluginDependency + 150.ImportedFromIB2 + 19.IBPluginDependency + 19.ImportedFromIB2 + 195.IBPluginDependency + 195.ImportedFromIB2 + 196.IBPluginDependency + 196.ImportedFromIB2 + 197.IBPluginDependency + 197.ImportedFromIB2 + 198.IBPluginDependency + 198.ImportedFromIB2 + 199.IBPluginDependency + 199.ImportedFromIB2 + 200.IBEditorWindowLastContentRect + 200.IBPluginDependency + 200.ImportedFromIB2 + 200.editorWindowContentRectSynchronizationRect + 201.IBPluginDependency + 201.ImportedFromIB2 + 202.IBPluginDependency + 202.ImportedFromIB2 + 203.IBPluginDependency + 203.ImportedFromIB2 + 204.IBPluginDependency + 204.ImportedFromIB2 + 205.IBEditorWindowLastContentRect + 205.IBPluginDependency + 205.ImportedFromIB2 + 205.editorWindowContentRectSynchronizationRect + 206.IBPluginDependency + 206.ImportedFromIB2 + 207.IBPluginDependency + 207.ImportedFromIB2 + 208.IBPluginDependency + 208.ImportedFromIB2 + 209.IBPluginDependency + 209.ImportedFromIB2 + 210.IBPluginDependency + 210.ImportedFromIB2 + 211.IBPluginDependency + 211.ImportedFromIB2 + 212.IBEditorWindowLastContentRect + 212.IBPluginDependency + 212.ImportedFromIB2 + 212.editorWindowContentRectSynchronizationRect + 213.IBPluginDependency + 213.ImportedFromIB2 + 214.IBPluginDependency + 214.ImportedFromIB2 + 215.IBPluginDependency + 215.ImportedFromIB2 + 216.IBPluginDependency + 216.ImportedFromIB2 + 217.IBPluginDependency + 217.ImportedFromIB2 + 218.IBPluginDependency + 218.ImportedFromIB2 + 219.IBPluginDependency + 219.ImportedFromIB2 + 220.IBEditorWindowLastContentRect + 220.IBPluginDependency + 220.ImportedFromIB2 + 220.editorWindowContentRectSynchronizationRect + 221.IBPluginDependency + 221.ImportedFromIB2 + 23.IBPluginDependency + 23.ImportedFromIB2 + 236.IBPluginDependency + 236.ImportedFromIB2 + 239.IBPluginDependency + 239.ImportedFromIB2 + 24.IBEditorWindowLastContentRect + 24.IBPluginDependency + 24.ImportedFromIB2 + 24.editorWindowContentRectSynchronizationRect + 29.IBEditorWindowLastContentRect + 29.IBPluginDependency + 29.ImportedFromIB2 + 29.WindowOrigin + 29.editorWindowContentRectSynchronizationRect + 295.IBPluginDependency + 296.IBEditorWindowLastContentRect + 296.IBPluginDependency + 296.editorWindowContentRectSynchronizationRect + 297.IBPluginDependency + 298.IBPluginDependency + 299.IBPluginDependency + 300.IBEditorWindowLastContentRect + 300.IBPluginDependency + 300.editorWindowContentRectSynchronizationRect + 344.IBPluginDependency + 345.IBPluginDependency + 346.IBPluginDependency + 346.ImportedFromIB2 + 348.IBPluginDependency + 348.ImportedFromIB2 + 349.IBEditorWindowLastContentRect + 349.IBPluginDependency + 349.ImportedFromIB2 + 349.editorWindowContentRectSynchronizationRect + 350.IBPluginDependency + 350.ImportedFromIB2 + 351.IBPluginDependency + 351.ImportedFromIB2 + 354.IBPluginDependency + 354.ImportedFromIB2 + 389.IBPluginDependency + 5.IBPluginDependency + 5.ImportedFromIB2 + 56.IBPluginDependency + 56.ImportedFromIB2 + 57.IBEditorWindowLastContentRect + 57.IBPluginDependency + 57.ImportedFromIB2 + 57.editorWindowContentRectSynchronizationRect + 58.IBPluginDependency + 58.ImportedFromIB2 + 72.IBPluginDependency + 72.ImportedFromIB2 + 73.IBPluginDependency + 73.ImportedFromIB2 + 74.IBPluginDependency + 74.ImportedFromIB2 + 75.IBPluginDependency + 75.ImportedFromIB2 + 77.IBPluginDependency + 77.ImportedFromIB2 + 78.IBPluginDependency + 78.ImportedFromIB2 + 79.IBPluginDependency + 79.ImportedFromIB2 + 80.IBPluginDependency + 80.ImportedFromIB2 + 81.IBEditorWindowLastContentRect + 81.IBPluginDependency + 81.ImportedFromIB2 + 81.editorWindowContentRectSynchronizationRect + 82.IBPluginDependency + 82.ImportedFromIB2 + 83.IBPluginDependency + 83.ImportedFromIB2 + 92.IBPluginDependency + 92.ImportedFromIB2 + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + {{906, 713}, {164, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{375, 955}, {171, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{522, 812}, {146, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{436, 809}, {64, 6}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {272, 83}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {275, 83}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{675, 493}, {240, 243}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{144, 735}, {243, 243}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {164, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {167, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {238, 103}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {241, 103}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{835, 663}, {194, 73}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{304, 905}, {197, 73}} + {{541, 736}, {426, 20}} + com.apple.InterfaceBuilder.CocoaPlugin + + {74, 862} + {{6, 836}, {430, 20}} + com.apple.InterfaceBuilder.CocoaPlugin + {{785, 693}, {231, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + {{254, 935}, {234, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{719, 693}, {173, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + {{188, 935}, {176, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {212, 63}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {215, 63}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{553, 553}, {193, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{18, 653}, {200, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{633, 533}, {196, 203}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{102, 775}, {199, 203}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + + + + YES + + + YES + + + + + YES + + + YES + + + + 439 + + + + YES + + NSApplication + NSResponder + + IBFrameworkSource + AppKit.framework/Headers/NSApplication.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSApplicationScripting.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSColorPanel.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSHelpManager.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSPageLayout.h + + + + NSBrowser + NSControl + + IBFrameworkSource + AppKit.framework/Headers/NSBrowser.h + + + + NSControl + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSControl.h + + + + NSController + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSController.h + + + + NSDocument + NSObject + + YES + + YES + printDocument: + revertDocumentToSaved: + runPageLayout: + saveDocument: + saveDocumentAs: + saveDocumentTo: + + + YES + id + id + id + id + id + id + + + + YES + + YES + printDocument: + revertDocumentToSaved: + runPageLayout: + saveDocument: + saveDocumentAs: + saveDocumentTo: + + + YES + + printDocument: + id + + + revertDocumentToSaved: + id + + + runPageLayout: + id + + + saveDocument: + id + + + saveDocumentAs: + id + + + saveDocumentTo: + id + + + + + IBFrameworkSource + AppKit.framework/Headers/NSDocument.h + + + + NSDocument + + IBFrameworkSource + AppKit.framework/Headers/NSDocumentScripting.h + + + + NSDocumentController + NSObject + + YES + + YES + clearRecentDocuments: + newDocument: + openDocument: + saveAllDocuments: + + + YES + id + id + id + id + + + + YES + + YES + clearRecentDocuments: + newDocument: + openDocument: + saveAllDocuments: + + + YES + + clearRecentDocuments: + id + + + newDocument: + id + + + openDocument: + id + + + saveAllDocuments: + id + + + + + IBFrameworkSource + AppKit.framework/Headers/NSDocumentController.h + + + + NSFormatter + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSFormatter.h + + + + NSMatrix + NSControl + + IBFrameworkSource + AppKit.framework/Headers/NSMatrix.h + + + + NSMenu + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSMenu.h + + + + NSMenuItem + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSMenuItem.h + + + + NSMovieView + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSMovieView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSAccessibility.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSAlert.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSAnimation.h + + + + NSObject + + + + NSObject + + + + NSObject + + + + NSObject + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSComboBox.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSComboBoxCell.h + + + + NSObject + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDatePickerCell.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDictionaryController.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDragging.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDrawer.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSFontManager.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSFontPanel.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSImage.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSKeyValueBinding.h + + + + NSObject + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSNibLoading.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSOutlineView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSPasteboard.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSRuleEditor.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSavePanel.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSound.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSpeechRecognizer.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSpeechSynthesizer.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSplitView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTabView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTableView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSText.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTextStorage.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTextView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTokenField.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTokenFieldCell.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSToolbar.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSToolbarItem.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSWindow.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSArchiver.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSClassDescription.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSConnection.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSError.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSFileManager.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSKeyValueCoding.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSKeyValueObserving.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSKeyedArchiver.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSMetadata.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSNetServices.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSObject.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSObjectScripting.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSPort.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSPortCoder.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSRunLoop.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptClassDescription.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptKeyValueCoding.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptObjectSpecifiers.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptWhoseTests.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSSpellServer.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSStream.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSThread.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSURL.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSURLConnection.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSURLDownload.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSXMLParser.h + + + + NSObject + + IBFrameworkSource + Print.framework/Headers/PDEPluginInterface.h + + + + NSObject + + IBFrameworkSource + QuartzCore.framework/Headers/CAAnimation.h + + + + NSObject + + IBFrameworkSource + QuartzCore.framework/Headers/CALayer.h + + + + NSObject + + IBFrameworkSource + QuartzCore.framework/Headers/CIImageProvider.h + + + + NSResponder + + IBFrameworkSource + AppKit.framework/Headers/NSInterfaceStyle.h + + + + NSResponder + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSResponder.h + + + + NSTableView + NSControl + + + + NSText + NSView + + + + NSUserDefaultsController + NSController + + IBFrameworkSource + AppKit.framework/Headers/NSUserDefaultsController.h + + + + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSClipView.h + + + + NSView + + + + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSRulerView.h + + + + NSView + NSResponder + + + + NSWindow + + + + NSWindow + NSResponder + + + + NSWindow + + IBFrameworkSource + AppKit.framework/Headers/NSWindowScripting.h + + + + + 0 + IBCocoaFramework + + com.apple.InterfaceBuilder.CocoaPlugin.macosx + + + + com.apple.InterfaceBuilder.CocoaPlugin.macosx + + + + com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 + + + YES + ../../../../cef.xcodeproj + 3 + + YES + + YES + NSMenuCheckmark + NSMenuMixedState + + + YES + {9, 8} + {7, 2} + + + + diff --git a/tests/cefclient/mac/Info.plist b/tests/cefclient/mac/Info.plist new file mode 100644 index 000000000..555b68414 --- /dev/null +++ b/tests/cefclient/mac/Info.plist @@ -0,0 +1,30 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFile + cefclient.icns + CFBundleIdentifier + org.cef.cefclient + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + NSSupportsAutomaticGraphicsSwitching + + + diff --git a/tests/cefclient/mac/cefclient.icns b/tests/cefclient/mac/cefclient.icns new file mode 100644 index 000000000..f36742de2 Binary files /dev/null and b/tests/cefclient/mac/cefclient.icns differ diff --git a/tests/cefclient/mac/helper-Info.plist b/tests/cefclient/mac/helper-Info.plist new file mode 100644 index 000000000..ed5abfae9 --- /dev/null +++ b/tests/cefclient/mac/helper-Info.plist @@ -0,0 +1,30 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + ${EXECUTABLE_NAME} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + org.cef.cefclient.helper + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + LSFileQuarantineEnabled + + LSMinimumSystemVersion + 10.5.0 + LSUIElement + 1 + NSSupportsAutomaticGraphicsSwitching + + + diff --git a/tests/cefclient/main_context.cc b/tests/cefclient/main_context.cc new file mode 100644 index 000000000..cd6f2b7e5 --- /dev/null +++ b/tests/cefclient/main_context.cc @@ -0,0 +1,31 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_context.h" + +namespace client { + +namespace { + +MainContext* g_main_context = NULL; + +} // namespace + +// static +MainContext* MainContext::Get() { + DCHECK(g_main_context); + return g_main_context; +} + +MainContext::MainContext() { + DCHECK(!g_main_context); + g_main_context = this; + +} + +MainContext::~MainContext() { + g_main_context = NULL; +} + +} // namespace client diff --git a/tests/cefclient/main_context.h b/tests/cefclient/main_context.h new file mode 100644 index 000000000..c158eebee --- /dev/null +++ b/tests/cefclient/main_context.h @@ -0,0 +1,47 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_MAIN_CONTEXT_H_ +#define CEF_TESTS_CEFCLIENT_MAIN_CONTEXT_H_ + +#include + +#include "include/base/cef_ref_counted.h" +#include "include/internal/cef_types_wrappers.h" + +namespace client { + +// Used to store global context in the browser process. The methods of this +// class are thread-safe unless otherwise indicated. +class MainContext { + public: + // Returns the singleton instance of this object. + static MainContext* Get(); + + // Returns the full path to the console log file. + virtual std::string GetConsoleLogPath() = 0; + + // Returns the full path to |file_name|. + virtual std::string GetDownloadPath(const std::string& file_name) = 0; + + // Returns the app working directory including trailing path separator. + virtual std::string GetAppWorkingDirectory() = 0; + + // Returns the main application URL. + virtual std::string GetMainURL() = 0; + + // Populate |settings| based on command-line arguments. + virtual void PopulateSettings(CefSettings* settings) = 0; + virtual void PopulateBrowserSettings(CefBrowserSettings* settings) = 0; + + protected: + MainContext(); + virtual ~MainContext(); + + DISALLOW_COPY_AND_ASSIGN(MainContext); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_MAIN_CONTEXT_H_ diff --git a/tests/cefclient/main_context_impl.cc b/tests/cefclient/main_context_impl.cc new file mode 100644 index 000000000..783ab2d7b --- /dev/null +++ b/tests/cefclient/main_context_impl.cc @@ -0,0 +1,63 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_context_impl.h" + +#include "cefclient/client_switches.h" + +namespace client { + +namespace { + +// The default URL to load in a browser window. +const char kDefaultUrl[] = "http://www.google.com"; + +} // namespace + +MainContextImpl::MainContextImpl(int argc, + const char* const* argv) { + // Parse the command line. + command_line_ = CefCommandLine::CreateCommandLine(); +#if defined(OS_WIN) + command_line_->InitFromString(::GetCommandLineW()); +#else + command_line_->InitFromArgv(argc, argv); +#endif + + // Set the main URL. + if (command_line_->HasSwitch(switches::kUrl)) + main_url_ = command_line_->GetSwitchValue(switches::kUrl); + if (main_url_.empty()) + main_url_ = kDefaultUrl; +} + +std::string MainContextImpl::GetConsoleLogPath() { + return GetAppWorkingDirectory() + "console.log"; +} + +std::string MainContextImpl::GetMainURL() { + return main_url_; +} + +void MainContextImpl::PopulateSettings(CefSettings* settings) { +#if defined(OS_WIN) + settings->multi_threaded_message_loop = + command_line_->HasSwitch(switches::kMultiThreadedMessageLoop); +#endif + + CefString(&settings->cache_path) = + command_line_->GetSwitchValue(switches::kCachePath); + + if (command_line_->HasSwitch(switches::kOffScreenRenderingEnabled)) + settings->windowless_rendering_enabled = true; +} + +void MainContextImpl::PopulateBrowserSettings(CefBrowserSettings* settings) { + if (command_line_->HasSwitch(switches::kOffScreenFrameRate)) { + settings->windowless_frame_rate = atoi(command_line_-> + GetSwitchValue(switches::kOffScreenFrameRate).ToString().c_str()); + } +} + +} // namespace client diff --git a/tests/cefclient/main_context_impl.h b/tests/cefclient/main_context_impl.h new file mode 100644 index 000000000..dd2619c04 --- /dev/null +++ b/tests/cefclient/main_context_impl.h @@ -0,0 +1,42 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_MAIN_CONTEXT_IMPL_H_ +#define CEF_TESTS_CEFCLIENT_MAIN_CONTEXT_IMPL_H_ + +#include "include/base/cef_scoped_ptr.h" +#include "include/cef_command_line.h" +#include "cefclient/main_context.h" + +namespace client { + +// Used to store global context in the browser process. +class MainContextImpl : public MainContext { + public: + MainContextImpl(int argc, + const char* const* argv); + + // MainContext members. + std::string GetConsoleLogPath() OVERRIDE; + std::string GetDownloadPath(const std::string& file_name) OVERRIDE; + std::string GetAppWorkingDirectory() OVERRIDE; + std::string GetMainURL() OVERRIDE; + void PopulateSettings(CefSettings* settings) OVERRIDE; + void PopulateBrowserSettings(CefBrowserSettings* settings) OVERRIDE; + + private: + // Allow deletion via scoped_ptr only. + friend struct base::DefaultDeleter; + + ~MainContextImpl() {} + + CefRefPtr command_line_; + std::string main_url_; + + DISALLOW_COPY_AND_ASSIGN(MainContextImpl); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_MAIN_CONTEXT_IMPL_H_ diff --git a/tests/cefclient/main_context_impl_posix.cc b/tests/cefclient/main_context_impl_posix.cc new file mode 100644 index 000000000..c4b75e6dd --- /dev/null +++ b/tests/cefclient/main_context_impl_posix.cc @@ -0,0 +1,28 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_context_impl.h" + +#include + +namespace client { + +std::string MainContextImpl::GetDownloadPath(const std::string& file_name) { + return std::string(); +} + +std::string MainContextImpl::GetAppWorkingDirectory() { + char szWorkingDir[256]; + if (getcwd(szWorkingDir, sizeof(szWorkingDir) - 1) == NULL) { + szWorkingDir[0] = 0; + } else { + // Add trailing path separator. + size_t len = strlen(szWorkingDir); + szWorkingDir[len] = '/'; + szWorkingDir[len + 1] = 0; + } + return szWorkingDir; +} + +} // namespace client diff --git a/tests/cefclient/main_context_impl_win.cc b/tests/cefclient/main_context_impl_win.cc new file mode 100644 index 000000000..b4501c6bb --- /dev/null +++ b/tests/cefclient/main_context_impl_win.cc @@ -0,0 +1,39 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_context_impl.h" + +#include +#include + +namespace client { + +std::string MainContextImpl::GetDownloadPath(const std::string& file_name) { + TCHAR szFolderPath[MAX_PATH]; + std::string path; + + // Save the file in the user's "My Documents" folder. + if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, + NULL, 0, szFolderPath))) { + path = CefString(szFolderPath); + path += "\\" + file_name; + } + + return path; +} + +std::string MainContextImpl::GetAppWorkingDirectory() { + char szWorkingDir[MAX_PATH + 1]; + if (_getcwd(szWorkingDir, MAX_PATH) == NULL) { + szWorkingDir[0] = 0; + } else { + // Add trailing path separator. + size_t len = strlen(szWorkingDir); + szWorkingDir[len] = '\\'; + szWorkingDir[len + 1] = 0; + } + return szWorkingDir; +} + +} // namespace client diff --git a/tests/cefclient/main_message_loop.cc b/tests/cefclient/main_message_loop.cc new file mode 100644 index 000000000..286e16b2c --- /dev/null +++ b/tests/cefclient/main_message_loop.cc @@ -0,0 +1,37 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_message_loop.h" + +#include "include/cef_task.h" +#include "include/wrapper/cef_closure_task.h" + +namespace client { + +namespace { + +MainMessageLoop* g_main_message_loop = NULL; + +} // namespace + +MainMessageLoop::MainMessageLoop() { + DCHECK(!g_main_message_loop); + g_main_message_loop = this; +} + +MainMessageLoop::~MainMessageLoop() { + g_main_message_loop = NULL; +} + +// static +MainMessageLoop* MainMessageLoop::Get() { + DCHECK(g_main_message_loop); + return g_main_message_loop; +} + +void MainMessageLoop::PostClosure(const base::Closure& closure) { + PostTask(CefCreateClosureTask(closure)); +} + +} // namespace client diff --git a/tests/cefclient/main_message_loop.h b/tests/cefclient/main_message_loop.h new file mode 100644 index 000000000..803a3c524 --- /dev/null +++ b/tests/cefclient/main_message_loop.h @@ -0,0 +1,120 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_H_ +#define CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_H_ + +#include "include/base/cef_bind.h" +#include "include/base/cef_scoped_ptr.h" +#include "include/cef_task.h" + +#if defined(OS_WIN) +#include +#endif + +namespace client { + +// Represents the message loop running on the main application thread in the +// browser process. This will be the same as the CEF UI thread on Linux, OS X +// and Windows when not using multi-threaded message loop mode. The methods of +// this class are thread-safe unless otherwise indicated. +class MainMessageLoop { + public: + // Returns the singleton instance of this object. + static MainMessageLoop* Get(); + + // Run the message loop. The thread that this method is called on will be + // considered the main thread. This blocks until Quit() is called. + virtual int Run() = 0; + + // Quit the message loop. + virtual void Quit() = 0; + + // Post a task for execution on the main message loop. + virtual void PostTask(CefRefPtr task) = 0; + + // Returns true if this message loop runs tasks on the current thread. + virtual bool RunsTasksOnCurrentThread() const = 0; + +#if defined(OS_WIN) + // Set the current modeless dialog on Windows for proper delivery of dialog + // messages when using multi-threaded message loop mode. This method must be + // called from the main thread. See http://support.microsoft.com/kb/71450 for + // background. + virtual void SetCurrentModelessDialog(HWND hWndDialog) = 0; +#endif + + // Post a closure for execution on the main message loop. + void PostClosure(const base::Closure& closure); + + // Used in combination with DeleteOnMainThread to delete |object| on the + // correct thread. + template + void DeleteSoon(const T* object) { + // Execute DeleteHelper on the main thread. + PostClosure(base::Bind(&MainMessageLoop::DeleteHelper, object)); + } + + protected: + // Only allow deletion via scoped_ptr. + friend struct base::DefaultDeleter; + + MainMessageLoop(); + virtual ~MainMessageLoop(); + + private: + // Helper for deleting |object|. + template + static void DeleteHelper(const T* object) { + delete object; + } + + DISALLOW_COPY_AND_ASSIGN(MainMessageLoop); +}; + +#define CURRENTLY_ON_MAIN_THREAD() \ + client::MainMessageLoop::Get()->RunsTasksOnCurrentThread() + +#define REQUIRE_MAIN_THREAD() DCHECK(CURRENTLY_ON_MAIN_THREAD()) + +#define MAIN_POST_TASK(task) \ + client::MainMessageLoop::Get()->PostTask(task) + +#define MAIN_POST_CLOSURE(closure) \ + client::MainMessageLoop::Get()->PostClosure(closure) + +// Use this struct in conjuction with RefCountedThreadSafe to ensure that an +// object is deleted on the main thread. For example: +// +// class Foo : public base::RefCountedThreadSafe { +// public: +// Foo(); +// void DoSomething(); +// +// private: +// // Allow deletion via scoped_refptr only. +// friend struct DeleteOnMainThread; +// friend class base::RefCountedThreadSafe; +// +// virtual ~Foo() {} +// }; +// +// base::scoped_refptr foo = new Foo(); +// foo->DoSomething(); +// foo = NULL; // Deletion of |foo| will occur on the main thread. +// +struct DeleteOnMainThread { + template + static void Destruct(const T* x) { + if (CURRENTLY_ON_MAIN_THREAD()) { + delete x; + } else { + client::MainMessageLoop::Get()->DeleteSoon(x); + } + } +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_H_ diff --git a/tests/cefclient/main_message_loop_multithreaded_win.cc b/tests/cefclient/main_message_loop_multithreaded_win.cc new file mode 100644 index 000000000..eec47db5a --- /dev/null +++ b/tests/cefclient/main_message_loop_multithreaded_win.cc @@ -0,0 +1,166 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_message_loop_multithreaded_win.h" + +#include "include/base/cef_bind.h" +#include "include/cef_app.h" +#include "cefclient/resource.h" +#include "cefclient/util_win.h" + +namespace client { + +namespace { + +const wchar_t kWndClass[] = L"Client_MessageWindow"; +const wchar_t kTaskMessageName[] = L"Client_CustomTask"; + +} // namespace + +MainMessageLoopMultithreadedWin::MainMessageLoopMultithreadedWin() + : thread_id_(base::PlatformThread::CurrentId()), + task_message_id_(RegisterWindowMessage(kTaskMessageName)), + dialog_hwnd_(NULL), + message_hwnd_(NULL) { +} + +MainMessageLoopMultithreadedWin::~MainMessageLoopMultithreadedWin() { + DCHECK(RunsTasksOnCurrentThread()); + DCHECK(!message_hwnd_); + DCHECK(queued_tasks_.empty()); +} + +int MainMessageLoopMultithreadedWin::Run() { + DCHECK(RunsTasksOnCurrentThread()); + + HINSTANCE hInstance = ::GetModuleHandle(NULL); + + { + base::AutoLock lock_scope(lock_); + + // Create the hidden window for message processing. + message_hwnd_ = CreateMessageWindow(hInstance); + CHECK(message_hwnd_); + + // Store a pointer to |this| in the window's user data. + SetUserDataPtr(message_hwnd_, this); + + // Execute any tasks that are currently queued. + while (!queued_tasks_.empty()) { + PostTaskInternal(queued_tasks_.front()); + queued_tasks_.pop(); + } + } + + HACCEL hAccelTable = + LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CEFCLIENT)); + + MSG msg; + + // Run the application message loop. + while (GetMessage(&msg, NULL, 0, 0)) { + // Allow processing of dialog messages. + if (dialog_hwnd_ && IsDialogMessage(dialog_hwnd_, &msg)) + continue; + + if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + + { + base::AutoLock lock_scope(lock_); + + // Destroy the message window. + DestroyWindow(message_hwnd_); + message_hwnd_ = NULL; + } + + return static_cast(msg.wParam); +} + +void MainMessageLoopMultithreadedWin::Quit() { + // Execute PostQuitMessage(0) on the main thread. + PostClosure(base::Bind(::PostQuitMessage, 0)); +} + +void MainMessageLoopMultithreadedWin::PostTask(CefRefPtr task) { + base::AutoLock lock_scope(lock_); + PostTaskInternal(task); +} + +bool MainMessageLoopMultithreadedWin::RunsTasksOnCurrentThread() const { + return (thread_id_ == base::PlatformThread::CurrentId()); +} + +void MainMessageLoopMultithreadedWin::SetCurrentModelessDialog( + HWND hWndDialog) { + DCHECK(RunsTasksOnCurrentThread()); + +#ifndef NDEBUG + if (hWndDialog) { + // A new dialog reference should not be set while one is currently set. + DCHECK(!dialog_hwnd_); + } +#endif + dialog_hwnd_ = hWndDialog; +} + +// static +HWND MainMessageLoopMultithreadedWin::CreateMessageWindow(HINSTANCE hInstance) { + WNDCLASSEX wc = {0}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = MessageWndProc; + wc.hInstance = hInstance; + wc.lpszClassName = kWndClass; + RegisterClassEx(&wc); + + return CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hInstance, + 0); +} + +// static +LRESULT CALLBACK MainMessageLoopMultithreadedWin::MessageWndProc( + HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { + MainMessageLoopMultithreadedWin* self = + GetUserDataPtr(hWnd); + + if (self && message == self->task_message_id_) { + // Execute the task. + CefTask* task = reinterpret_cast(wParam); + task->Execute(); + + // Release the reference added in PostTaskInternal. This will likely result + // in |task| being deleted. + task->Release(); + } else switch (message) { + case WM_DESTROY: + // Clear the reference to |self|. + SetUserDataPtr(hWnd, NULL); + break; + } + + return DefWindowProc(hWnd, message, wParam, lParam); +} + +void MainMessageLoopMultithreadedWin::PostTaskInternal( + CefRefPtr task) { + lock_.AssertAcquired(); + + if (!message_hwnd_) { + // Queue the task until the message loop starts running. + queued_tasks_.push(task); + return; + } + + // Add a reference that will be released in MessageWndProc. + task->AddRef(); + + // Post the task for execution by the message window. + PostMessage(message_hwnd_, task_message_id_, + reinterpret_cast(task.get()), 0); +} + +} // namespace client diff --git a/tests/cefclient/main_message_loop_multithreaded_win.h b/tests/cefclient/main_message_loop_multithreaded_win.h new file mode 100644 index 000000000..ffa7e1f99 --- /dev/null +++ b/tests/cefclient/main_message_loop_multithreaded_win.h @@ -0,0 +1,60 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_MULTITHREADED_WIN_H_ +#define CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_MULTITHREADED_WIN_H_ + +#include +#include + +#include "include/base/cef_lock.h" +#include "include/base/cef_platform_thread.h" +#include "cefclient/main_message_loop.h" + +namespace client { + +// Represents the main message loop in the browser process when using multi- +// threaded message loop mode on Windows. In this mode there is no Chromium +// message loop running on the main application thread. Instead, this +// implementation utilizes a hidden message window for running tasks. +class MainMessageLoopMultithreadedWin : public MainMessageLoop { + public: + MainMessageLoopMultithreadedWin(); + ~MainMessageLoopMultithreadedWin(); + + // MainMessageLoop methods. + int Run() OVERRIDE; + void Quit() OVERRIDE; + void PostTask(CefRefPtr task) OVERRIDE; + bool RunsTasksOnCurrentThread() const OVERRIDE; + void SetCurrentModelessDialog(HWND hWndDialog) OVERRIDE; + + private: + // Create the message window. + static HWND CreateMessageWindow(HINSTANCE hInstance); + + // Window procedure for the message window. + static LRESULT CALLBACK MessageWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam); + + void PostTaskInternal(CefRefPtr task); + + base::PlatformThreadId thread_id_; + UINT task_message_id_; + + // Only accessed on the main thread. + HWND dialog_hwnd_; + + base::Lock lock_; + + // Must be protected by |lock_|. + HWND message_hwnd_; + std::queue > queued_tasks_; + + DISALLOW_COPY_AND_ASSIGN(MainMessageLoopMultithreadedWin); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_MULTITHREADED_WIN_H_ diff --git a/tests/cefclient/main_message_loop_std.cc b/tests/cefclient/main_message_loop_std.cc new file mode 100644 index 000000000..e64de99dd --- /dev/null +++ b/tests/cefclient/main_message_loop_std.cc @@ -0,0 +1,38 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/main_message_loop_std.h" + +#include "include/cef_app.h" + +namespace client { + +MainMessageLoopStd::MainMessageLoopStd() { +} + +int MainMessageLoopStd::Run() { + CefRunMessageLoop(); + return 0; +} + +void MainMessageLoopStd::Quit() { + CefQuitMessageLoop(); +} + +void MainMessageLoopStd::PostTask(CefRefPtr task) { + CefPostTask(TID_UI, task); +} + +bool MainMessageLoopStd::RunsTasksOnCurrentThread() const { + return CefCurrentlyOn(TID_UI); +} + +#if defined(OS_WIN) +void MainMessageLoopStd::SetCurrentModelessDialog(HWND hWndDialog) { + // Nothing to do here. The Chromium message loop implementation will + // internally route dialog messages. +} +#endif + +} // namespace client diff --git a/tests/cefclient/main_message_loop_std.h b/tests/cefclient/main_message_loop_std.h new file mode 100644 index 000000000..5fa092ddc --- /dev/null +++ b/tests/cefclient/main_message_loop_std.h @@ -0,0 +1,34 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_STD_H_ +#define CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_STD_H_ + +#include "cefclient/main_message_loop.h" + +namespace client { + +// Represents the main message loop in the browser process. This implementation +// is a light-weight wrapper around the Chromium UI thread. +class MainMessageLoopStd : public MainMessageLoop { + public: + MainMessageLoopStd(); + + // MainMessageLoop methods. + int Run() OVERRIDE; + void Quit() OVERRIDE; + void PostTask(CefRefPtr task) OVERRIDE; + bool RunsTasksOnCurrentThread() const OVERRIDE; + +#if defined(OS_WIN) + void SetCurrentModelessDialog(HWND hWndDialog) OVERRIDE; +#endif + + private: + DISALLOW_COPY_AND_ASSIGN(MainMessageLoopStd); +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_MAIN_MESSAGE_LOOP_STD_H_ diff --git a/tests/cefclient/osr_dragdrop_events.h b/tests/cefclient/osr_dragdrop_events.h new file mode 100644 index 000000000..3063405e4 --- /dev/null +++ b/tests/cefclient/osr_dragdrop_events.h @@ -0,0 +1,36 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_OSR_DRAGDROP_EVENTS_H_ +#define CEF_TESTS_CEFCLIENT_OSR_DRAGDROP_EVENTS_H_ + +#include "include/cef_render_handler.h" +#include "cefclient/client_handler.h" + +namespace client { + +class OsrDragEvents { + public: + virtual CefBrowserHost::DragOperationsMask OnDragEnter( + CefRefPtr drag_data, + CefMouseEvent ev, + CefBrowserHost::DragOperationsMask effect) = 0; + + virtual CefBrowserHost::DragOperationsMask OnDragOver( + CefMouseEvent ev, + CefBrowserHost::DragOperationsMask effect) = 0; + + virtual void OnDragLeave() = 0; + + virtual CefBrowserHost::DragOperationsMask OnDrop( + CefMouseEvent ev, + CefBrowserHost::DragOperationsMask effect) = 0; + + protected: + virtual ~OsrDragEvents() {} +}; + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_OSR_DRAGDROP_EVENTS_H_ diff --git a/tests/cefclient/osr_dragdrop_win.cc b/tests/cefclient/osr_dragdrop_win.cc new file mode 100644 index 000000000..690d932b6 --- /dev/null +++ b/tests/cefclient/osr_dragdrop_win.cc @@ -0,0 +1,657 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/osr_dragdrop_win.h" + +#if defined(CEF_USE_ATL) + +#include +#include +#include + +#include +#include + +#include "include/wrapper/cef_helpers.h" +#include "cefclient/bytes_write_handler.h" +#include "cefclient/resource.h" +#include "cefclient/util_win.h" + +namespace client { + +namespace { + +DWORD DragOperationToDropEffect(CefRenderHandler::DragOperation allowed_ops) { + DWORD effect = DROPEFFECT_NONE; + if (allowed_ops & DRAG_OPERATION_COPY) + effect |= DROPEFFECT_COPY; + if (allowed_ops & DRAG_OPERATION_LINK) + effect |= DROPEFFECT_LINK; + if (allowed_ops & DRAG_OPERATION_MOVE) + effect |= DROPEFFECT_MOVE; + return effect; +} + +CefRenderHandler::DragOperationsMask DropEffectToDragOperation(DWORD effect) { + DWORD operation = DRAG_OPERATION_NONE; + if (effect & DROPEFFECT_COPY) + operation |= DRAG_OPERATION_COPY; + if (effect & DROPEFFECT_LINK) + operation |= DRAG_OPERATION_LINK; + if (effect & DROPEFFECT_MOVE) + operation |= DRAG_OPERATION_MOVE; + return static_cast(operation); +} + +CefMouseEvent ToMouseEvent(POINTL p, DWORD key_state, HWND hWnd) { + CefMouseEvent ev; + POINT screen_point = { p.x, p.y }; + ScreenToClient(hWnd, &screen_point); + ev.x = screen_point.x; + ev.y = screen_point.y; + ev.modifiers = GetCefMouseModifiers(key_state); + return ev; +} + + +void GetStorageForBytes(STGMEDIUM* storage, const void* data, size_t bytes) { + HANDLE handle = GlobalAlloc(GPTR, static_cast(bytes)); + if (handle) { + memcpy(handle, data, bytes); + } + + storage->hGlobal = handle; + storage->tymed = TYMED_HGLOBAL; + storage->pUnkForRelease = NULL; +} + +template +void GetStorageForString(STGMEDIUM* stgmed, const std::basic_string& data) { + GetStorageForBytes(stgmed, data.c_str(), + (data.size() + 1) * sizeof(std::basic_string::value_type)); +} + +void GetStorageForFileDescriptor(STGMEDIUM* storage, + const std::wstring& file_name) { + DCHECK(!file_name.empty()); + HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR)); + + FILEGROUPDESCRIPTOR* descriptor = + reinterpret_cast(hdata); + descriptor->cItems = 1; + descriptor->fgd[0].dwFlags = FD_LINKUI; + wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(), + std::min(file_name.size(), static_cast(MAX_PATH - 1u))); + + storage->tymed = TYMED_HGLOBAL; + storage->hGlobal = hdata; + storage->pUnkForRelease = NULL; +} + +// Helper method for converting from text/html to MS CF_HTML. +// Documentation for the CF_HTML format is available at +// http://msdn.microsoft.com/en-us/library/aa767917(VS.85).aspx +std::string HtmlToCFHtml(const std::string& html, const std::string& base_url) { + if (html.empty()) + return std::string(); + +#define MAX_DIGITS 10 +#define MAKE_NUMBER_FORMAT_1(digits) MAKE_NUMBER_FORMAT_2(digits) +#define MAKE_NUMBER_FORMAT_2(digits) "%0" #digits "u" +#define NUMBER_FORMAT MAKE_NUMBER_FORMAT_1(MAX_DIGITS) + + static const char* header = "Version:0.9\r\n" + "StartHTML:" NUMBER_FORMAT "\r\n" + "EndHTML:" NUMBER_FORMAT "\r\n" + "StartFragment:" NUMBER_FORMAT "\r\n" + "EndFragment:" NUMBER_FORMAT "\r\n"; + static const char* source_url_prefix = "SourceURL:"; + + static const char* start_markup = "\r\n\r\n"; + static const char* end_markup = "\r\n\r\n"; + + // Calculate offsets + size_t start_html_offset = strlen(header) - strlen(NUMBER_FORMAT) * 4 + + MAX_DIGITS * 4; + if (!base_url.empty()) { + start_html_offset += strlen(source_url_prefix) + base_url.length() + + 2; // Add 2 for \r\n. + } + size_t start_fragment_offset = start_html_offset + strlen(start_markup); + size_t end_fragment_offset = start_fragment_offset + html.length(); + size_t end_html_offset = end_fragment_offset + strlen(end_markup); + char raw_result[1024]; + _snprintf(raw_result, sizeof(1024), + header, + start_html_offset, + end_html_offset, + start_fragment_offset, + end_fragment_offset); + std::string result = raw_result; + if (!base_url.empty()) { + result.append(source_url_prefix); + result.append(base_url); + result.append("\r\n"); + } + result.append(start_markup); + result.append(html); + result.append(end_markup); + +#undef MAX_DIGITS +#undef MAKE_NUMBER_FORMAT_1 +#undef MAKE_NUMBER_FORMAT_2 +#undef NUMBER_FORMAT + + return result; +} + +void CFHtmlExtractMetadata(const std::string& cf_html, + std::string* base_url, + size_t* html_start, + size_t* fragment_start, + size_t* fragment_end) { + // Obtain base_url if present. + if (base_url) { + static std::string src_url_str("SourceURL:"); + size_t line_start = cf_html.find(src_url_str); + if (line_start != std::string::npos) { + size_t src_end = cf_html.find("\n", line_start); + size_t src_start = line_start + src_url_str.length(); + if (src_end != std::string::npos && src_start != std::string::npos) { + *base_url = cf_html.substr(src_start, src_end - src_start); + } + } + } + + // Find the markup between "" and "". + // If the comments cannot be found, like copying from OpenOffice Writer, + // we simply fall back to using StartFragment/EndFragment bytecount values + // to determine the fragment indexes. + std::string cf_html_lower = cf_html; + size_t markup_start = cf_html_lower.find("(atoi(cf_html.c_str() + + start_fragment_start + start_fragment_str.length())); + } + + static std::string end_fragment_str("EndFragment:"); + size_t end_fragment_start = cf_html.find(end_fragment_str); + if (end_fragment_start != std::string::npos) { + *fragment_end = static_cast(atoi(cf_html.c_str() + + end_fragment_start + end_fragment_str.length())); + } + } else { + *fragment_start = cf_html.find('>', tag_start) + 1; + size_t tag_end = cf_html.rfind(" + + + +
+ + Result 1: +
Result 2: +
+ +
+ + + + + + + + + + +
NameResult 1 Avg (ms)Result 2 Avg (ms)% Diff
+
+ + + + + diff --git a/tests/cefclient/res/performance2.html b/tests/cefclient/res/performance2.html new file mode 100644 index 000000000..6664de7b2 --- /dev/null +++ b/tests/cefclient/res/performance2.html @@ -0,0 +1,442 @@ + + + + Performance Tests (2) + + + +

Performance Tests (2)

+ +
+ + + + + + + + + + + + + + + + + + + +
Settings:
Iterations:
Samples:
Mode:Asynchronous + Synchronous +
+
+ + +
+ +
+ + + + + + + + + + + + + + + + + + + +
EnabledNameSamples x IterationsMin, msAvg, msMax, msAverage calls/secMeasuring InacurracyMemory, MBMemory delta, MBDescription
+
+ + + + + diff --git a/tests/cefclient/res/small.ico b/tests/cefclient/res/small.ico new file mode 100644 index 000000000..d551aa3aa Binary files /dev/null and b/tests/cefclient/res/small.ico differ diff --git a/tests/cefclient/res/transparency.html b/tests/cefclient/res/transparency.html new file mode 100644 index 000000000..a8dd3b46e --- /dev/null +++ b/tests/cefclient/res/transparency.html @@ -0,0 +1,63 @@ + + + +Transparency Examples + + + + +

Image Transparency

+Hover over an image to make it fully opaque.
+klematis +klematis + +

Block Transparency

+White 0% White 25% White 50% White 75% White 100% +
+Black 0% Black 25% Black 50% Black 75% Black 100% + + + diff --git a/tests/cefclient/res/window.html b/tests/cefclient/res/window.html new file mode 100644 index 000000000..7d4fe6640 --- /dev/null +++ b/tests/cefclient/res/window.html @@ -0,0 +1,48 @@ + + +Window Test + + + +
+Click a button to perform the associated window action. +
+
+
(minimizes and then restores the window as topmost) +
X: Y: Width: Height: +
+ + diff --git a/tests/cefclient/res/xmlhttprequest.html b/tests/cefclient/res/xmlhttprequest.html new file mode 100644 index 000000000..20dbef919 --- /dev/null +++ b/tests/cefclient/res/xmlhttprequest.html @@ -0,0 +1,26 @@ + + + +
+URL: +
+
+
+ + diff --git a/tests/cefclient/resource.h b/tests/cefclient/resource.h new file mode 100644 index 000000000..a6b4e1150 --- /dev/null +++ b/tests/cefclient/resource.h @@ -0,0 +1,65 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by cefclient.rc +// +#define BINARY 256 +#define IDC_MYICON 2 +#define IDD_CEFCLIENT_DIALOG 102 +#define IDS_APP_TITLE 103 +#define IDD_ABOUTBOX 103 +#define IDM_ABOUT 104 +#define IDM_EXIT 105 +#define IDI_CEFCLIENT 107 +#define IDI_SMALL 108 +#define IDC_CEFCLIENT 109 +#define IDS_OSR_WIDGET_CLASS 110 +#define IDR_MAINFRAME 128 +#define IDC_NAV_BACK 200 +#define IDC_NAV_FORWARD 201 +#define IDC_NAV_RELOAD 202 +#define IDC_NAV_STOP 203 +#define ID_QUIT 32500 +#define ID_FIND 32501 +#define ID_TESTS_FIRST 32700 +#define ID_TESTS_GETSOURCE 32700 +#define ID_TESTS_GETTEXT 32701 +#define ID_TESTS_OTHER_TESTS 32702 +#define ID_TESTS_PLUGIN_INFO 32703 +#define ID_TESTS_POPUP 32704 +#define ID_TESTS_PRINT 32705 +#define ID_TESTS_REQUEST 32706 +#define ID_TESTS_TRACING_BEGIN 32707 +#define ID_TESTS_TRACING_END 32708 +#define ID_TESTS_ZOOM_IN 32709 +#define ID_TESTS_ZOOM_OUT 32710 +#define ID_TESTS_ZOOM_RESET 32711 +#define ID_TESTS_LAST 32711 +#define IDC_STATIC -1 +#define IDS_BINDING 1000 +#define IDS_DIALOGS 1001 +#define IDS_LOCALSTORAGE 1002 +#define IDS_LOGO 1003 +#define IDS_LOGOBALL 1004 +#define IDS_OSRTEST 1005 +#define IDS_OTHER_TESTS 1006 +#define IDS_PERFORMANCE 1007 +#define IDS_TRANSPARENCY 1008 +#define IDS_WINDOW 1009 +#define IDS_XMLHTTPREQUEST 1010 +#define IDS_PERFORMANCE2 1011 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 130 +#define _APS_NEXT_COMMAND_VALUE 32774 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 111 +#endif +#endif diff --git a/tests/cefclient/resource_util.h b/tests/cefclient/resource_util.h new file mode 100644 index 000000000..568feeea3 --- /dev/null +++ b/tests/cefclient/resource_util.h @@ -0,0 +1,27 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_ +#define CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_ +#pragma once + +#include +#include "include/cef_stream.h" + +namespace client { + +#if defined(OS_POSIX) +// Returns the directory containing resource files. +bool GetResourceDir(std::string& dir); +#endif + +// Retrieve a resource as a string. +bool LoadBinaryResource(const char* resource_name, std::string& resource_data); + +// Retrieve a resource as a steam reader. +CefRefPtr GetBinaryResourceReader(const char* resource_name); + +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_ diff --git a/tests/cefclient/resource_util_linux.cc b/tests/cefclient/resource_util_linux.cc new file mode 100644 index 000000000..408bf10c2 --- /dev/null +++ b/tests/cefclient/resource_util_linux.cc @@ -0,0 +1,34 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cefclient/resource_util.h" +#include +#include +#include + +namespace client { + +bool GetResourceDir(std::string& dir) { + char buff[1024]; + + // Retrieve the executable path. + ssize_t len = readlink("/proc/self/exe", buff, sizeof(buff)-1); + if (len == -1) + return false; + + buff[len] = 0; + + // Remove the executable name from the path. + char* pos = strrchr(buff, '/'); + if (!pos) + return false; + + // Add "files" to the path. + strcpy(pos+1, "files"); // NOLINT(runtime/printf) + dir = std::string(buff); + return true; +} + +} // namespace client diff --git a/tests/cefclient/resource_util_mac.mm b/tests/cefclient/resource_util_mac.mm new file mode 100644 index 000000000..3b8ed96f4 --- /dev/null +++ b/tests/cefclient/resource_util_mac.mm @@ -0,0 +1,65 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cefclient/resource_util.h" + +#import +#include +#include + +#include "include/base/cef_logging.h" + +namespace client { + +namespace { + +bool AmIBundled() { + // Implementation adapted from Chromium's base/mac/foundation_util.mm + ProcessSerialNumber psn = {0, kCurrentProcess}; + + FSRef fsref; + OSStatus pbErr; + if ((pbErr = GetProcessBundleLocation(&psn, &fsref)) != noErr) { + NOTREACHED(); + return false; + } + + FSCatalogInfo info; + OSErr fsErr; + if ((fsErr = FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info, + NULL, NULL, NULL)) != noErr) { + NOTREACHED(); + return false; + } + + return (info.nodeFlags & kFSNodeIsDirectoryMask); +} + +} // namespace + +bool GetResourceDir(std::string& dir) { + // Implementation adapted from Chromium's base/base_path_mac.mm + if (AmIBundled()) { + // Retrieve the executable directory. + uint32_t pathSize = 0; + _NSGetExecutablePath(NULL, &pathSize); + if (pathSize > 0) { + dir.resize(pathSize); + _NSGetExecutablePath(const_cast(dir.c_str()), &pathSize); + } + + // Trim executable name up to the last separator + std::string::size_type last_separator = dir.find_last_of("/"); + dir.resize(last_separator); + dir.append("/../Resources"); + return true; + } else { + // TODO: Provide unbundled path + NOTIMPLEMENTED(); + return false; + } +} + +} // namespace client diff --git a/tests/cefclient/resource_util_posix.cc b/tests/cefclient/resource_util_posix.cc new file mode 100644 index 000000000..96dfa5706 --- /dev/null +++ b/tests/cefclient/resource_util_posix.cc @@ -0,0 +1,63 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/resource_util.h" +#include + +namespace client { + +namespace { + +bool FileExists(const char* path) { + FILE* f = fopen(path, "rb"); + if (f) { + fclose(f); + return true; + } + return false; +} + +bool ReadFileToString(const char* path, std::string& data) { + // Implementation adapted from base/file_util.cc + FILE* file = fopen(path, "rb"); + if (!file) + return false; + + char buf[1 << 16]; + size_t len; + while ((len = fread(buf, 1, sizeof(buf), file)) > 0) + data.append(buf, len); + fclose(file); + + return true; +} + +} // namespace + +bool LoadBinaryResource(const char* resource_name, std::string& resource_data) { + std::string path; + if (!GetResourceDir(path)) + return false; + + path.append("/"); + path.append(resource_name); + + return ReadFileToString(path.c_str(), resource_data); +} + +CefRefPtr GetBinaryResourceReader(const char* resource_name) { + std::string path; + if (!GetResourceDir(path)) + return NULL; + + path.append("/"); + path.append(resource_name); + + if (!FileExists(path.c_str())) + return NULL; + + return CefStreamReader::CreateForFile(path); +} + +} // namespace client diff --git a/tests/cefclient/resource_util_win.cc b/tests/cefclient/resource_util_win.cc new file mode 100644 index 000000000..c4314df55 --- /dev/null +++ b/tests/cefclient/resource_util_win.cc @@ -0,0 +1,95 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/resource_util.h" +#include "include/base/cef_logging.h" +#include "include/cef_stream.h" +#include "include/wrapper/cef_byte_read_handler.h" +#include "cefclient/resource.h" + +namespace client { + +namespace { + +bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes) { + HINSTANCE hInst = GetModuleHandle(NULL); + HRSRC hRes = FindResource(hInst, MAKEINTRESOURCE(binaryId), + MAKEINTRESOURCE(256)); + if (hRes) { + HGLOBAL hGlob = LoadResource(hInst, hRes); + if (hGlob) { + dwSize = SizeofResource(hInst, hRes); + pBytes = (LPBYTE)LockResource(hGlob); + if (dwSize > 0 && pBytes) + return true; + } + } + + return false; +} + +int GetResourceId(const char* resource_name) { + // Map of resource labels to BINARY id values. + static struct _resource_map { + char* name; + int id; + } resource_map[] = { + {"binding.html", IDS_BINDING}, + {"dialogs.html", IDS_DIALOGS}, + {"localstorage.html", IDS_LOCALSTORAGE}, + {"logo.png", IDS_LOGO}, + {"osr_test.html", IDS_OSRTEST}, + {"other_tests.html", IDS_OTHER_TESTS}, + {"performance.html", IDS_PERFORMANCE}, + {"performance2.html", IDS_PERFORMANCE2}, + {"transparency.html", IDS_TRANSPARENCY}, + {"window.html", IDS_WINDOW}, + {"xmlhttprequest.html", IDS_XMLHTTPREQUEST}, + }; + + for (int i = 0; i < sizeof(resource_map)/sizeof(_resource_map); ++i) { + if (!strcmp(resource_map[i].name, resource_name)) + return resource_map[i].id; + } + + return 0; +} + +} // namespace + +bool LoadBinaryResource(const char* resource_name, std::string& resource_data) { + int resource_id = GetResourceId(resource_name); + if (resource_id == 0) + return false; + + DWORD dwSize; + LPBYTE pBytes; + + if (LoadBinaryResource(resource_id, dwSize, pBytes)) { + resource_data = std::string(reinterpret_cast(pBytes), dwSize); + return true; + } + + NOTREACHED(); // The resource should be found. + return false; +} + +CefRefPtr GetBinaryResourceReader(const char* resource_name) { + int resource_id = GetResourceId(resource_name); + if (resource_id == 0) + return NULL; + + DWORD dwSize; + LPBYTE pBytes; + + if (LoadBinaryResource(resource_id, dwSize, pBytes)) { + return CefStreamReader::CreateForHandler( + new CefByteReadHandler(pBytes, dwSize, NULL)); + } + + NOTREACHED(); // The resource should be found. + return NULL; +} + +} // namespace client diff --git a/tests/cefclient/scheme_test.cc b/tests/cefclient/scheme_test.cc new file mode 100644 index 000000000..3460c4b5b --- /dev/null +++ b/tests/cefclient/scheme_test.cc @@ -0,0 +1,161 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/scheme_test.h" + +#include +#include + +#include "include/cef_browser.h" +#include "include/cef_callback.h" +#include "include/cef_frame.h" +#include "include/cef_resource_handler.h" +#include "include/cef_response.h" +#include "include/cef_request.h" +#include "include/cef_scheme.h" +#include "include/wrapper/cef_helpers.h" +#include "cefclient/resource_util.h" +#include "cefclient/test_runner.h" + +namespace client { +namespace scheme_test { + +namespace { + +// Implementation of the schema handler for client:// requests. +class ClientSchemeHandler : public CefResourceHandler { + public: + ClientSchemeHandler() : offset_(0) {} + + virtual bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) + OVERRIDE { + CEF_REQUIRE_IO_THREAD(); + + bool handled = false; + + std::string url = request->GetURL(); + if (strstr(url.c_str(), "handler.html") != NULL) { + // Build the response html + data_ = "Client Scheme Handler" + "" + "This contents of this page page are served by the " + "ClientSchemeHandler class handling the client:// protocol." + "
You should see an image:" + "
";
+
+      // Output a string representation of the request
+      std::string dump;
+      test_runner::DumpRequestContents(request, dump);
+      data_.append(dump);
+
+      data_.append("

Try the test form:" + "
" + "" + "" + "" + "
"); + + handled = true; + + // Set the resulting mime type + mime_type_ = "text/html"; + } else if (strstr(url.c_str(), "logo.png") != NULL) { + // Load the response image + if (LoadBinaryResource("logo.png", data_)) { + handled = true; + // Set the resulting mime type + mime_type_ = "image/png"; + } + } + + if (handled) { + // Indicate the headers are available. + callback->Continue(); + return true; + } + + return false; + } + + virtual void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) OVERRIDE { + CEF_REQUIRE_IO_THREAD(); + + DCHECK(!data_.empty()); + + response->SetMimeType(mime_type_); + response->SetStatus(200); + + // Set the resulting response length + response_length = data_.length(); + } + + virtual void Cancel() OVERRIDE { + CEF_REQUIRE_IO_THREAD(); + } + + virtual bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) + OVERRIDE { + CEF_REQUIRE_IO_THREAD(); + + bool has_data = false; + bytes_read = 0; + + if (offset_ < data_.length()) { + // Copy the next block of data into the buffer. + int transfer_size = + std::min(bytes_to_read, static_cast(data_.length() - offset_)); + memcpy(data_out, data_.c_str() + offset_, transfer_size); + offset_ += transfer_size; + + bytes_read = transfer_size; + has_data = true; + } + + return has_data; + } + + private: + std::string data_; + std::string mime_type_; + size_t offset_; + + IMPLEMENT_REFCOUNTING(ClientSchemeHandler); +}; + +// Implementation of the factory for for creating schema handlers. +class ClientSchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + // Return a new scheme handler instance to handle the request. + virtual CefRefPtr Create(CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) + OVERRIDE { + CEF_REQUIRE_IO_THREAD(); + return new ClientSchemeHandler(); + } + + IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory); +}; + +} // namespace + +void RegisterCustomSchemes(CefRefPtr registrar, + std::vector& cookiable_schemes) { + registrar->AddCustomScheme("client", true, false, false); +} + +void RegisterSchemeHandlers() { + CefRegisterSchemeHandlerFactory("client", "tests", + new ClientSchemeHandlerFactory()); +} + +} // namespace scheme_test +} // namespace client diff --git a/tests/cefclient/scheme_test.h b/tests/cefclient/scheme_test.h new file mode 100644 index 000000000..157e27bfc --- /dev/null +++ b/tests/cefclient/scheme_test.h @@ -0,0 +1,28 @@ +// Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_ +#define CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_ +#pragma once + +#include +#include "include/cef_base.h" + +class CefBrowser; +class CefSchemeRegistrar; + +namespace client { +namespace scheme_test { + +// Register the scheme. +void RegisterCustomSchemes(CefRefPtr registrar, + std::vector& cookiable_schemes); + +// Create the scheme handler. +void RegisterSchemeHandlers(); + +} // namespace scheme_test +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_ diff --git a/tests/cefclient/test_runner.cc b/tests/cefclient/test_runner.cc new file mode 100644 index 000000000..7cd48a0c3 --- /dev/null +++ b/tests/cefclient/test_runner.cc @@ -0,0 +1,432 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/test_runner.h" + +#include "include/base/cef_bind.h" +#include "include/cef_task.h" +#include "include/cef_trace.h" +#include "include/cef_url.h" +#include "include/cef_web_plugin.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_stream_resource_handler.h" +#include "cefclient/binding_test.h" +#include "cefclient/dialog_test.h" +#include "cefclient/main_context.h" +#include "cefclient/resource.h" +#include "cefclient/resource_util.h" +#include "cefclient/scheme_test.h" +#include "cefclient/window_test.h" + +namespace client { +namespace test_runner { + +namespace { + +const char kTestOrigin[] = "http://tests/"; + +// Replace all instances of |from| with |to| in |str|. +std::string StringReplace(const std::string& str, const std::string& from, + const std::string& to) { + std::string result = str; + std::string::size_type pos = 0; + std::string::size_type from_len = from.length(); + std::string::size_type to_len = to.length(); + do { + pos = result.find(from, pos); + if (pos != std::string::npos) { + result.replace(pos, from_len, to); + pos += to_len; + } + } while (pos != std::string::npos); + return result; +} + +void RunGetSourceTest(CefRefPtr browser) { + class Visitor : public CefStringVisitor { + public: + explicit Visitor(CefRefPtr browser) : browser_(browser) {} + virtual void Visit(const CefString& string) OVERRIDE { + std::string source = StringReplace(string, "<", "<"); + source = StringReplace(source, ">", ">"); + std::stringstream ss; + ss << "Source:
" << source <<
+            "
"; + browser_->GetMainFrame()->LoadString(ss.str(), "http://tests/getsource"); + } + private: + CefRefPtr browser_; + IMPLEMENT_REFCOUNTING(Visitor); + }; + + browser->GetMainFrame()->GetSource(new Visitor(browser)); +} + +void RunGetTextTest(CefRefPtr browser) { + class Visitor : public CefStringVisitor { + public: + explicit Visitor(CefRefPtr browser) : browser_(browser) {} + virtual void Visit(const CefString& string) OVERRIDE { + std::string text = StringReplace(string, "<", "<"); + text = StringReplace(text, ">", ">"); + std::stringstream ss; + ss << "Text:
" << text <<
+            "
"; + browser_->GetMainFrame()->LoadString(ss.str(), "http://tests/gettext"); + } + private: + CefRefPtr browser_; + IMPLEMENT_REFCOUNTING(Visitor); + }; + + browser->GetMainFrame()->GetText(new Visitor(browser)); +} + +void RunRequestTest(CefRefPtr browser) { + // Create a new request + CefRefPtr request(CefRequest::Create()); + + // Set the request URL + request->SetURL("http://tests/request"); + + // Add post data to the request. The correct method and content- + // type headers will be set by CEF. + CefRefPtr postDataElement(CefPostDataElement::Create()); + std::string data = "arg1=val1&arg2=val2"; + postDataElement->SetToBytes(data.length(), data.c_str()); + CefRefPtr postData(CefPostData::Create()); + postData->AddElement(postDataElement); + request->SetPostData(postData); + + // Add a custom header + CefRequest::HeaderMap headerMap; + headerMap.insert( + std::make_pair("X-My-Header", "My Header Value")); + request->SetHeaderMap(headerMap); + + // Load the request + browser->GetMainFrame()->LoadRequest(request); +} + +void RunPopupTest(CefRefPtr browser) { + browser->GetMainFrame()->ExecuteJavaScript( + "window.open('http://www.google.com');", "about:blank", 0); +} + +void RunPluginInfoTest(CefRefPtr browser) { + class Visitor : public CefWebPluginInfoVisitor { + public: + explicit Visitor(CefRefPtr browser) + : browser_(browser) { + html_ = "Plugin Info Test" + "" + "\nInstalled plugins:"; + } + ~Visitor() { + html_ += "\n"; + + // Load the html in the browser. + browser_->GetMainFrame()->LoadString(html_, "http://tests/plugin_info"); + } + + virtual bool Visit(CefRefPtr info, int count, int total) + OVERRIDE { + html_ += "\n

Name: " + info->GetName().ToString() + + "\n
Description: " + info->GetDescription().ToString() + + "\n
Version: " + info->GetVersion().ToString() + + "\n
Path: " + info->GetPath().ToString(); + return true; + } + + private: + std::string html_; + CefRefPtr browser_; + IMPLEMENT_REFCOUNTING(Visitor); + }; + + CefVisitWebPluginInfo(new Visitor(browser)); +} + +void ModifyZoom(CefRefPtr browser, double delta) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, base::Bind(&ModifyZoom, browser, delta)); + return; + } + + browser->GetHost()->SetZoomLevel( + browser->GetHost()->GetZoomLevel() + delta); +} + +void BeginTracing() { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, base::Bind(&BeginTracing)); + return; + } + + CefBeginTracing(CefString(), NULL); +} + +void EndTracing(CefRefPtr browser) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, base::Bind(&EndTracing, browser)); + return; + } + + class Client : public CefEndTracingCallback, + public CefRunFileDialogCallback { + public: + explicit Client(CefRefPtr browser) + : browser_(browser) { + RunDialog(); + } + + void RunDialog() { + static const char kDefaultFileName[] = "trace.txt"; + std::string path = MainContext::Get()->GetDownloadPath(kDefaultFileName); + if (path.empty()) + path = kDefaultFileName; + + // Results in a call to OnFileDialogDismissed. + browser_->GetHost()->RunFileDialog( + FILE_DIALOG_SAVE, + CefString(), // title + path, + std::vector(), // accept_filters + 0, // selected_accept_filter + this); + } + + virtual void OnFileDialogDismissed( + int selected_accept_filter, + const std::vector& file_paths) OVERRIDE { + if (!file_paths.empty()) { + // File selected. Results in a call to OnEndTracingComplete. + CefEndTracing(file_paths.front(), this); + } else { + // No file selected. Discard the trace data. + CefEndTracing(CefString(), NULL); + } + } + + virtual void OnEndTracingComplete( + const CefString& tracing_file) OVERRIDE { + Alert(browser_, + "File \"" + tracing_file.ToString() + "\" saved successfully."); + } + + private: + CefRefPtr browser_; + + IMPLEMENT_REFCOUNTING(Client); + }; + + new Client(browser); +} + +void RunOtherTests(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("http://tests/other_tests"); +} + +// Retrieve the file name and mime type based on the specified url. +bool ParseTestUrl(const std::string& url, + std::string* file_name, + std::string* mime_type) { + // Retrieve the path component. + CefURLParts parts; + CefParseURL(url, parts); + std::string file = CefString(&parts.path); + if (file.size() < 2) + return false; + + // Remove the leading slash. + file = file.substr(1); + + // Verify that the file name is valid. + for(size_t i = 0; i < file.size(); ++i) { + const char c = file[i]; + if (!isalpha(c) && !isdigit(c) && c != '_' && c != '.') + return false; + } + + // Determine the mime type based on the file extension, if any. + size_t pos = file.rfind("."); + if (pos != std::string::npos) { + std::string ext = file.substr(pos + 1); + if (ext == "html") + *mime_type = "text/html"; + else if (ext == "png") + *mime_type = "image/png"; + else + return false; + } else { + // Default to an html extension if none is specified. + *mime_type = "text/html"; + file += ".html"; + } + + *file_name = file; + return true; +} + +} // namespace + +void RunTest(CefRefPtr browser, int id) { + if (!browser) + return; + + switch (id) { + case ID_TESTS_GETSOURCE: + RunGetSourceTest(browser); + break; + case ID_TESTS_GETTEXT: + RunGetTextTest(browser); + break; + case ID_TESTS_POPUP: + RunPopupTest(browser); + break; + case ID_TESTS_REQUEST: + RunRequestTest(browser); + break; + case ID_TESTS_PLUGIN_INFO: + RunPluginInfoTest(browser); + break; + case ID_TESTS_ZOOM_IN: + ModifyZoom(browser, 0.5); + break; + case ID_TESTS_ZOOM_OUT: + ModifyZoom(browser, -0.5); + break; + case ID_TESTS_ZOOM_RESET: + browser->GetHost()->SetZoomLevel(0.0); + break; + case ID_TESTS_TRACING_BEGIN: + BeginTracing(); + break; + case ID_TESTS_TRACING_END: + EndTracing(browser); + break; + case ID_TESTS_PRINT: + browser->GetHost()->Print(); + break; + case ID_TESTS_OTHER_TESTS: + RunOtherTests(browser); + break; + } +} + +void DumpRequestContents(CefRefPtr request, std::string& str) { + std::stringstream ss; + + ss << "URL: " << std::string(request->GetURL()); + ss << "\nMethod: " << std::string(request->GetMethod()); + + CefRequest::HeaderMap headerMap; + request->GetHeaderMap(headerMap); + if (headerMap.size() > 0) { + ss << "\nHeaders:"; + CefRequest::HeaderMap::const_iterator it = headerMap.begin(); + for (; it != headerMap.end(); ++it) { + ss << "\n\t" << std::string((*it).first) << ": " << + std::string((*it).second); + } + } + + CefRefPtr postData = request->GetPostData(); + if (postData.get()) { + CefPostData::ElementVector elements; + postData->GetElements(elements); + if (elements.size() > 0) { + ss << "\nPost Data:"; + CefRefPtr element; + CefPostData::ElementVector::const_iterator it = elements.begin(); + for (; it != elements.end(); ++it) { + element = (*it); + if (element->GetType() == PDE_TYPE_BYTES) { + // the element is composed of bytes + ss << "\n\tBytes: "; + if (element->GetBytesCount() == 0) { + ss << "(empty)"; + } else { + // retrieve the data. + size_t size = element->GetBytesCount(); + char* bytes = new char[size]; + element->GetBytes(size, bytes); + ss << std::string(bytes, size); + delete [] bytes; + } + } else if (element->GetType() == PDE_TYPE_FILE) { + ss << "\n\tFile: " << std::string(element->GetFile()); + } + } + } + } + + str = ss.str(); +} + +CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) { + std::string url = request->GetURL(); + if (url.find(kTestOrigin) == 0) { + // Handle URLs in the test origin. + std::string file_name, mime_type; + if (ParseTestUrl(url, &file_name, &mime_type)) { + if (file_name == "request.html") { + // Show the request contents. + std::string dump; + DumpRequestContents(request, dump); + std::string str = "
" + dump +
+                          "
"; + CefRefPtr stream = + CefStreamReader::CreateForData( + static_cast(const_cast(str.c_str())), + str.size()); + DCHECK(stream.get()); + return new CefStreamResourceHandler("text/html", stream); + } else { + // Load the resource from file. + CefRefPtr stream = + GetBinaryResourceReader(file_name.c_str()); + if (stream.get()) + return new CefStreamResourceHandler(mime_type, stream); + } + } + } + + return NULL; +} + +void Alert(CefRefPtr browser, const std::string& message) { + // Escape special characters in the message. + std::string msg = StringReplace(message, "\\", "\\\\"); + msg = StringReplace(msg, "'", "\\'"); + + // Execute a JavaScript alert(). + CefRefPtr frame = browser->GetMainFrame(); + frame->ExecuteJavaScript("alert('" + msg + "');", frame->GetURL(), 0); +} + +void CreateMessageHandlers(MessageHandlerSet& handlers) { + // Create the dialog test handlers. + dialog_test::CreateMessageHandlers(handlers); + + // Create the binding test handlers. + binding_test::CreateMessageHandlers(handlers); + + // Create the window test handlers. + window_test::CreateMessageHandlers(handlers); +} + +void RegisterSchemeHandlers() { + // Register the scheme handler. + scheme_test::RegisterSchemeHandlers(); +} + +} // namespace test_runner +} // namespace client diff --git a/tests/cefclient/test_runner.h b/tests/cefclient/test_runner.h new file mode 100644 index 000000000..2dc428398 --- /dev/null +++ b/tests/cefclient/test_runner.h @@ -0,0 +1,45 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_TEST_RUNNER_H_ +#define CEF_TESTS_CEFCLIENT_TEST_RUNNER_H_ + +#include +#include + +#include "include/cef_browser.h" +#include "include/cef_resource_handler.h" +#include "include/cef_request.h" +#include "include/wrapper/cef_message_router.h" + +namespace client { +namespace test_runner { + +// Run a test. +void RunTest(CefRefPtr browser, int id); + +// Dump the contents of the request into a string. +void DumpRequestContents(CefRefPtr request, std::string& str); + +// Get test resources. +CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request); + +// Show a JS alert message. +void Alert(CefRefPtr browser, const std::string& message); + +// Create all CefMessageRouterBrowserSide::Handler objects. They will be +// deleted when the ClientHandler is destroyed. +typedef std::set MessageHandlerSet; +void CreateMessageHandlers(MessageHandlerSet& handlers); + +// Register scheme handlers for tests. +void RegisterSchemeHandlers(); + +} // namespace test_runner +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_TEST_RUNNER_H_ diff --git a/tests/cefclient/util_win.cc b/tests/cefclient/util_win.cc new file mode 100644 index 000000000..aa0d49af7 --- /dev/null +++ b/tests/cefclient/util_win.cc @@ -0,0 +1,136 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/util_win.h" + +#include "include/base/cef_logging.h" +#include "include/internal/cef_types.h" + +namespace client { + +void SetUserDataPtr(HWND hWnd, void* ptr) { + SetLastError(ERROR_SUCCESS); + LONG_PTR result = ::SetWindowLongPtr( + hWnd, GWLP_USERDATA, reinterpret_cast(ptr)); + CHECK(result != 0 || GetLastError() == ERROR_SUCCESS); +} + +WNDPROC SetWndProcPtr(HWND hWnd, WNDPROC wndProc) { + WNDPROC old = + reinterpret_cast(::GetWindowLongPtr(hWnd, GWLP_WNDPROC)); + CHECK(old != NULL); + LONG_PTR result = ::SetWindowLongPtr( + hWnd, GWLP_WNDPROC, reinterpret_cast(wndProc)); + CHECK(result != 0 || GetLastError() == ERROR_SUCCESS); + return old; +} + +int GetCefMouseModifiers(WPARAM wparam) { + int modifiers = 0; + if (wparam & MK_CONTROL) + modifiers |= EVENTFLAG_CONTROL_DOWN; + if (wparam & MK_SHIFT) + modifiers |= EVENTFLAG_SHIFT_DOWN; + if (IsKeyDown(VK_MENU)) + modifiers |= EVENTFLAG_ALT_DOWN; + if (wparam & MK_LBUTTON) + modifiers |= EVENTFLAG_LEFT_MOUSE_BUTTON; + if (wparam & MK_MBUTTON) + modifiers |= EVENTFLAG_MIDDLE_MOUSE_BUTTON; + if (wparam & MK_RBUTTON) + modifiers |= EVENTFLAG_RIGHT_MOUSE_BUTTON; + + // Low bit set from GetKeyState indicates "toggled". + if (::GetKeyState(VK_NUMLOCK) & 1) + modifiers |= EVENTFLAG_NUM_LOCK_ON; + if (::GetKeyState(VK_CAPITAL) & 1) + modifiers |= EVENTFLAG_CAPS_LOCK_ON; + return modifiers; +} + +int GetCefKeyboardModifiers(WPARAM wparam, LPARAM lparam) { + int modifiers = 0; + if (IsKeyDown(VK_SHIFT)) + modifiers |= EVENTFLAG_SHIFT_DOWN; + if (IsKeyDown(VK_CONTROL)) + modifiers |= EVENTFLAG_CONTROL_DOWN; + if (IsKeyDown(VK_MENU)) + modifiers |= EVENTFLAG_ALT_DOWN; + + // Low bit set from GetKeyState indicates "toggled". + if (::GetKeyState(VK_NUMLOCK) & 1) + modifiers |= EVENTFLAG_NUM_LOCK_ON; + if (::GetKeyState(VK_CAPITAL) & 1) + modifiers |= EVENTFLAG_CAPS_LOCK_ON; + + switch (wparam) { + case VK_RETURN: + if ((lparam >> 16) & KF_EXTENDED) + modifiers |= EVENTFLAG_IS_KEY_PAD; + break; + case VK_INSERT: + case VK_DELETE: + case VK_HOME: + case VK_END: + case VK_PRIOR: + case VK_NEXT: + case VK_UP: + case VK_DOWN: + case VK_LEFT: + case VK_RIGHT: + if (!((lparam >> 16) & KF_EXTENDED)) + modifiers |= EVENTFLAG_IS_KEY_PAD; + break; + case VK_NUMLOCK: + case VK_NUMPAD0: + case VK_NUMPAD1: + case VK_NUMPAD2: + case VK_NUMPAD3: + case VK_NUMPAD4: + case VK_NUMPAD5: + case VK_NUMPAD6: + case VK_NUMPAD7: + case VK_NUMPAD8: + case VK_NUMPAD9: + case VK_DIVIDE: + case VK_MULTIPLY: + case VK_SUBTRACT: + case VK_ADD: + case VK_DECIMAL: + case VK_CLEAR: + modifiers |= EVENTFLAG_IS_KEY_PAD; + break; + case VK_SHIFT: + if (IsKeyDown(VK_LSHIFT)) + modifiers |= EVENTFLAG_IS_LEFT; + else if (IsKeyDown(VK_RSHIFT)) + modifiers |= EVENTFLAG_IS_RIGHT; + break; + case VK_CONTROL: + if (IsKeyDown(VK_LCONTROL)) + modifiers |= EVENTFLAG_IS_LEFT; + else if (IsKeyDown(VK_RCONTROL)) + modifiers |= EVENTFLAG_IS_RIGHT; + break; + case VK_MENU: + if (IsKeyDown(VK_LMENU)) + modifiers |= EVENTFLAG_IS_LEFT; + else if (IsKeyDown(VK_RMENU)) + modifiers |= EVENTFLAG_IS_RIGHT; + break; + case VK_LWIN: + modifiers |= EVENTFLAG_IS_LEFT; + break; + case VK_RWIN: + modifiers |= EVENTFLAG_IS_RIGHT; + break; + } + return modifiers; +} + +bool IsKeyDown(WPARAM wparam) { + return (GetKeyState(wparam) & 0x8000) != 0; +} + +} // namespace client diff --git a/tests/cefclient/util_win.h b/tests/cefclient/util_win.h new file mode 100644 index 000000000..0ae37e79b --- /dev/null +++ b/tests/cefclient/util_win.h @@ -0,0 +1,26 @@ +// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include + +namespace client { + +// Set the window's user data pointer. +void SetUserDataPtr(HWND hWnd, void* ptr); + +// Return the window's user data pointer. +template +T GetUserDataPtr(HWND hWnd) { + return reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); +} + +// Set the window's window procedure pointer and return the old value. +WNDPROC SetWndProcPtr(HWND hWnd, WNDPROC wndProc); + +int GetCefMouseModifiers(WPARAM wparam); +int GetCefKeyboardModifiers(WPARAM wparam, LPARAM lparam); +bool IsKeyDown(WPARAM wparam); + +} // namespace client diff --git a/tests/cefclient/window_test.cc b/tests/cefclient/window_test.cc new file mode 100644 index 000000000..18c2ffa9f --- /dev/null +++ b/tests/cefclient/window_test.cc @@ -0,0 +1,110 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/window_test.h" + +#include +#include +#include +#include + +#include "include/base/cef_bind.h" +#include "include/wrapper/cef_stream_resource_handler.h" +#include "cefclient/main_message_loop.h" + +namespace client { +namespace window_test { + +namespace { + +const char kTestUrl[] = "http://tests/window"; +const char kMessagePositionName[] = "WindowTest.Position"; +const char kMessageMinimizeName[] = "WindowTest.Minimize"; +const char kMessageMaximizeName[] = "WindowTest.Maximize"; +const char kMessageRestoreName[] = "WindowTest.Restore"; + +// Handle messages in the browser process. +class Handler : public CefMessageRouterBrowserSide::Handler { + public: + Handler() {} + + // Called due to cefBroadcast execution in window.html. + virtual bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) OVERRIDE { + // Only handle messages from the test URL. + const std::string& url = frame->GetURL(); + if (url.find(kTestUrl) != 0) + return false; + + const std::string& message_name = request; + if (message_name.find(kMessagePositionName) == 0) { + // Parse the comma-delimited list of integer values. + std::vector vec; + const std::string& vals = + message_name.substr(sizeof(kMessagePositionName)); + std::stringstream ss(vals); + int i; + while (ss >> i) { + vec.push_back(i); + if (ss.peek() == ',') + ss.ignore(); + } + + if (vec.size() == 4) { + // Execute SetPos() on the main thread. + MAIN_POST_CLOSURE(base::Bind(&SetPos, browser, + vec[0], vec[1], vec[2], vec[3])); + } + } else if (message_name == kMessageMinimizeName) { + // Execute Minimize() on the main thread. + MAIN_POST_CLOSURE(base::Bind(&Minimize, browser)); + } else if (message_name == kMessageMaximizeName) { + // Execute Maximize() on the main thread. + MAIN_POST_CLOSURE(base::Bind(&Maximize, browser)); + } else if (message_name == kMessageRestoreName) { + // Execute Restore() on the main thread. + MAIN_POST_CLOSURE(base::Bind(&Restore, browser)); + } else { + NOTREACHED(); + } + + callback->Success(""); + return true; + } +}; + +} // namespace + +void ModifyBounds(const CefRect& display, CefRect& window) { + window.x += display.x; + window.y += display.y; + + if (window.x < display.x) + window.x = display.x; + if (window.y < display.y) + window.y = display.y; + if (window.width < 100) + window.width = 100; + else if (window.width >= display.width) + window.width = display.width; + if (window.height < 100) + window.height = 100; + else if (window.height >= display.height) + window.height = display.height; + if (window.x + window.width >= display.x + display.width) + window.x = display.x + display.width - window.width; + if (window.y + window.height >= display.y + display.height) + window.y = display.y + display.height - window.height; +} + +void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers) { + handlers.insert(new Handler()); +} + +} // namespace window_test +} // namespace client diff --git a/tests/cefclient/window_test.h b/tests/cefclient/window_test.h new file mode 100644 index 000000000..a81f0fe9f --- /dev/null +++ b/tests/cefclient/window_test.h @@ -0,0 +1,31 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFCLIENT_WINDOW_TEST_H_ +#define CEF_TESTS_CEFCLIENT_WINDOW_TEST_H_ +#pragma once + +#include "cefclient/test_runner.h" + +namespace client { +namespace window_test { + +/// Handler creation. +void CreateMessageHandlers(test_runner::MessageHandlerSet& handlers); + +// Fit |window| inside |display|. Coordinates are relative to the upper-left +// corner of the display. +void ModifyBounds(const CefRect& display, CefRect& window); + +// Platform implementations. +void SetPos(CefRefPtr browser, + int x, int y, int width, int height); +void Minimize(CefRefPtr browser); +void Maximize(CefRefPtr browser); +void Restore(CefRefPtr browser); + +} // namespace window_test +} // namespace client + +#endif // CEF_TESTS_CEFCLIENT_WINDOW_TEST_H_ diff --git a/tests/cefclient/window_test_gtk.cc b/tests/cefclient/window_test_gtk.cc new file mode 100644 index 000000000..13036a591 --- /dev/null +++ b/tests/cefclient/window_test_gtk.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/window_test.h" +#include "cefclient/client_handler.h" + +#include + +namespace client { +namespace window_test { + +namespace { + +GtkWindow* GetWindow(CefRefPtr browser) { + // We can't get the GtkWidget* from the X11 Window that would be returned via + // CefBrowserHost::GetWindowHandle so retrieve it via the ClientHandler + // instance instead. + CefRefPtr handler = + static_cast(browser->GetHost()->GetClient().get()); + return GTK_WINDOW(gtk_widget_get_toplevel(handler->GetMainWindowHandle())); +} + +bool IsMaximized(GtkWindow* window) { + GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window)); + gint state = gdk_window_get_state(gdk_window); + return (state & GDK_WINDOW_STATE_MAXIMIZED) ? true : false; +} + +} // namespace + +void SetPos(CefRefPtr browser, int x, int y, int width, + int height) { + GtkWindow* window = GetWindow(browser); + GdkWindow* gdk_window = gtk_widget_get_window(GTK_WIDGET(window)); + + // Make sure the window isn't minimized or maximized. + if (IsMaximized(window)) + gtk_window_unmaximize(window); + else + gtk_window_present(window); + + // Retrieve information about the display that contains the window. + GdkScreen* screen = gdk_screen_get_default(); + gint monitor = gdk_screen_get_monitor_at_window(screen, gdk_window); + GdkRectangle rect; + gdk_screen_get_monitor_geometry(screen, monitor, &rect); + + // Make sure the window is inside the display. + CefRect display_rect(rect.x, rect.y, rect.width, rect.height); + CefRect window_rect(x, y, width, height); + ModifyBounds(display_rect, window_rect); + + gdk_window_move_resize(gdk_window, window_rect.x, window_rect.y, + window_rect.width, window_rect.height); +} + +void Minimize(CefRefPtr browser) { + GtkWindow* window = GetWindow(browser); + + // Unmaximize the window before minimizing so restore behaves correctly. + if (IsMaximized(window)) + gtk_window_unmaximize(window); + + gtk_window_iconify(window); +} + +void Maximize(CefRefPtr browser) { + gtk_window_maximize(GetWindow(browser)); +} + +void Restore(CefRefPtr browser) { + GtkWindow* window = GetWindow(browser); + if (IsMaximized(window)) + gtk_window_unmaximize(window); + else + gtk_window_present(window); +} + +} // namespace window_test +} // namespace client diff --git a/tests/cefclient/window_test_mac.mm b/tests/cefclient/window_test_mac.mm new file mode 100644 index 000000000..5580b2fae --- /dev/null +++ b/tests/cefclient/window_test_mac.mm @@ -0,0 +1,72 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/window_test.h" + +#import + +namespace client { +namespace window_test { + +namespace { + +NSWindow* GetWindow(CefRefPtr browser) { + NSView* view = (NSView*)browser->GetHost()->GetWindowHandle(); + return [view window]; +} + +} // namespace + +void SetPos(CefRefPtr browser, int x, int y, int width, + int height) { + NSWindow* window = GetWindow(browser); + + // Make sure the window isn't minimized or maximized. + if ([window isMiniaturized]) + [window deminiaturize:nil]; + else if ([window isZoomed]) + [window performZoom:nil]; + + // Retrieve information for the display that contains the window. + NSScreen* screen = [window screen]; + if (screen == nil) + screen = [NSScreen mainScreen]; + NSRect frame = [screen frame]; + NSRect visibleFrame = [screen visibleFrame]; + + // Make sure the window is inside the display. + CefRect display_rect( + visibleFrame.origin.x, + frame.size.height - visibleFrame.size.height - visibleFrame.origin.y, + visibleFrame.size.width, + visibleFrame.size.height); + CefRect window_rect(x, y, width, height); + ModifyBounds(display_rect, window_rect); + + NSRect newRect; + newRect.origin.x = window_rect.x; + newRect.origin.y = frame.size.height - window_rect.height - window_rect.y; + newRect.size.width = window_rect.width; + newRect.size.height = window_rect.height; + [window setFrame:newRect display:YES]; +} + +void Minimize(CefRefPtr browser) { + [GetWindow(browser) performMiniaturize:nil]; +} + +void Maximize(CefRefPtr browser) { + [GetWindow(browser) performZoom:nil]; +} + +void Restore(CefRefPtr browser) { + NSWindow* window = GetWindow(browser); + if ([window isMiniaturized]) + [window deminiaturize:nil]; + else if ([window isZoomed]) + [window performZoom:nil]; +} + +} // namespace window_test +} // namespace client diff --git a/tests/cefclient/window_test_win.cc b/tests/cefclient/window_test_win.cc new file mode 100644 index 000000000..65fc3a165 --- /dev/null +++ b/tests/cefclient/window_test_win.cc @@ -0,0 +1,83 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefclient/window_test.h" + +namespace client { +namespace window_test { + +namespace { + +HWND GetRootHwnd(CefRefPtr browser) { + return ::GetAncestor(browser->GetHost()->GetWindowHandle(), GA_ROOT); +} + +// Toggles the current display state. +void Toggle(HWND root_hwnd, UINT nCmdShow) { + // Retrieve current window placement information. + WINDOWPLACEMENT placement; + ::GetWindowPlacement(root_hwnd, &placement); + + if (placement.showCmd == nCmdShow) + ::ShowWindow(root_hwnd, SW_RESTORE); + else + ::ShowWindow(root_hwnd, nCmdShow); +} + +} // namespace + +void SetPos(CefRefPtr browser, + int x, int y, int width, int height) { + HWND root_hwnd = GetRootHwnd(browser); + + // Retrieve current window placement information. + WINDOWPLACEMENT placement; + ::GetWindowPlacement(root_hwnd, &placement); + + // Retrieve information about the display that contains the window. + HMONITOR monitor = MonitorFromRect(&placement.rcNormalPosition, + MONITOR_DEFAULTTONEAREST); + MONITORINFO info; + info.cbSize = sizeof(info); + GetMonitorInfo(monitor, &info); + + // Make sure the window is inside the display. + CefRect display_rect( + info.rcWork.left, + info.rcWork.top, + info.rcWork.right - info.rcWork.left, + info.rcWork.bottom - info.rcWork.top); + CefRect window_rect(x, y, width, height); + ModifyBounds(display_rect, window_rect); + + if (placement.showCmd == SW_MINIMIZE || placement.showCmd == SW_MAXIMIZE) { + // The window is currently minimized or maximized. Restore it to the desired + // position. + placement.rcNormalPosition.left = window_rect.x; + placement.rcNormalPosition.right = window_rect.x + window_rect.width; + placement.rcNormalPosition.top = window_rect.y; + placement.rcNormalPosition.bottom = window_rect.y + window_rect.height; + ::SetWindowPlacement(root_hwnd, &placement); + ::ShowWindow(root_hwnd, SW_RESTORE); + } else { + // Set the window position. + ::SetWindowPos(root_hwnd, NULL, window_rect.x, window_rect.y, + window_rect.width, window_rect.height, SWP_NOZORDER); + } +} + +void Minimize(CefRefPtr browser) { + Toggle(GetRootHwnd(browser), SW_MINIMIZE); +} + +void Maximize(CefRefPtr browser) { + Toggle(GetRootHwnd(browser), SW_MAXIMIZE); +} + +void Restore(CefRefPtr browser) { + ::ShowWindow(GetRootHwnd(browser), SW_RESTORE); +} + +} // namespace window_test +} // namespace client diff --git a/tests/cefsimple/CMakeLists.txt.in b/tests/cefsimple/CMakeLists.txt.in new file mode 100644 index 000000000..b4ca941bc --- /dev/null +++ b/tests/cefsimple/CMakeLists.txt.in @@ -0,0 +1,164 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +# +# Source files. +# + +# cefsimple sources. +{{ + 'prefix': 'cefsimple', + 'set': 'CEFSIMPLE_SRCS', + 'includes': [ + 'cefsimple_sources_common', + 'cefsimple_sources_win:WINDOWS', + 'cefsimple_sources_mac:MACOSX', + 'cefsimple_sources_linux:LINUX', + ], +}} + +# cefsimple helper sources. +{{ + 'prefix': 'cefsimple_helper', + 'includes': [ + 'cefsimple_sources_mac_helper:MACOSX', + ], +}} + +# cefsimple resources. +{{ + 'prefix': 'cefsimple_resources', + 'set': 'CEFSIMPLE_RESOURCES_SRCS', + 'includes': [ + 'cefsimple_bundle_resources_mac:MACOSX', + ], +}} + + +# +# Shared configuration. +# + +# Target executable names. +set(CEF_TARGET "cefsimple") +if(OS_MACOSX) + set(CEF_HELPER_TARGET "cefsimple Helper") +endif() + +# Logical target used to link the libcef library. +ADD_LOGICAL_TARGET("libcef_lib" "${CEF_LIB_DEBUG}" "${CEF_LIB_RELEASE}") + +# Determine the target output directory. +SET_CEF_TARGET_OUT_DIR() + + +# +# Linux configuration. +# + +if(OS_LINUX) + # Executable target. + add_executable(${CEF_TARGET} ${CEFSIMPLE_SRCS}) + add_dependencies(${CEF_TARGET} libcef_dll_wrapper) + target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + + # Set rpath so that libraries can be placed next to the executable. + set_target_properties(${CEF_TARGET} PROPERTIES INSTALL_RPATH "$ORIGIN") + set_target_properties(${CEF_TARGET} PROPERTIES BUILD_WITH_INSTALL_RPATH TRUE) + set_target_properties(${CEF_TARGET} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CEF_TARGET_OUT_DIR}) + + # Copy binary and resource files to the target output directory. + COPY_FILES("${CEF_TARGET}" "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "${CEF_TARGET_OUT_DIR}") + COPY_FILES("${CEF_TARGET}" "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "${CEF_TARGET_OUT_DIR}") + + # Set SUID permissions on the chrome-sandbox target. + SET_LINUX_SUID_PERMISSIONS("${CEF_TARGET}" "${CEF_TARGET_OUT_DIR}/chrome-sandbox") +endif() + + +# +# Mac OS X configuration. +# + +if(OS_MACOSX) + # Output paths for the app bundles. + set(CEF_APP "${CEF_TARGET_OUT_DIR}/${CEF_TARGET}.app") + set(CEF_HELPER_APP "${CEF_TARGET_OUT_DIR}/${CEF_HELPER_TARGET}.app") + + # Variable referenced from Info.plist files. + set(PRODUCT_NAME "${CEF_TARGET}") + + # Helper executable target. + add_executable(${CEF_HELPER_TARGET} MACOSX_BUNDLE ${CEFSIMPLE_HELPER_SRCS}) + add_dependencies(${CEF_HELPER_TARGET} libcef_dll_wrapper) + target_link_libraries(${CEF_HELPER_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + set_target_properties(${CEF_HELPER_TARGET} PROPERTIES + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/mac/helper-Info.plist + ) + + # Fix the framework link in the helper executable. + FIX_MACOSX_HELPER_FRAMEWORK_LINK(${CEF_HELPER_TARGET} ${CEF_HELPER_APP}) + + # Main executable target. + add_executable(${CEF_TARGET} MACOSX_BUNDLE ${CEFSIMPLE_RESOURCES_SRCS} ${CEFSIMPLE_SRCS}) + add_dependencies(${CEF_TARGET} libcef_dll_wrapper "${CEF_HELPER_TARGET}") + target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + set_target_properties(${CEF_TARGET} PROPERTIES + RESOURCE "${CEFSIMPLE_RESOURCES_SRCS}" + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_CURRENT_SOURCE_DIR}/mac/Info.plist + ) + + # Copy files into the main app bundle. + add_custom_command( + TARGET ${CEF_TARGET} + POST_BUILD + # Copy the helper app bundle into the Frameworks directory. + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${CEF_HELPER_APP}" + "${CEF_APP}/Contents/Frameworks/${CEF_HELPER_TARGET}.app" + # Copy the CEF framework into the Frameworks directory. + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${CEF_BINARY_DIR}/Chromium Embedded Framework.framework" + "${CEF_APP}/Contents/Frameworks/Chromium Embedded Framework.framework" + VERBATIM + ) + + # Fix the framework link in the main executable. + FIX_MACOSX_MAIN_FRAMEWORK_LINK(${CEF_TARGET} ${CEF_APP}) + + # Make the other helper app bundles. + MAKE_MACOSX_HELPERS(${CEF_TARGET} ${CEF_APP}) + + if(NOT ${CMAKE_GENERATOR} STREQUAL "Xcode") + # Manually process and copy over resource files. + # The Xcode generator handles this via the set_target_properties RESOURCE directive. + set(PREFIXES "mac/") # Remove these prefixes from input file paths. + COPY_MACOSX_RESOURCES("${CEFSIMPLE_RESOURCES_SRCS}" "${PREFIXES}" "${CEF_TARGET}" "${CMAKE_CURRENT_SOURCE_DIR}" "${CEF_APP}") + endif() +endif() + + +# +# Windows configuration. +# + +if(OS_WINDOWS) + # Executable target. + add_executable(${CEF_TARGET} WIN32 ${CEFSIMPLE_SRCS}) + add_dependencies(${CEF_TARGET} libcef_dll_wrapper) + target_link_libraries(${CEF_TARGET} libcef_lib libcef_dll_wrapper ${CEF_STANDARD_LIBS}) + + if(USE_SANDBOX) + # Logical target used to link the cef_sandbox library. + ADD_LOGICAL_TARGET("cef_sandbox_lib" "${CEF_SANDBOX_LIB_DEBUG}" "${CEF_SANDBOX_LIB_RELEASE}") + target_link_libraries(${CEF_TARGET} cef_sandbox_lib ${CEF_SANDBOX_STANDARD_LIBS}) + endif() + + # Add the custom manifest files to the executable. + ADD_WINDOWS_MANIFEST("${CEF_TARGET}") + + # Copy binary and resource files to the target output directory. + COPY_FILES("${CEF_TARGET}" "${CEF_BINARY_FILES}" "${CEF_BINARY_DIR}" "${CEF_TARGET_OUT_DIR}") + COPY_FILES("${CEF_TARGET}" "${CEF_RESOURCE_FILES}" "${CEF_RESOURCE_DIR}" "${CEF_TARGET_OUT_DIR}") +endif() diff --git a/tests/cefsimple/cefsimple.exe.manifest b/tests/cefsimple/cefsimple.exe.manifest new file mode 100644 index 000000000..d36f084b6 --- /dev/null +++ b/tests/cefsimple/cefsimple.exe.manifest @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/tests/cefsimple/cefsimple.rc b/tests/cefsimple/cefsimple.rc new file mode 100644 index 000000000..c4f3f2973 --- /dev/null +++ b/tests/cefsimple/cefsimple.rc @@ -0,0 +1,79 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#define APSTUDIO_HIDDEN_SYMBOLS +#include "windows.h" +#undef APSTUDIO_HIDDEN_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_CEFSIMPLE ICON "res\cefsimple.ico" +IDI_SMALL ICON "res\small.ico" + + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#define APSTUDIO_HIDDEN_SYMBOLS\r\n" + "#include ""windows.h""\r\n" + "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/tests/cefsimple/cefsimple_linux.cc b/tests/cefsimple/cefsimple_linux.cc new file mode 100644 index 000000000..98c7dfee3 --- /dev/null +++ b/tests/cefsimple/cefsimple_linux.cc @@ -0,0 +1,68 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefsimple/simple_app.h" + +#include + +#include "include/base/cef_logging.h" + +namespace { + +int XErrorHandlerImpl(Display *display, XErrorEvent *event) { + LOG(WARNING) + << "X error received: " + << "type " << event->type << ", " + << "serial " << event->serial << ", " + << "error_code " << static_cast(event->error_code) << ", " + << "request_code " << static_cast(event->request_code) << ", " + << "minor_code " << static_cast(event->minor_code); + return 0; +} + +int XIOErrorHandlerImpl(Display *display) { + return 0; +} + +} // namespace + + +// Entry point function for all processes. +int main(int argc, char* argv[]) { + // Provide CEF with command-line arguments. + CefMainArgs main_args(argc, argv); + + // SimpleApp implements application-level callbacks. It will create the first + // browser instance in OnContextInitialized() after CEF has initialized. + CefRefPtr app(new SimpleApp); + + // CEF applications have multiple sub-processes (render, plugin, GPU, etc) + // that share the same executable. This function checks the command-line and, + // if this is a sub-process, executes the appropriate logic. + int exit_code = CefExecuteProcess(main_args, app.get(), NULL); + if (exit_code >= 0) { + // The sub-process has completed so return here. + return exit_code; + } + + // Specify CEF global settings here. + CefSettings settings; + + // Install xlib error handlers so that the application won't be terminated + // on non-fatal errors. + XSetErrorHandler(XErrorHandlerImpl); + XSetIOErrorHandler(XIOErrorHandlerImpl); + + // Initialize CEF for the browser process. + CefInitialize(main_args, settings, app.get(), NULL); + + // Run the CEF message loop. This will block until CefQuitMessageLoop() is + // called. + CefRunMessageLoop(); + + // Shut down CEF. + CefShutdown(); + + return 0; +} diff --git a/tests/cefsimple/cefsimple_mac.mm b/tests/cefsimple/cefsimple_mac.mm new file mode 100644 index 000000000..d4052fa3a --- /dev/null +++ b/tests/cefsimple/cefsimple_mac.mm @@ -0,0 +1,150 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2010 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#import + +#include "cefsimple/simple_app.h" +#include "cefsimple/simple_handler.h" +#include "include/cef_application_mac.h" +#include "include/wrapper/cef_helpers.h" + +// Receives notifications from the application. +@interface SimpleAppDelegate : NSObject +- (void)createApplication:(id)object; +- (void)tryToTerminateApplication:(NSApplication*)app; +@end + +// Provide the CefAppProtocol implementation required by CEF. +@interface SimpleApplication : NSApplication { +@private + BOOL handlingSendEvent_; +} +@end + +@implementation SimpleApplication +- (BOOL)isHandlingSendEvent { + return handlingSendEvent_; +} + +- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { + handlingSendEvent_ = handlingSendEvent; +} + +- (void)sendEvent:(NSEvent*)event { + CefScopedSendingEvent sendingEventScoper; + [super sendEvent:event]; +} + +// |-terminate:| is the entry point for orderly "quit" operations in Cocoa. This +// includes the application menu's quit menu item and keyboard equivalent, the +// application's dock icon menu's quit menu item, "quit" (not "force quit") in +// the Activity Monitor, and quits triggered by user logout and system restart +// and shutdown. +// +// The default |-terminate:| implementation ends the process by calling exit(), +// and thus never leaves the main run loop. This is unsuitable for Chromium +// since Chromium depends on leaving the main run loop to perform an orderly +// shutdown. We support the normal |-terminate:| interface by overriding the +// default implementation. Our implementation, which is very specific to the +// needs of Chromium, works by asking the application delegate to terminate +// using its |-tryToTerminateApplication:| method. +// +// |-tryToTerminateApplication:| differs from the standard +// |-applicationShouldTerminate:| in that no special event loop is run in the +// case that immediate termination is not possible (e.g., if dialog boxes +// allowing the user to cancel have to be shown). Instead, this method tries to +// close all browsers by calling CloseBrowser(false) via +// ClientHandler::CloseAllBrowsers. Calling CloseBrowser will result in a call +// to ClientHandler::DoClose and execution of |-performClose:| on the NSWindow. +// DoClose sets a flag that is used to differentiate between new close events +// (e.g., user clicked the window close button) and in-progress close events +// (e.g., user approved the close window dialog). The NSWindowDelegate +// |-windowShouldClose:| method checks this flag and either calls +// CloseBrowser(false) in the case of a new close event or destructs the +// NSWindow in the case of an in-progress close event. +// ClientHandler::OnBeforeClose will be called after the CEF NSView hosted in +// the NSWindow is dealloc'ed. +// +// After the final browser window has closed ClientHandler::OnBeforeClose will +// begin actual tear-down of the application by calling CefQuitMessageLoop. +// This ends the NSApplication event loop and execution then returns to the +// main() function for cleanup before application termination. +// +// The standard |-applicationShouldTerminate:| is not supported, and code paths +// leading to it must be redirected. +- (void)terminate:(id)sender { + SimpleAppDelegate* delegate = + static_cast([NSApp delegate]); + [delegate tryToTerminateApplication:self]; + // Return, don't exit. The application is responsible for exiting on its own. +} +@end + +@implementation SimpleAppDelegate + +// Create the application on the UI thread. +- (void)createApplication:(id)object { + [NSApplication sharedApplication]; + [NSBundle loadNibNamed:@"MainMenu" owner:NSApp]; + + // Set the delegate for application events. + [NSApp setDelegate:self]; +} + +- (void)tryToTerminateApplication:(NSApplication*)app { + SimpleHandler* handler = SimpleHandler::GetInstance(); + if (handler && !handler->IsClosing()) + handler->CloseAllBrowsers(false); +} + +- (NSApplicationTerminateReply)applicationShouldTerminate: + (NSApplication *)sender { + return NSTerminateNow; +} +@end + + +// Entry point function for the browser process. +int main(int argc, char* argv[]) { + // Provide CEF with command-line arguments. + CefMainArgs main_args(argc, argv); + + // SimpleApp implements application-level callbacks. It will create the first + // browser instance in OnContextInitialized() after CEF has initialized. + CefRefPtr app(new SimpleApp); + + // Initialize the AutoRelease pool. + NSAutoreleasePool* autopool = [[NSAutoreleasePool alloc] init]; + + // Initialize the SimpleApplication instance. + [SimpleApplication sharedApplication]; + + // Specify CEF global settings here. + CefSettings settings; + + // Initialize CEF for the browser process. + CefInitialize(main_args, settings, app.get(), NULL); + + // Create the application delegate. + NSObject* delegate = [[SimpleAppDelegate alloc] init]; + [delegate performSelectorOnMainThread:@selector(createApplication:) + withObject:nil + waitUntilDone:NO]; + + // Run the CEF message loop. This will block until CefQuitMessageLoop() is + // called. + CefRunMessageLoop(); + + // Shut down CEF. + CefShutdown(); + + // Release the delegate. + [delegate release]; + + // Release the AutoRelease pool. + [autopool release]; + + return 0; +} diff --git a/tests/cefsimple/cefsimple_win.cc b/tests/cefsimple/cefsimple_win.cc new file mode 100644 index 000000000..84a082a90 --- /dev/null +++ b/tests/cefsimple/cefsimple_win.cc @@ -0,0 +1,75 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +#include "cefsimple/simple_app.h" +#include "include/cef_sandbox_win.h" + + +// When generating projects with CMake the CEF_USE_SANDBOX value will be defined +// automatically if using the required compiler version. Pass -DUSE_SANDBOX=OFF +// to the CMake command-line to disable use of the sandbox. +// Uncomment this line to manually enable sandbox support. +// #define CEF_USE_SANDBOX 1 + +#if defined(CEF_USE_SANDBOX) +// The cef_sandbox.lib static library is currently built with VS2013. It may not +// link successfully with other VS versions. +#pragma comment(lib, "cef_sandbox.lib") +#endif + + +// Entry point function for all processes. +int APIENTRY wWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + + void* sandbox_info = NULL; + +#if defined(CEF_USE_SANDBOX) + // Manage the life span of the sandbox information object. This is necessary + // for sandbox support on Windows. See cef_sandbox_win.h for complete details. + CefScopedSandboxInfo scoped_sandbox; + sandbox_info = scoped_sandbox.sandbox_info(); +#endif + + // Provide CEF with command-line arguments. + CefMainArgs main_args(hInstance); + + // SimpleApp implements application-level callbacks. It will create the first + // browser instance in OnContextInitialized() after CEF has initialized. + CefRefPtr app(new SimpleApp); + + // CEF applications have multiple sub-processes (render, plugin, GPU, etc) + // that share the same executable. This function checks the command-line and, + // if this is a sub-process, executes the appropriate logic. + int exit_code = CefExecuteProcess(main_args, app.get(), sandbox_info); + if (exit_code >= 0) { + // The sub-process has completed so return here. + return exit_code; + } + + // Specify CEF global settings here. + CefSettings settings; + +#if !defined(CEF_USE_SANDBOX) + settings.no_sandbox = true; +#endif + + // Initialize CEF. + CefInitialize(main_args, settings, app.get(), sandbox_info); + + // Run the CEF message loop. This will block until CefQuitMessageLoop() is + // called. + CefRunMessageLoop(); + + // Shut down CEF. + CefShutdown(); + + return 0; +} diff --git a/tests/cefsimple/mac/English.lproj/InfoPlist.strings b/tests/cefsimple/mac/English.lproj/InfoPlist.strings new file mode 100644 index 000000000..dc5ebb069 --- /dev/null +++ b/tests/cefsimple/mac/English.lproj/InfoPlist.strings @@ -0,0 +1,3 @@ +/* Localized versions of Info.plist keys */ + +NSHumanReadableCopyright = "© Chromium Embedded Framework Authors, 2013"; diff --git a/tests/cefsimple/mac/English.lproj/MainMenu.xib b/tests/cefsimple/mac/English.lproj/MainMenu.xib new file mode 100644 index 000000000..55facd0fb --- /dev/null +++ b/tests/cefsimple/mac/English.lproj/MainMenu.xib @@ -0,0 +1,2880 @@ + + + + 1050 + 10F569 + 820 + 1038.29 + 461.00 + + com.apple.InterfaceBuilder.CocoaPlugin + 820 + + + YES + + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + + + PluginDependencyRecalculationVersion + + + + YES + + NSApplication + + + FirstResponder + + + NSApplication + + + AMainMenu + + YES + + + cefsimple + + 1048576 + 2147483647 + + NSImage + NSMenuCheckmark + + + NSImage + NSMenuMixedState + + submenuAction: + + TestShell + + YES + + + About cefsimple + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Preferences… + , + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Services + + 1048576 + 2147483647 + + + submenuAction: + + Services + + YES + + _NSServicesMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Hide cefsimple + h + 1048576 + 2147483647 + + + + + + Hide Others + h + 1572864 + 2147483647 + + + + + + Show All + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Quit cefsimple + q + 1048576 + 2147483647 + + + + + _NSAppleMenu + + + + + File + + 1048576 + 2147483647 + + + submenuAction: + + File + + YES + + + New + n + 1048576 + 2147483647 + + + + + + Open… + o + 1048576 + 2147483647 + + + + + + Open Recent + + 1048576 + 2147483647 + + + submenuAction: + + Open Recent + + YES + + + Clear Menu + + 1048576 + 2147483647 + + + + + _NSRecentDocumentsMenu + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Close + w + 1048576 + 2147483647 + + + + + + Save + s + 1048576 + 2147483647 + + + + + + Save As… + S + 1179648 + 2147483647 + + + + + + Revert to Saved + + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Page Setup... + P + 1179648 + 2147483647 + + + + + + + Print… + p + 1048576 + 2147483647 + + + + + + + + + Edit + + 1048576 + 2147483647 + + + submenuAction: + + Edit + + YES + + + Undo + z + 1048576 + 2147483647 + + + + + + Redo + Z + 1179648 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Cut + x + 1048576 + 2147483647 + + + + + + Copy + c + 1048576 + 2147483647 + + + + + + Paste + v + 1048576 + 2147483647 + + + + + + Delete + + 1048576 + 2147483647 + + + + + + Select All + a + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Find + + 1048576 + 2147483647 + + + submenuAction: + + Find + + YES + + + Find… + f + 1048576 + 2147483647 + + + 1 + + + + Find Next + g + 1048576 + 2147483647 + + + 2 + + + + Find Previous + G + 1179648 + 2147483647 + + + 3 + + + + Use Selection for Find + e + 1048576 + 2147483647 + + + 7 + + + + Jump to Selection + j + 1048576 + 2147483647 + + + + + + + + + Spelling and Grammar + + 1048576 + 2147483647 + + + submenuAction: + + Spelling and Grammar + + YES + + + Show Spelling… + : + 1048576 + 2147483647 + + + + + + Check Spelling + ; + 1048576 + 2147483647 + + + + + + Check Spelling While Typing + + 1048576 + 2147483647 + + + + + + Check Grammar With Spelling + + 1048576 + 2147483647 + + + + + + + + + Substitutions + + 1048576 + 2147483647 + + + submenuAction: + + Substitutions + + YES + + + Smart Copy/Paste + f + 1048576 + 2147483647 + + + 1 + + + + Smart Quotes + g + 1048576 + 2147483647 + + + 2 + + + + Smart Links + G + 1179648 + 2147483647 + + + 3 + + + + + + + Speech + + 1048576 + 2147483647 + + + submenuAction: + + Speech + + YES + + + Start Speaking + + 1048576 + 2147483647 + + + + + + Stop Speaking + + 1048576 + 2147483647 + + + + + + + + + + + + Format + + 1048576 + 2147483647 + + + submenuAction: + + Format + + YES + + + Show Fonts + t + 1048576 + 2147483647 + + + + + + Show Colors + C + 1179648 + 2147483647 + + + + + + + + + View + + 1048576 + 2147483647 + + + submenuAction: + + View + + YES + + + Show Toolbar + t + 1572864 + 2147483647 + + + + + + Customize Toolbar… + + 1048576 + 2147483647 + + + + + + + + + Window + + 1048576 + 2147483647 + + + submenuAction: + + Window + + YES + + + Minimize + m + 1048576 + 2147483647 + + + + + + Zoom + + 1048576 + 2147483647 + + + + + + YES + YES + + + 1048576 + 2147483647 + + + + + + Bring All to Front + + 1048576 + 2147483647 + + + + + _NSWindowsMenu + + + + + Help + + 1048576 + 2147483647 + + + submenuAction: + + Help + + YES + + + cefsimple Help + ? + 1048576 + 2147483647 + + + + + + + + _NSMainMenu + + + YES + + + + + YES + + + performMiniaturize: + + + + 37 + + + + arrangeInFront: + + + + 39 + + + + print: + + + + 86 + + + + runPageLayout: + + + + 87 + + + + clearRecentDocuments: + + + + 127 + + + + orderFrontStandardAboutPanel: + + + + 142 + + + + performClose: + + + + 193 + + + + toggleContinuousSpellChecking: + + + + 222 + + + + undo: + + + + 223 + + + + copy: + + + + 224 + + + + checkSpelling: + + + + 225 + + + + paste: + + + + 226 + + + + stopSpeaking: + + + + 227 + + + + cut: + + + + 228 + + + + showGuessPanel: + + + + 230 + + + + redo: + + + + 231 + + + + selectAll: + + + + 232 + + + + startSpeaking: + + + + 233 + + + + delete: + + + + 235 + + + + performZoom: + + + + 240 + + + + performFindPanelAction: + + + + 241 + + + + centerSelectionInVisibleArea: + + + + 245 + + + + toggleGrammarChecking: + + + + 347 + + + + toggleSmartInsertDelete: + + + + 355 + + + + toggleAutomaticQuoteSubstitution: + + + + 356 + + + + toggleAutomaticLinkDetection: + + + + 357 + + + + showHelp: + + + + 360 + + + + orderFrontColorPanel: + + + + 361 + + + + saveDocument: + + + + 362 + + + + saveDocumentAs: + + + + 363 + + + + revertDocumentToSaved: + + + + 364 + + + + runToolbarCustomizationPalette: + + + + 365 + + + + toggleToolbarShown: + + + + 366 + + + + hide: + + + + 367 + + + + hideOtherApplications: + + + + 368 + + + + terminate: + + + + 369 + + + + unhideAllApplications: + + + + 370 + + + + newDocument: + + + + 373 + + + + openDocument: + + + + 374 + + + + + YES + + 0 + + YES + + + + + + -2 + + + File's Owner + + + -1 + + + First Responder + + + -3 + + + Application + + + 29 + + + YES + + + + + + + + + + MainMenu + + + 19 + + + YES + + + + + + 56 + + + YES + + + + + + 103 + + + YES + + + + 1 + + + 217 + + + YES + + + + + + 83 + + + YES + + + + + + 81 + + + YES + + + + + + + + + + + + + + + + 75 + + + 3 + + + 80 + + + 8 + + + 78 + + + 6 + + + 72 + + + + + 82 + + + 9 + + + 124 + + + YES + + + + + + 77 + + + 5 + + + 73 + + + 1 + + + 79 + + + 7 + + + 112 + + + 10 + + + 74 + + + 2 + + + 125 + + + YES + + + + + + 126 + + + + + 205 + + + YES + + + + + + + + + + + + + + + + + + 202 + + + + + 198 + + + + + 207 + + + + + 214 + + + + + 199 + + + + + 203 + + + + + 197 + + + + + 206 + + + + + 215 + + + + + 218 + + + YES + + + + + + 216 + + + YES + + + + + + 200 + + + YES + + + + + + + + + 219 + + + + + 201 + + + + + 204 + + + + + 220 + + + YES + + + + + + + + + + 213 + + + + + 210 + + + + + 221 + + + + + 208 + + + + + 209 + + + + + 106 + + + YES + + + + 2 + + + 111 + + + + + 57 + + + YES + + + + + + + + + + + + + + + + 58 + + + + + 134 + + + + + 150 + + + + + 136 + + + 1111 + + + 144 + + + + + 129 + + + 121 + + + 143 + + + + + 236 + + + + + 131 + + + YES + + + + + + 149 + + + + + 145 + + + + + 130 + + + + + 24 + + + YES + + + + + + + + + 92 + + + + + 5 + + + + + 239 + + + + + 23 + + + + + 295 + + + YES + + + + + + 296 + + + YES + + + + + + + 297 + + + + + 298 + + + + + 299 + + + YES + + + + + + 300 + + + YES + + + + + + + 344 + + + + + 345 + + + + + 211 + + + YES + + + + + + 212 + + + YES + + + + + + + 195 + + + + + 196 + + + + + 346 + + + + + 348 + + + YES + + + + + + 349 + + + YES + + + + + + + + 350 + + + + + 351 + + + + + 354 + + + + + 389 + + + + + + + YES + + YES + -3.IBPluginDependency + 103.IBPluginDependency + 103.ImportedFromIB2 + 106.IBEditorWindowLastContentRect + 106.IBPluginDependency + 106.ImportedFromIB2 + 106.editorWindowContentRectSynchronizationRect + 111.IBPluginDependency + 111.ImportedFromIB2 + 112.IBPluginDependency + 112.ImportedFromIB2 + 124.IBPluginDependency + 124.ImportedFromIB2 + 125.IBPluginDependency + 125.ImportedFromIB2 + 125.editorWindowContentRectSynchronizationRect + 126.IBPluginDependency + 126.ImportedFromIB2 + 129.IBPluginDependency + 129.ImportedFromIB2 + 130.IBPluginDependency + 130.ImportedFromIB2 + 130.editorWindowContentRectSynchronizationRect + 131.IBPluginDependency + 131.ImportedFromIB2 + 134.IBPluginDependency + 134.ImportedFromIB2 + 136.IBPluginDependency + 136.ImportedFromIB2 + 143.IBPluginDependency + 143.ImportedFromIB2 + 144.IBPluginDependency + 144.ImportedFromIB2 + 145.IBPluginDependency + 145.ImportedFromIB2 + 149.IBPluginDependency + 149.ImportedFromIB2 + 150.IBPluginDependency + 150.ImportedFromIB2 + 19.IBPluginDependency + 19.ImportedFromIB2 + 195.IBPluginDependency + 195.ImportedFromIB2 + 196.IBPluginDependency + 196.ImportedFromIB2 + 197.IBPluginDependency + 197.ImportedFromIB2 + 198.IBPluginDependency + 198.ImportedFromIB2 + 199.IBPluginDependency + 199.ImportedFromIB2 + 200.IBEditorWindowLastContentRect + 200.IBPluginDependency + 200.ImportedFromIB2 + 200.editorWindowContentRectSynchronizationRect + 201.IBPluginDependency + 201.ImportedFromIB2 + 202.IBPluginDependency + 202.ImportedFromIB2 + 203.IBPluginDependency + 203.ImportedFromIB2 + 204.IBPluginDependency + 204.ImportedFromIB2 + 205.IBEditorWindowLastContentRect + 205.IBPluginDependency + 205.ImportedFromIB2 + 205.editorWindowContentRectSynchronizationRect + 206.IBPluginDependency + 206.ImportedFromIB2 + 207.IBPluginDependency + 207.ImportedFromIB2 + 208.IBPluginDependency + 208.ImportedFromIB2 + 209.IBPluginDependency + 209.ImportedFromIB2 + 210.IBPluginDependency + 210.ImportedFromIB2 + 211.IBPluginDependency + 211.ImportedFromIB2 + 212.IBEditorWindowLastContentRect + 212.IBPluginDependency + 212.ImportedFromIB2 + 212.editorWindowContentRectSynchronizationRect + 213.IBPluginDependency + 213.ImportedFromIB2 + 214.IBPluginDependency + 214.ImportedFromIB2 + 215.IBPluginDependency + 215.ImportedFromIB2 + 216.IBPluginDependency + 216.ImportedFromIB2 + 217.IBPluginDependency + 217.ImportedFromIB2 + 218.IBPluginDependency + 218.ImportedFromIB2 + 219.IBPluginDependency + 219.ImportedFromIB2 + 220.IBEditorWindowLastContentRect + 220.IBPluginDependency + 220.ImportedFromIB2 + 220.editorWindowContentRectSynchronizationRect + 221.IBPluginDependency + 221.ImportedFromIB2 + 23.IBPluginDependency + 23.ImportedFromIB2 + 236.IBPluginDependency + 236.ImportedFromIB2 + 239.IBPluginDependency + 239.ImportedFromIB2 + 24.IBEditorWindowLastContentRect + 24.IBPluginDependency + 24.ImportedFromIB2 + 24.editorWindowContentRectSynchronizationRect + 29.IBEditorWindowLastContentRect + 29.IBPluginDependency + 29.ImportedFromIB2 + 29.WindowOrigin + 29.editorWindowContentRectSynchronizationRect + 295.IBPluginDependency + 296.IBEditorWindowLastContentRect + 296.IBPluginDependency + 296.editorWindowContentRectSynchronizationRect + 297.IBPluginDependency + 298.IBPluginDependency + 299.IBPluginDependency + 300.IBEditorWindowLastContentRect + 300.IBPluginDependency + 300.editorWindowContentRectSynchronizationRect + 344.IBPluginDependency + 345.IBPluginDependency + 346.IBPluginDependency + 346.ImportedFromIB2 + 348.IBPluginDependency + 348.ImportedFromIB2 + 349.IBEditorWindowLastContentRect + 349.IBPluginDependency + 349.ImportedFromIB2 + 349.editorWindowContentRectSynchronizationRect + 350.IBPluginDependency + 350.ImportedFromIB2 + 351.IBPluginDependency + 351.ImportedFromIB2 + 354.IBPluginDependency + 354.ImportedFromIB2 + 389.IBPluginDependency + 5.IBPluginDependency + 5.ImportedFromIB2 + 56.IBPluginDependency + 56.ImportedFromIB2 + 57.IBEditorWindowLastContentRect + 57.IBPluginDependency + 57.ImportedFromIB2 + 57.editorWindowContentRectSynchronizationRect + 58.IBPluginDependency + 58.ImportedFromIB2 + 72.IBPluginDependency + 72.ImportedFromIB2 + 73.IBPluginDependency + 73.ImportedFromIB2 + 74.IBPluginDependency + 74.ImportedFromIB2 + 75.IBPluginDependency + 75.ImportedFromIB2 + 77.IBPluginDependency + 77.ImportedFromIB2 + 78.IBPluginDependency + 78.ImportedFromIB2 + 79.IBPluginDependency + 79.ImportedFromIB2 + 80.IBPluginDependency + 80.ImportedFromIB2 + 81.IBEditorWindowLastContentRect + 81.IBPluginDependency + 81.ImportedFromIB2 + 81.editorWindowContentRectSynchronizationRect + 82.IBPluginDependency + 82.ImportedFromIB2 + 83.IBPluginDependency + 83.ImportedFromIB2 + 92.IBPluginDependency + 92.ImportedFromIB2 + + + YES + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + {{906, 713}, {164, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{375, 955}, {171, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{522, 812}, {146, 23}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{436, 809}, {64, 6}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {272, 83}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {275, 83}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{675, 493}, {240, 243}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{144, 735}, {243, 243}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {164, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {167, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {238, 103}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {241, 103}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{835, 663}, {194, 73}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{304, 905}, {197, 73}} + {{541, 736}, {426, 20}} + com.apple.InterfaceBuilder.CocoaPlugin + + {74, 862} + {{6, 836}, {430, 20}} + com.apple.InterfaceBuilder.CocoaPlugin + {{785, 693}, {231, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + {{254, 935}, {234, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + {{719, 693}, {173, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + {{188, 935}, {176, 43}} + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{915, 473}, {212, 63}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{608, 612}, {215, 63}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{553, 553}, {193, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{18, 653}, {200, 183}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + {{633, 533}, {196, 203}} + com.apple.InterfaceBuilder.CocoaPlugin + + {{102, 775}, {199, 203}} + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + com.apple.InterfaceBuilder.CocoaPlugin + + + + + YES + + + YES + + + + + YES + + + YES + + + + 439 + + + + YES + + NSApplication + NSResponder + + IBFrameworkSource + AppKit.framework/Headers/NSApplication.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSApplicationScripting.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSColorPanel.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSHelpManager.h + + + + NSApplication + + IBFrameworkSource + AppKit.framework/Headers/NSPageLayout.h + + + + NSBrowser + NSControl + + IBFrameworkSource + AppKit.framework/Headers/NSBrowser.h + + + + NSControl + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSControl.h + + + + NSController + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSController.h + + + + NSDocument + NSObject + + YES + + YES + printDocument: + revertDocumentToSaved: + runPageLayout: + saveDocument: + saveDocumentAs: + saveDocumentTo: + + + YES + id + id + id + id + id + id + + + + YES + + YES + printDocument: + revertDocumentToSaved: + runPageLayout: + saveDocument: + saveDocumentAs: + saveDocumentTo: + + + YES + + printDocument: + id + + + revertDocumentToSaved: + id + + + runPageLayout: + id + + + saveDocument: + id + + + saveDocumentAs: + id + + + saveDocumentTo: + id + + + + + IBFrameworkSource + AppKit.framework/Headers/NSDocument.h + + + + NSDocument + + IBFrameworkSource + AppKit.framework/Headers/NSDocumentScripting.h + + + + NSDocumentController + NSObject + + YES + + YES + clearRecentDocuments: + newDocument: + openDocument: + saveAllDocuments: + + + YES + id + id + id + id + + + + YES + + YES + clearRecentDocuments: + newDocument: + openDocument: + saveAllDocuments: + + + YES + + clearRecentDocuments: + id + + + newDocument: + id + + + openDocument: + id + + + saveAllDocuments: + id + + + + + IBFrameworkSource + AppKit.framework/Headers/NSDocumentController.h + + + + NSFormatter + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSFormatter.h + + + + NSMatrix + NSControl + + IBFrameworkSource + AppKit.framework/Headers/NSMatrix.h + + + + NSMenu + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSMenu.h + + + + NSMenuItem + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSMenuItem.h + + + + NSMovieView + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSMovieView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSAccessibility.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSAlert.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSAnimation.h + + + + NSObject + + + + NSObject + + + + NSObject + + + + NSObject + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSComboBox.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSComboBoxCell.h + + + + NSObject + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDatePickerCell.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDictionaryController.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDragging.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSDrawer.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSFontManager.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSFontPanel.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSImage.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSKeyValueBinding.h + + + + NSObject + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSNibLoading.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSOutlineView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSPasteboard.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSRuleEditor.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSavePanel.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSound.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSpeechRecognizer.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSpeechSynthesizer.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSSplitView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTabView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTableView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSText.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTextStorage.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTextView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTokenField.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSTokenFieldCell.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSToolbar.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSToolbarItem.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSView.h + + + + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSWindow.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSArchiver.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSClassDescription.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSConnection.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSError.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSFileManager.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSKeyValueCoding.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSKeyValueObserving.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSKeyedArchiver.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSMetadata.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSNetServices.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSObject.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSObjectScripting.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSPort.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSPortCoder.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSRunLoop.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptClassDescription.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptKeyValueCoding.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptObjectSpecifiers.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSScriptWhoseTests.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSSpellServer.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSStream.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSThread.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSURL.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSURLConnection.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSURLDownload.h + + + + NSObject + + IBFrameworkSource + Foundation.framework/Headers/NSXMLParser.h + + + + NSObject + + IBFrameworkSource + Print.framework/Headers/PDEPluginInterface.h + + + + NSObject + + IBFrameworkSource + QuartzCore.framework/Headers/CAAnimation.h + + + + NSObject + + IBFrameworkSource + QuartzCore.framework/Headers/CALayer.h + + + + NSObject + + IBFrameworkSource + QuartzCore.framework/Headers/CIImageProvider.h + + + + NSResponder + + IBFrameworkSource + AppKit.framework/Headers/NSInterfaceStyle.h + + + + NSResponder + NSObject + + IBFrameworkSource + AppKit.framework/Headers/NSResponder.h + + + + NSTableView + NSControl + + + + NSText + NSView + + + + NSUserDefaultsController + NSController + + IBFrameworkSource + AppKit.framework/Headers/NSUserDefaultsController.h + + + + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSClipView.h + + + + NSView + + + + NSView + + IBFrameworkSource + AppKit.framework/Headers/NSRulerView.h + + + + NSView + NSResponder + + + + NSWindow + + + + NSWindow + NSResponder + + + + NSWindow + + IBFrameworkSource + AppKit.framework/Headers/NSWindowScripting.h + + + + + 0 + IBCocoaFramework + + com.apple.InterfaceBuilder.CocoaPlugin.macosx + + + + com.apple.InterfaceBuilder.CocoaPlugin.macosx + + + + com.apple.InterfaceBuilder.CocoaPlugin.InterfaceBuilder3 + + + YES + ../../../../cef.xcodeproj + 3 + + YES + + YES + NSMenuCheckmark + NSMenuMixedState + + + YES + {9, 8} + {7, 2} + + + + diff --git a/tests/cefsimple/mac/Info.plist b/tests/cefsimple/mac/Info.plist new file mode 100644 index 000000000..0ef32d6dc --- /dev/null +++ b/tests/cefsimple/mac/Info.plist @@ -0,0 +1,30 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFile + cefsimple.icns + CFBundleIdentifier + org.cef.cefsimple + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + NSSupportsAutomaticGraphicsSwitching + + + diff --git a/tests/cefsimple/mac/cefsimple.icns b/tests/cefsimple/mac/cefsimple.icns new file mode 100644 index 000000000..f36742de2 Binary files /dev/null and b/tests/cefsimple/mac/cefsimple.icns differ diff --git a/tests/cefsimple/mac/helper-Info.plist b/tests/cefsimple/mac/helper-Info.plist new file mode 100644 index 000000000..32763b065 --- /dev/null +++ b/tests/cefsimple/mac/helper-Info.plist @@ -0,0 +1,30 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + ${EXECUTABLE_NAME} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + org.cef.cefsimple.helper + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + LSFileQuarantineEnabled + + LSMinimumSystemVersion + 10.5.0 + LSUIElement + 1 + NSSupportsAutomaticGraphicsSwitching + + + diff --git a/tests/cefsimple/process_helper_mac.cc b/tests/cefsimple/process_helper_mac.cc new file mode 100644 index 000000000..2ebbc2ddb --- /dev/null +++ b/tests/cefsimple/process_helper_mac.cc @@ -0,0 +1,14 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that can +// be found in the LICENSE file. + +#include "include/cef_app.h" + +// Entry point function for sub-processes. +int main(int argc, char* argv[]) { + // Provide CEF with command-line arguments. + CefMainArgs main_args(argc, argv); + + // Execute the sub-process. + return CefExecuteProcess(main_args, NULL, NULL); +} diff --git a/tests/cefsimple/res/cefsimple.ico b/tests/cefsimple/res/cefsimple.ico new file mode 100644 index 000000000..d551aa3aa Binary files /dev/null and b/tests/cefsimple/res/cefsimple.ico differ diff --git a/tests/cefsimple/res/small.ico b/tests/cefsimple/res/small.ico new file mode 100644 index 000000000..d551aa3aa Binary files /dev/null and b/tests/cefsimple/res/small.ico differ diff --git a/tests/cefsimple/resource.h b/tests/cefsimple/resource.h new file mode 100644 index 000000000..19093ded4 --- /dev/null +++ b/tests/cefsimple/resource.h @@ -0,0 +1,26 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by cefsimple.rc +// + +#define IDI_CEFSIMPLE 100 +#define IDI_SMALL 101 + +// Avoid files associated with MacOS +#define _X86_ + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 32700 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 102 +#endif +#endif diff --git a/tests/cefsimple/simple_app.cc b/tests/cefsimple/simple_app.cc new file mode 100644 index 000000000..f09ee8ab7 --- /dev/null +++ b/tests/cefsimple/simple_app.cc @@ -0,0 +1,48 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefsimple/simple_app.h" + +#include + +#include "cefsimple/simple_handler.h" +#include "include/cef_browser.h" +#include "include/cef_command_line.h" +#include "include/wrapper/cef_helpers.h" + +SimpleApp::SimpleApp() { +} + +void SimpleApp::OnContextInitialized() { + CEF_REQUIRE_UI_THREAD(); + + // Information used when creating the native window. + CefWindowInfo window_info; + +#if defined(OS_WIN) + // On Windows we need to specify certain flags that will be passed to + // CreateWindowEx(). + window_info.SetAsPopup(NULL, "cefsimple"); +#endif + + // SimpleHandler implements browser-level callbacks. + CefRefPtr handler(new SimpleHandler()); + + // Specify CEF browser settings here. + CefBrowserSettings browser_settings; + + std::string url; + + // Check if a "--url=" value was provided via the command-line. If so, use + // that instead of the default URL. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + url = command_line->GetSwitchValue("url"); + if (url.empty()) + url = "http://www.google.com"; + + // Create the first browser window. + CefBrowserHost::CreateBrowser(window_info, handler.get(), url, + browser_settings, NULL); +} diff --git a/tests/cefsimple/simple_app.h b/tests/cefsimple/simple_app.h new file mode 100644 index 000000000..1e454a428 --- /dev/null +++ b/tests/cefsimple/simple_app.h @@ -0,0 +1,27 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFSIMPLE_SIMPLE_APP_H_ +#define CEF_TESTS_CEFSIMPLE_SIMPLE_APP_H_ + +#include "include/cef_app.h" + +class SimpleApp : public CefApp, + public CefBrowserProcessHandler { + public: + SimpleApp(); + + // CefApp methods: + virtual CefRefPtr GetBrowserProcessHandler() + OVERRIDE { return this; } + + // CefBrowserProcessHandler methods: + virtual void OnContextInitialized() OVERRIDE; + + private: + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(SimpleApp); +}; + +#endif // CEF_TESTS_CEFSIMPLE_SIMPLE_APP_H_ diff --git a/tests/cefsimple/simple_handler.cc b/tests/cefsimple/simple_handler.cc new file mode 100644 index 000000000..0d71f0e20 --- /dev/null +++ b/tests/cefsimple/simple_handler.cc @@ -0,0 +1,111 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefsimple/simple_handler.h" + +#include +#include + +#include "include/base/cef_bind.h" +#include "include/cef_app.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_helpers.h" + +namespace { + +SimpleHandler* g_instance = NULL; + +} // namespace + +SimpleHandler::SimpleHandler() + : is_closing_(false) { + DCHECK(!g_instance); + g_instance = this; +} + +SimpleHandler::~SimpleHandler() { + g_instance = NULL; +} + +// static +SimpleHandler* SimpleHandler::GetInstance() { + return g_instance; +} + +void SimpleHandler::OnAfterCreated(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + // Add to the list of existing browsers. + browser_list_.push_back(browser); +} + +bool SimpleHandler::DoClose(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + // Closing the main window requires special handling. See the DoClose() + // documentation in the CEF header for a detailed destription of this + // process. + if (browser_list_.size() == 1) { + // Set a flag to indicate that the window close should be allowed. + is_closing_ = true; + } + + // Allow the close. For windowed browsers this will result in the OS close + // event being sent. + return false; +} + +void SimpleHandler::OnBeforeClose(CefRefPtr browser) { + CEF_REQUIRE_UI_THREAD(); + + // Remove from the list of existing browsers. + BrowserList::iterator bit = browser_list_.begin(); + for (; bit != browser_list_.end(); ++bit) { + if ((*bit)->IsSame(browser)) { + browser_list_.erase(bit); + break; + } + } + + if (browser_list_.empty()) { + // All browser windows have closed. Quit the application message loop. + CefQuitMessageLoop(); + } +} + +void SimpleHandler::OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) { + CEF_REQUIRE_UI_THREAD(); + + // Don't display an error for downloaded files. + if (errorCode == ERR_ABORTED) + return; + + // Display a load error message. + std::stringstream ss; + ss << "" + "

Failed to load URL " << std::string(failedUrl) << + " with error " << std::string(errorText) << " (" << errorCode << + ").

"; + frame->LoadString(ss.str(), failedUrl); +} + +void SimpleHandler::CloseAllBrowsers(bool force_close) { + if (!CefCurrentlyOn(TID_UI)) { + // Execute on the UI thread. + CefPostTask(TID_UI, + base::Bind(&SimpleHandler::CloseAllBrowsers, this, force_close)); + return; + } + + if (browser_list_.empty()) + return; + + BrowserList::const_iterator it = browser_list_.begin(); + for (; it != browser_list_.end(); ++it) + (*it)->GetHost()->CloseBrowser(force_close); +} diff --git a/tests/cefsimple/simple_handler.h b/tests/cefsimple/simple_handler.h new file mode 100644 index 000000000..1f272ff1f --- /dev/null +++ b/tests/cefsimple/simple_handler.h @@ -0,0 +1,66 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_ +#define CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_ + +#include "include/cef_client.h" + +#include + +class SimpleHandler : public CefClient, + public CefDisplayHandler, + public CefLifeSpanHandler, + public CefLoadHandler { + public: + SimpleHandler(); + ~SimpleHandler(); + + // Provide access to the single global instance of this object. + static SimpleHandler* GetInstance(); + + // CefClient methods: + virtual CefRefPtr GetDisplayHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetLifeSpanHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetLoadHandler() OVERRIDE { + return this; + } + + // CefDisplayHandler methods: + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) OVERRIDE; + + // CefLifeSpanHandler methods: + virtual void OnAfterCreated(CefRefPtr browser) OVERRIDE; + virtual bool DoClose(CefRefPtr browser) OVERRIDE; + virtual void OnBeforeClose(CefRefPtr browser) OVERRIDE; + + // CefLoadHandler methods: + virtual void OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) OVERRIDE; + + // Request that all existing browser windows close. + void CloseAllBrowsers(bool force_close); + + bool IsClosing() const { return is_closing_; } + + private: + // List of existing browser windows. Only accessed on the CEF UI thread. + typedef std::list > BrowserList; + BrowserList browser_list_; + + bool is_closing_; + + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(SimpleHandler); +}; + +#endif // CEF_TESTS_CEFSIMPLE_SIMPLE_HANDLER_H_ diff --git a/tests/cefsimple/simple_handler_linux.cc b/tests/cefsimple/simple_handler_linux.cc new file mode 100644 index 000000000..907d63863 --- /dev/null +++ b/tests/cefsimple/simple_handler_linux.cc @@ -0,0 +1,54 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefsimple/simple_handler.h" + +#include +#include +#include + +#include "include/cef_browser.h" +#include "include/wrapper/cef_helpers.h" + +void SimpleHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + CEF_REQUIRE_UI_THREAD(); + std::string titleStr(title); + + // Retrieve the X11 display shared with Chromium. + ::Display* display = cef_get_xdisplay(); + DCHECK(display); + + // Retrieve the X11 window handle for the browser. + ::Window window = browser->GetHost()->GetWindowHandle(); + DCHECK(window != kNullWindowHandle); + + // Retrieve the atoms required by the below XChangeProperty call. + const char* kAtoms[] = { + "_NET_WM_NAME", + "UTF8_STRING" + }; + Atom atoms[2]; + int result = XInternAtoms(display, const_cast(kAtoms), 2, false, + atoms); + if (!result) + NOTREACHED(); + + // Set the window title. + XChangeProperty(display, + window, + atoms[0], + atoms[1], + 8, + PropModeReplace, + reinterpret_cast(titleStr.c_str()), + titleStr.size()); + + // TODO(erg): This is technically wrong. So XStoreName and friends expect + // this in Host Portable Character Encoding instead of UTF-8, which I believe + // is Compound Text. This shouldn't matter 90% of the time since this is the + // fallback to the UTF8 property above. + XStoreName(display, browser->GetHost()->GetWindowHandle(), titleStr.c_str()); +} + diff --git a/tests/cefsimple/simple_handler_mac.mm b/tests/cefsimple/simple_handler_mac.mm new file mode 100644 index 000000000..696959a5c --- /dev/null +++ b/tests/cefsimple/simple_handler_mac.mm @@ -0,0 +1,21 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefsimple/simple_handler.h" + +#import + +#include "include/cef_browser.h" +#include "include/wrapper/cef_helpers.h" + +void SimpleHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + CEF_REQUIRE_UI_THREAD(); + + NSView* view = (NSView*)browser->GetHost()->GetWindowHandle(); + NSWindow* window = [view window]; + std::string titleStr(title); + NSString* str = [NSString stringWithUTF8String:titleStr.c_str()]; + [window setTitle:str]; +} diff --git a/tests/cefsimple/simple_handler_win.cc b/tests/cefsimple/simple_handler_win.cc new file mode 100644 index 000000000..32fc1c008 --- /dev/null +++ b/tests/cefsimple/simple_handler_win.cc @@ -0,0 +1,19 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "cefsimple/simple_handler.h" + +#include +#include + +#include "include/cef_browser.h" +#include "include/wrapper/cef_helpers.h" + +void SimpleHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + CEF_REQUIRE_UI_THREAD(); + + CefWindowHandle hwnd = browser->GetHost()->GetWindowHandle(); + SetWindowText(hwnd, std::wstring(title).c_str()); +} diff --git a/tests/unittests/browser_info_map_unittest.cc b/tests/unittests/browser_info_map_unittest.cc new file mode 100644 index 000000000..cede17bec --- /dev/null +++ b/tests/unittests/browser_info_map_unittest.cc @@ -0,0 +1,722 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "libcef_dll/wrapper/cef_browser_info_map.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +struct MyObject { + MyObject(int val = 0) : member(val) {} + int member; +}; + +int g_destruct_ct = 0; + +struct MyObjectTraits { + static void Destruct(MyObject info) { + g_destruct_ct++; + } +}; + +typedef CefBrowserInfoMap MyObjectMap; + +class MyVisitor : public MyObjectMap::Visitor { + public: + MyVisitor(bool remove = false, + int remove_browser_id = 0, + InfoIdType remove_info_id = 0) + : remove_(remove), + remove_browser_id_(remove_browser_id), + remove_info_id_(remove_info_id) {} + + bool OnNextInfo(int browser_id, + InfoIdType info_id, + InfoObjectType info, + bool* remove) override { + Info info_rec; + info_rec.browser_id = browser_id; + info_rec.info_id = info_id; + info_rec.info = info; + info_list_.push_back(info_rec); + + // Based on test configuration remove no objects, all objects, or only the + // specified object. + *remove = remove_ || (browser_id == remove_browser_id_ && + info_id == remove_info_id_); + return true; + } + + // Returns true if the specified info was passed to OnNextInfo. Removes the + // record if found. + bool Exists(int browser_id, + InfoIdType info_id, + InfoObjectType info) { + InfoList::iterator it = info_list_.begin(); + for (; it != info_list_.end(); ++it) { + const Info& found_info = *it; + if (browser_id == found_info.browser_id && + info_id == found_info.info_id && + info.member == found_info.info.member) { + info_list_.erase(it); + return true; + } + } + return false; + } + + size_t info_size() const { return info_list_.size(); } + + private: + bool remove_; + int remove_browser_id_; + InfoIdType remove_info_id_; + + struct Info { + int browser_id; + InfoIdType info_id; + InfoObjectType info; + }; + + // Track calls to OnNextInfo. + typedef std::list InfoList; + InfoList info_list_; +}; + +} // namespace + +TEST(BrowserInfoMapTest, AddSingleBrowser) { + MyObjectMap map; + const int kBrowserId = 1; + + g_destruct_ct = 0; + + EXPECT_EQ(0U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId)); + + MyObject obj1(1); + map.Add(kBrowserId, 1, obj1); + EXPECT_EQ(1U, map.size()); + EXPECT_EQ(1U, map.size(kBrowserId)); + + MyObject obj2(2); + map.Add(kBrowserId, 2, obj2); + EXPECT_EQ(2U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId)); + + MyObject obj3(3); + map.Add(kBrowserId, 3, obj3); + EXPECT_EQ(3U, map.size()); + EXPECT_EQ(3U, map.size(kBrowserId)); + + EXPECT_EQ(0, g_destruct_ct); + + map.clear(kBrowserId); + EXPECT_EQ(0U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId)); + + EXPECT_EQ(3, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, AddMultipleBrowsers) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + EXPECT_EQ(0U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId1)); + EXPECT_EQ(0U, map.size(kBrowserId2)); + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + EXPECT_EQ(1U, map.size()); + EXPECT_EQ(1U, map.size(kBrowserId1)); + EXPECT_EQ(0U, map.size(kBrowserId2)); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + EXPECT_EQ(2U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(0U, map.size(kBrowserId2)); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + EXPECT_EQ(3U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(1U, map.size(kBrowserId2)); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + EXPECT_EQ(0, g_destruct_ct); + + map.clear(kBrowserId1); + EXPECT_EQ(2U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + EXPECT_EQ(2, g_destruct_ct); + + map.clear(kBrowserId2); + EXPECT_EQ(0U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId1)); + EXPECT_EQ(0U, map.size(kBrowserId2)); + + EXPECT_EQ(4, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindSingleBrowser) { + MyObjectMap map; + const int kBrowserId = 1; + + g_destruct_ct = 0; + + // obj1 not added yet. + MyObject nf1 = map.Find(kBrowserId, 1, NULL); + EXPECT_EQ(0, nf1.member); + + MyObject obj1(1); + map.Add(kBrowserId, 1, obj1); + + // obj1 should exist. + MyObject f1 = map.Find(kBrowserId, 1, NULL); + EXPECT_EQ(obj1.member, f1.member); + + // obj2 not added yet. + MyObject nf2 = map.Find(kBrowserId, 2, NULL); + EXPECT_EQ(0, nf2.member); + + MyObject obj2(2); + map.Add(kBrowserId, 2, obj2); + + // obj2 should exist. + MyObject f2 = map.Find(kBrowserId, 2, NULL); + EXPECT_EQ(obj2.member, f2.member); + + // find obj1 again. + MyObject f1b = map.Find(kBrowserId, 1, NULL); + EXPECT_EQ(obj1.member, f1b.member); + + // find obj2 again. + MyObject f2b = map.Find(kBrowserId, 2, NULL); + EXPECT_EQ(obj2.member, f2b.member); + + // doesn't exist. + MyObject nf3 = map.Find(kBrowserId, 3, NULL); + EXPECT_EQ(0, nf3.member); + MyObject nf4 = map.Find(10, 1, NULL); + EXPECT_EQ(0, nf4.member); + MyObject nf5 = map.Find(10, 3, NULL); + EXPECT_EQ(0, nf5.member); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + EXPECT_EQ(2, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindMultipleBrowsers) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + // obj1 not added yet. + MyObject nf1 = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(0, nf1.member); + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + // obj1 should exist. + MyObject f1 = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(obj1.member, f1.member); + + // obj2 not added yet. + MyObject nf2 = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(0, nf2.member); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + // obj2 should exist. + MyObject f2 = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(obj2.member, f2.member); + + // obj3 not added yet. + MyObject nf3 = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(0, nf3.member); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + // obj3 should exist. + MyObject f3 = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(obj3.member, f3.member); + + // obj4 not added yet. + MyObject nf4 = map.Find(kBrowserId2, 4, NULL); + EXPECT_EQ(0, nf4.member); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + // obj4 should exist. + MyObject f4 = map.Find(kBrowserId2, 4, NULL); + EXPECT_EQ(obj4.member, f4.member); + + // obj1-3 should exist. + MyObject f1b = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(obj1.member, f1b.member); + MyObject f2b = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(obj2.member, f2b.member); + MyObject f3b = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(obj3.member, f3b.member); + + // wrong browser + MyObject nf5 = map.Find(kBrowserId1, 4, NULL); + EXPECT_EQ(0, nf5.member); + MyObject nf6 = map.Find(kBrowserId2, 1, NULL); + EXPECT_EQ(0, nf6.member); + + // deosn't exist + MyObject nf7 = map.Find(kBrowserId2, 5, NULL); + EXPECT_EQ(0, nf7.member); + MyObject nf8 = map.Find(8, 1, NULL); + EXPECT_EQ(0, nf8.member); + MyObject nf9 = map.Find(8, 10, NULL); + EXPECT_EQ(0, nf9.member); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + EXPECT_EQ(4, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, Find) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should only visit the single object + MyVisitor visitor; + map.Find(kBrowserId2, 4, &visitor); + EXPECT_EQ(1U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 4, obj4)); + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + EXPECT_EQ(4, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAndRemove) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should only visit and remove the single object. + MyVisitor visitor(true); + map.Find(kBrowserId1, 2, &visitor); + EXPECT_EQ(1U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 2, obj2)); + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(3U, map.size()); + EXPECT_EQ(1U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // visited object shouldn't exist + MyObject nf2 = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(0, nf2.member); + + // other objects should exist + MyObject nf1 = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(obj1.member, nf1.member); + MyObject nf3 = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(obj3.member, nf3.member); + MyObject nf4 = map.Find(kBrowserId2, 4, NULL); + EXPECT_EQ(obj4.member, nf4.member); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + // should destruct the remaining 3 objects + EXPECT_EQ(3, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAll) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should visit all objects + MyVisitor visitor; + map.FindAll(&visitor); + EXPECT_EQ(4U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 1, obj1)); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 2, obj2)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 3, obj3)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 4, obj4)); + // should be no unexpected visits + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + EXPECT_EQ(4, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAllByBrowser) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should only visit browser2 objects + MyVisitor visitor; + map.FindAll(kBrowserId2, &visitor); + EXPECT_EQ(2U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 3, obj3)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 4, obj4)); + // should be no unexpected visits + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + EXPECT_EQ(4, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAllAndRemoveAll) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should visit all objects + MyVisitor visitor(true); + map.FindAll(&visitor); + EXPECT_EQ(4U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 1, obj1)); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 2, obj2)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 3, obj3)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 4, obj4)); + // should be no unexpected visits + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(0U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId1)); + EXPECT_EQ(0U, map.size(kBrowserId2)); + + EXPECT_EQ(0, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAllAndRemoveOne) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should visit all objects and remove one + MyVisitor visitor(false, kBrowserId2, 3); + map.FindAll(&visitor); + EXPECT_EQ(4U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 1, obj1)); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 2, obj2)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 3, obj3)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 4, obj4)); + // should be no unexpected visits + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(3U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(1U, map.size(kBrowserId2)); + + // removed object shouldn't exist + MyObject nf3 = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(0, nf3.member); + + // other objects should exist + MyObject f1 = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(obj1.member, f1.member); + MyObject f2 = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(obj2.member, f2.member); + MyObject f4 = map.Find(kBrowserId2, 4, NULL); + EXPECT_EQ(obj4.member, f4.member); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + // should destruct the remaining 3 objects + EXPECT_EQ(3, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAllAndRemoveAllByBrowser) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should only visit browser1 objects + MyVisitor visitor(true); + map.FindAll(kBrowserId1, &visitor); + EXPECT_EQ(2U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 1, obj1)); + EXPECT_TRUE(visitor.Exists(kBrowserId1, 2, obj2)); + // should be no unexpected visits + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(2U, map.size()); + EXPECT_EQ(0U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // browser1 objects shouldn't exist + MyObject nf1 = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(0, nf1.member); + MyObject nf2 = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(0, nf2.member); + + // browser 2 objects should exist + MyObject f3 = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(obj3.member, f3.member); + MyObject f4 = map.Find(kBrowserId2, 4, NULL); + EXPECT_EQ(obj4.member, f4.member); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + // should destruct the remaining 2 objects + EXPECT_EQ(2, g_destruct_ct); +} + +TEST(BrowserInfoMapTest, FindAllAndRemoveOneByBrowser) { + MyObjectMap map; + const int kBrowserId1 = 1; + const int kBrowserId2 = 2; + + g_destruct_ct = 0; + + MyObject obj1(1); + map.Add(kBrowserId1, 1, obj1); + + MyObject obj2(2); + map.Add(kBrowserId1, 2, obj2); + + MyObject obj3(3); + map.Add(kBrowserId2, 3, obj3); + + MyObject obj4(4); + map.Add(kBrowserId2, 4, obj4); + + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(2U, map.size(kBrowserId2)); + + // should visit browser2 objects and remove one + MyVisitor visitor(false, kBrowserId2, 4); + map.FindAll(kBrowserId2, &visitor); + EXPECT_EQ(2U, visitor.info_size()); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 3, obj3)); + EXPECT_TRUE(visitor.Exists(kBrowserId2, 4, obj4)); + // should be no unexpected visits + EXPECT_EQ(0U, visitor.info_size()); + + EXPECT_EQ(3U, map.size()); + EXPECT_EQ(2U, map.size(kBrowserId1)); + EXPECT_EQ(1U, map.size(kBrowserId2)); + + // removed object shouldn't exist + MyObject nf4 = map.Find(kBrowserId2, 4, NULL); + EXPECT_EQ(0, nf4.member); + + // other objects should exist + MyObject f1 = map.Find(kBrowserId1, 1, NULL); + EXPECT_EQ(obj1.member, f1.member); + MyObject f2 = map.Find(kBrowserId1, 2, NULL); + EXPECT_EQ(obj2.member, f2.member); + MyObject f3 = map.Find(kBrowserId2, 3, NULL); + EXPECT_EQ(obj3.member, f3.member); + + EXPECT_EQ(0, g_destruct_ct); + map.clear(); + // should destruct the remaining 3 objects + EXPECT_EQ(3, g_destruct_ct); +} + + +namespace { + +class MyHeapObject { + public: + MyHeapObject(int* destroy_ct) : destroy_ct_(destroy_ct) {} + ~MyHeapObject() { + (*destroy_ct_)++; + } + + private: + int* destroy_ct_; +}; + +} // namespace + +TEST(BrowserInfoMapTest, DefaultTraits) { + CefBrowserInfoMap map; + + int destroy_ct = 0; + map.Add(1, 1, new MyHeapObject(&destroy_ct)); + map.Add(1, 2, new MyHeapObject(&destroy_ct)); + map.Add(2, 1, new MyHeapObject(&destroy_ct)); + map.Add(2, 2, new MyHeapObject(&destroy_ct)); + map.Add(3, 1, new MyHeapObject(&destroy_ct)); + map.Add(3, 2, new MyHeapObject(&destroy_ct)); + + EXPECT_EQ(6U, map.size()); + + map.clear(1); + EXPECT_EQ(4U, map.size()); + EXPECT_EQ(2, destroy_ct); + + map.clear(); + EXPECT_EQ(0U, map.size()); + EXPECT_EQ(6, destroy_ct); +} diff --git a/tests/unittests/chromium_includes.h b/tests/unittests/chromium_includes.h new file mode 100644 index 000000000..0611738a9 --- /dev/null +++ b/tests/unittests/chromium_includes.h @@ -0,0 +1,14 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_UNITTESTS_CHROMIUM_INCLUDES_H_ +#define CEF_TESTS_UNITTESTS_CHROMIUM_INCLUDES_H_ +#pragma once + +// Include some Chromium headers first to avoid type conflicts with CEF headers. +#include "base/bind.h" +#include "base/strings/string16.h" +#include "base/synchronization/lock.h" + +#endif // CEF_TESTS_UNITTESTS_CHROMIUM_INCLUDES_H_ diff --git a/tests/unittests/client_app_delegates.cc b/tests/unittests/client_app_delegates.cc new file mode 100644 index 000000000..ad8379799 --- /dev/null +++ b/tests/unittests/client_app_delegates.cc @@ -0,0 +1,131 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include "tests/cefclient/client_app.h" + +using client::ClientApp; + +void CreateBrowserDelegates(ClientApp::BrowserDelegateSet& delegates) { + // Bring in the Frame tests. + extern void CreateFrameBrowserTests( + ClientApp::BrowserDelegateSet& delegates); + CreateFrameBrowserTests(delegates); + + // Bring in the Navigation tests. + extern void CreateNavigationBrowserTests( + ClientApp::BrowserDelegateSet& delegates); + CreateNavigationBrowserTests(delegates); + + // Bring in the RequestHandler tests. + extern void CreateRequestHandlerBrowserTests( + ClientApp::BrowserDelegateSet& delegates); + CreateRequestHandlerBrowserTests(delegates); + + // Bring in the V8 tests. + extern void CreateV8BrowserTests( + ClientApp::BrowserDelegateSet& delegates); + CreateV8BrowserTests(delegates); +} + +void CreateRenderDelegates(ClientApp::RenderDelegateSet& delegates) { + // Bring in the Frame tests. + extern void CreateFrameRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateFrameRendererTests(delegates); + + // Bring in the DOM tests. + extern void CreateDOMRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateDOMRendererTests(delegates); + + // Bring in the message router tests. + extern void CreateMessageRouterRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateMessageRouterRendererTests(delegates); + + // Bring in the Navigation tests. + extern void CreateNavigationRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateNavigationRendererTests(delegates); + + // Bring in the process message tests. + extern void CreateProcessMessageRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateProcessMessageRendererTests(delegates); + + // Bring in the RequestHandler tests. + extern void CreateRequestHandlerRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateRequestHandlerRendererTests(delegates); + + // Bring in the Request tests. + extern void CreateRequestRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateRequestRendererTests(delegates); + + // Bring in the routing test handler delegate. + extern void CreateRoutingTestHandlerDelegate( + ClientApp::RenderDelegateSet& delegates); + CreateRoutingTestHandlerDelegate(delegates); + + // Bring in the URLRequest tests. + extern void CreateURLRequestRendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateURLRequestRendererTests(delegates); + + // Bring in the V8 tests. + extern void CreateV8RendererTests( + ClientApp::RenderDelegateSet& delegates); + CreateV8RendererTests(delegates); +} + +void RegisterCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes) { + // Bring in the scheme handler tests. + extern void RegisterSchemeHandlerCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes); + RegisterSchemeHandlerCustomSchemes(registrar, cookiable_schemes); + + // Bring in the cookie tests. + extern void RegisterCookieCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes); + RegisterCookieCustomSchemes(registrar, cookiable_schemes); + + // Bring in the URLRequest tests. + extern void RegisterURLRequestCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes); + RegisterURLRequestCustomSchemes(registrar, cookiable_schemes); +} + + +namespace client { + +// static +void ClientApp::CreateBrowserDelegates(BrowserDelegateSet& delegates) { + ::CreateBrowserDelegates(delegates); +} + +// static +void ClientApp::CreateRenderDelegates(RenderDelegateSet& delegates) { + ::CreateRenderDelegates(delegates); +} + +// static +void ClientApp::RegisterCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes) { + ::RegisterCustomSchemes(registrar, cookiable_schemes); +} + +// static +CefRefPtr ClientApp::CreatePrintHandler() { + return NULL; +} + +} // namespace client + diff --git a/tests/unittests/command_line_unittest.cc b/tests/unittests/command_line_unittest.cc new file mode 100644 index 000000000..da303beb4 --- /dev/null +++ b/tests/unittests/command_line_unittest.cc @@ -0,0 +1,121 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_command_line.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +void VerifyCommandLine(CefRefPtr command_line) { + std::string program = command_line->GetProgram(); + EXPECT_EQ("test.exe", program); + + EXPECT_TRUE(command_line->HasSwitches()); + + EXPECT_TRUE(command_line->HasSwitch("switch1")); + std::string switch1 = command_line->GetSwitchValue("switch1"); + EXPECT_EQ("", switch1); + EXPECT_TRUE(command_line->HasSwitch("switch2")); + std::string switch2 = command_line->GetSwitchValue("switch2"); + EXPECT_EQ("val2", switch2); + EXPECT_TRUE(command_line->HasSwitch("switch3")); + std::string switch3 = command_line->GetSwitchValue("switch3"); + EXPECT_EQ("val3", switch3); + EXPECT_TRUE(command_line->HasSwitch("switch4")); + std::string switch4 = command_line->GetSwitchValue("switch4"); + EXPECT_EQ("val 4", switch4); + EXPECT_FALSE(command_line->HasSwitch("switchnoexist")); + + CefCommandLine::SwitchMap switches; + command_line->GetSwitches(switches); + EXPECT_EQ((size_t)4, switches.size()); + + bool has1 = false, has2 = false, has3 = false, has4 = false; + + CefCommandLine::SwitchMap::const_iterator it = switches.begin(); + for (; it != switches.end(); ++it) { + std::string name = it->first; + std::string val = it->second; + + if (name == "switch1") { + has1 = true; + EXPECT_EQ("", val); + } else if (name == "switch2") { + has2 = true; + EXPECT_EQ("val2", val); + } else if (name == "switch3") { + has3 = true; + EXPECT_EQ("val3", val); + } else if (name == "switch4") { + has4 = true; + EXPECT_EQ("val 4", val); + } + } + + EXPECT_TRUE(has1); + EXPECT_TRUE(has2); + EXPECT_TRUE(has3); + EXPECT_TRUE(has4); + + EXPECT_TRUE(command_line->HasArguments()); + + CefCommandLine::ArgumentList args; + command_line->GetArguments(args); + EXPECT_EQ((size_t)2, args.size()); + std::string arg0 = args[0]; + EXPECT_EQ("arg1", arg0); + std::string arg1 = args[1]; + EXPECT_EQ("arg 2", arg1); + + command_line->Reset(); + EXPECT_FALSE(command_line->HasSwitches()); + EXPECT_FALSE(command_line->HasArguments()); + std::string cur_program = command_line->GetProgram(); + EXPECT_EQ(program, cur_program); +} + +} // namespace + +// Test creating a command line from argc/argv or string. +TEST(CommandLineTest, Init) { + CefRefPtr command_line = CefCommandLine::CreateCommandLine(); + EXPECT_TRUE(command_line.get() != NULL); + +#if defined(OS_WIN) + command_line->InitFromString("test.exe --switch1 -switch2=val2 /switch3=val3 " + "-switch4=\"val 4\" arg1 \"arg 2\""); +#else + const char* args[] = { + "test.exe", + "--switch1", + "-switch2=val2", + "-switch3=val3", + "-switch4=val 4", + "arg1", + "arg 2" + }; + command_line->InitFromArgv(sizeof(args) / sizeof(char*), args); +#endif + + VerifyCommandLine(command_line); +} + +// Test creating a command line using set and append methods. +TEST(CommandLineTest, Manual) { + CefRefPtr command_line = CefCommandLine::CreateCommandLine(); + EXPECT_TRUE(command_line.get() != NULL); + + command_line->SetProgram("test.exe"); + command_line->AppendSwitch("switch1"); + command_line->AppendSwitchWithValue("switch2", "val2"); + command_line->AppendSwitchWithValue("switch3", "val3"); + command_line->AppendSwitchWithValue("switch4", "val 4"); + command_line->AppendArgument("arg1"); + command_line->AppendArgument("arg 2"); + + VerifyCommandLine(command_line); +} diff --git a/tests/unittests/cookie_unittest.cc b/tests/unittests/cookie_unittest.cc new file mode 100644 index 000000000..2655d9de4 --- /dev/null +++ b/tests/unittests/cookie_unittest.cc @@ -0,0 +1,1133 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "base/files/scoped_temp_dir.h" +#include "base/synchronization/waitable_event.h" + +#include "include/base/cef_bind.h" +#include "include/base/cef_logging.h" +#include "include/base/cef_ref_counted.h" +#include "include/cef_cookie.h" +#include "include/cef_scheme.h" +#include "include/wrapper/cef_closure_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_suite.h" + +namespace { + +const char* kTestUrl = "http://www.test.com/path/to/cookietest/foo.html"; +const char* kTestDomain = "www.test.com"; +const char* kTestPath = "/path/to/cookietest"; + +typedef std::vector CookieVector; + +void IOT_Set(CefRefPtr manager, + const CefString& url, CookieVector* cookies, + base::WaitableEvent* event) { + CookieVector::const_iterator it = cookies->begin(); + for (; it != cookies->end(); ++it) + EXPECT_TRUE(manager->SetCookie(url, *it)); + event->Signal(); +} + +void IOT_Delete(CefRefPtr manager, + const CefString& url, const CefString& cookie_name, + base::WaitableEvent* event) { + EXPECT_TRUE(manager->DeleteCookies(url, cookie_name)); + event->Signal(); +} + +class TestVisitor : public CefCookieVisitor { + public: + TestVisitor(CookieVector* cookies, bool deleteCookies, + base::WaitableEvent* event) + : cookies_(cookies), + delete_cookies_(deleteCookies), + event_(event) { + } + ~TestVisitor() override { + event_->Signal(); + } + + bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) override { + cookies_->push_back(cookie); + if (delete_cookies_) + deleteCookie = true; + return true; + } + + CookieVector* cookies_; + bool delete_cookies_; + base::WaitableEvent* event_; + + IMPLEMENT_REFCOUNTING(TestVisitor); +}; + +// Set the cookies. +void SetCookies(CefRefPtr manager, + const CefString& url, CookieVector& cookies, + base::WaitableEvent& event) { + CefPostTask(TID_IO, base::Bind(IOT_Set, manager, url, &cookies, &event)); + event.Wait(); +} + +// Delete the cookie. +void DeleteCookies(CefRefPtr manager, + const CefString& url, const CefString& cookie_name, + base::WaitableEvent& event) { + CefPostTask(TID_IO, + base::Bind(IOT_Delete, manager, url, cookie_name, &event)); + event.Wait(); +} + +// Create a test cookie. If |withDomain| is true a domain cookie will be +// created, otherwise a host cookie will be created. +void CreateCookie(CefRefPtr manager, + CefCookie& cookie, bool withDomain, + bool sessionCookie, + base::WaitableEvent& event) { + CefString(&cookie.name).FromASCII("my_cookie"); + CefString(&cookie.value).FromASCII("My Value"); + if (withDomain) + CefString(&cookie.domain).FromASCII(kTestDomain); + CefString(&cookie.path).FromASCII(kTestPath); + if (!sessionCookie) { + cookie.has_expires = true; + cookie.expires.year = 2200; + cookie.expires.month = 4; + cookie.expires.day_of_week = 5; + cookie.expires.day_of_month = 11; + } + + CookieVector cookies; + cookies.push_back(cookie); + + SetCookies(manager, kTestUrl, cookies, event); +} + +// Retrieve the test cookie. If |withDomain| is true check that the cookie +// is a domain cookie, otherwise a host cookie. if |deleteCookies| is true +// the cookie will be deleted when it's retrieved. +void GetCookie(CefRefPtr manager, + const CefCookie& cookie, bool withDomain, + base::WaitableEvent& event, bool deleteCookies) { + CookieVector cookies; + + // Get the cookie and delete it. + EXPECT_TRUE(manager->VisitUrlCookies(kTestUrl, false, + new TestVisitor(&cookies, deleteCookies, &event))); + event.Wait(); + + EXPECT_EQ((CookieVector::size_type)1, cookies.size()); + + const CefCookie& cookie_read = cookies[0]; + EXPECT_EQ(CefString(&cookie_read.name), "my_cookie"); + EXPECT_EQ(CefString(&cookie_read.value), "My Value"); + if (withDomain) + EXPECT_EQ(CefString(&cookie_read.domain), ".www.test.com"); + else + EXPECT_EQ(CefString(&cookie_read.domain), kTestDomain); + EXPECT_EQ(CefString(&cookie_read.path), kTestPath); + EXPECT_EQ(cookie.has_expires, cookie_read.has_expires); + EXPECT_EQ(cookie.expires.year, cookie_read.expires.year); + EXPECT_EQ(cookie.expires.month, cookie_read.expires.month); + EXPECT_EQ(cookie.expires.day_of_week, cookie_read.expires.day_of_week); + EXPECT_EQ(cookie.expires.day_of_month, cookie_read.expires.day_of_month); + EXPECT_EQ(cookie.expires.hour, cookie_read.expires.hour); + EXPECT_EQ(cookie.expires.minute, cookie_read.expires.minute); + EXPECT_EQ(cookie.expires.second, cookie_read.expires.second); + EXPECT_EQ(cookie.expires.millisecond, cookie_read.expires.millisecond); +} + +// Visit URL cookies. +void VisitUrlCookies(CefRefPtr manager, + const CefString& url, + bool includeHttpOnly, + CookieVector& cookies, + bool deleteCookies, + base::WaitableEvent& event) { + EXPECT_TRUE(manager->VisitUrlCookies(url, includeHttpOnly, + new TestVisitor(&cookies, deleteCookies, &event))); + event.Wait(); +} + +// Visit all cookies. +void VisitAllCookies(CefRefPtr manager, + CookieVector& cookies, + bool deleteCookies, + base::WaitableEvent& event) { + EXPECT_TRUE(manager->VisitAllCookies( + new TestVisitor(&cookies, deleteCookies, &event))); + event.Wait(); +} + +// Verify that no cookies exist. If |withUrl| is true it will only check for +// cookies matching the URL. +void VerifyNoCookies(CefRefPtr manager, + base::WaitableEvent& event, bool withUrl) { + CookieVector cookies; + + // Verify that the cookie has been deleted. + if (withUrl) { + EXPECT_TRUE(manager->VisitUrlCookies(kTestUrl, false, + new TestVisitor(&cookies, false, &event))); + } else { + EXPECT_TRUE(manager->VisitAllCookies( + new TestVisitor(&cookies, false, &event))); + } + event.Wait(); + + EXPECT_EQ((CookieVector::size_type)0, cookies.size()); +} + +// Delete all system cookies. +void DeleteAllCookies(CefRefPtr manager, + base::WaitableEvent& event) { + CefPostTask(TID_IO, + base::Bind(IOT_Delete, manager, CefString(), CefString(), &event)); + event.Wait(); +} + +void TestDomainCookie(CefRefPtr manager) { + base::WaitableEvent event(false, false); + CefCookie cookie; + + // Create a domain cookie. + CreateCookie(manager, cookie, true, false, event); + + // Retrieve, verify and delete the domain cookie. + GetCookie(manager, cookie, true, event, true); + + // Verify that the cookie was deleted. + VerifyNoCookies(manager, event, true); +} + +void TestHostCookie(CefRefPtr manager) { + base::WaitableEvent event(false, false); + CefCookie cookie; + + // Create a host cookie. + CreateCookie(manager, cookie, false, false, event); + + // Retrieve, verify and delete the host cookie. + GetCookie(manager, cookie, false, event, true); + + // Verify that the cookie was deleted. + VerifyNoCookies(manager, event, true); +} + +void TestMultipleCookies(CefRefPtr manager) { + base::WaitableEvent event(false, false); + std::stringstream ss; + int i; + + CookieVector cookies; + + const int kNumCookies = 4; + + // Create the cookies. + for (i = 0; i < kNumCookies; i++) { + CefCookie cookie; + + ss << "my_cookie" << i; + CefString(&cookie.name).FromASCII(ss.str().c_str()); + ss.str(""); + ss << "My Value " << i; + CefString(&cookie.value).FromASCII(ss.str().c_str()); + ss.str(""); + + cookies.push_back(cookie); + } + + // Set the cookies. + SetCookies(manager, kTestUrl, cookies, event); + cookies.clear(); + + // Get the cookies without deleting them. + VisitUrlCookies(manager, kTestUrl, false, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)kNumCookies, cookies.size()); + + CookieVector::const_iterator it = cookies.begin(); + for (i = 0; it != cookies.end(); ++it, ++i) { + const CefCookie& cookie = *it; + + ss << "my_cookie" << i; + EXPECT_EQ(CefString(&cookie.name), ss.str()); + ss.str(""); + ss << "My Value " << i; + EXPECT_EQ(CefString(&cookie.value), ss.str()); + ss.str(""); + } + + cookies.clear(); + + // Delete the 2nd cookie. + DeleteCookies(manager, kTestUrl, CefString("my_cookie1"), event); + + // Verify that the cookie has been deleted. + VisitUrlCookies(manager, kTestUrl, false, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)3, cookies.size()); + EXPECT_EQ(CefString(&cookies[0].name), "my_cookie0"); + EXPECT_EQ(CefString(&cookies[1].name), "my_cookie2"); + EXPECT_EQ(CefString(&cookies[2].name), "my_cookie3"); + + cookies.clear(); + + // Delete the rest of the cookies. + DeleteCookies(manager, kTestUrl, CefString(), event); + + // Verify that the cookies have been deleted. + VisitUrlCookies(manager, kTestUrl, false, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)0, cookies.size()); + + // Create the cookies. + for (i = 0; i < kNumCookies; i++) { + CefCookie cookie; + + ss << "my_cookie" << i; + CefString(&cookie.name).FromASCII(ss.str().c_str()); + ss.str(""); + ss << "My Value " << i; + CefString(&cookie.value).FromASCII(ss.str().c_str()); + ss.str(""); + + cookies.push_back(cookie); + } + + // Delete all of the cookies using the visitor. + VisitUrlCookies(manager, kTestUrl, false, cookies, true, event); + + cookies.clear(); + + // Verify that the cookies have been deleted. + VisitUrlCookies(manager, kTestUrl, false, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)0, cookies.size()); +} + +void TestAllCookies(CefRefPtr manager) { + base::WaitableEvent event(false, false); + CookieVector cookies; + + // Delete all system cookies just in case something is left over from a + // different test. + DeleteCookies(manager, CefString(), CefString(), event); + + // Verify that all system cookies have been deleted. + VisitAllCookies(manager, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)0, cookies.size()); + + // Create cookies with 2 separate hosts. + CefCookie cookie1; + const char* kUrl1 = "http://www.foo.com"; + CefString(&cookie1.name).FromASCII("my_cookie1"); + CefString(&cookie1.value).FromASCII("My Value 1"); + + cookies.push_back(cookie1); + SetCookies(manager, kUrl1, cookies, event); + cookies.clear(); + + CefCookie cookie2; + const char* kUrl2 = "http://www.bar.com"; + CefString(&cookie2.name).FromASCII("my_cookie2"); + CefString(&cookie2.value).FromASCII("My Value 2"); + + cookies.push_back(cookie2); + SetCookies(manager, kUrl2, cookies, event); + cookies.clear(); + + // Verify that all system cookies can be retrieved. + VisitAllCookies(manager, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)2, cookies.size()); + EXPECT_EQ(CefString(&cookies[0].name), "my_cookie1"); + EXPECT_EQ(CefString(&cookies[0].value), "My Value 1"); + EXPECT_EQ(CefString(&cookies[0].domain), "www.foo.com"); + EXPECT_EQ(CefString(&cookies[1].name), "my_cookie2"); + EXPECT_EQ(CefString(&cookies[1].value), "My Value 2"); + EXPECT_EQ(CefString(&cookies[1].domain), "www.bar.com"); + cookies.clear(); + + // Verify that the cookies can be retrieved separately. + VisitUrlCookies(manager, kUrl1, false, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)1, cookies.size()); + EXPECT_EQ(CefString(&cookies[0].name), "my_cookie1"); + EXPECT_EQ(CefString(&cookies[0].value), "My Value 1"); + EXPECT_EQ(CefString(&cookies[0].domain), "www.foo.com"); + cookies.clear(); + + VisitUrlCookies(manager, kUrl2, false, cookies, false, event); + + EXPECT_EQ((CookieVector::size_type)1, cookies.size()); + EXPECT_EQ(CefString(&cookies[0].name), "my_cookie2"); + EXPECT_EQ(CefString(&cookies[0].value), "My Value 2"); + EXPECT_EQ(CefString(&cookies[0].domain), "www.bar.com"); + cookies.clear(); + + // Delete all of the system cookies. + DeleteAllCookies(manager, event); + + // Verify that all system cookies have been deleted. + VerifyNoCookies(manager, event, false); +} + +void TestChangeDirectory(CefRefPtr manager, + const CefString& original_dir) { + base::WaitableEvent event(false, false); + CefCookie cookie; + + base::ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + // Delete all of the system cookies. + DeleteAllCookies(manager, event); + + // Set the new temporary directory as the storage location. + EXPECT_TRUE(manager->SetStoragePath(temp_dir.path().value(), false)); + + // Wait for the storage location change to complete on the IO thread. + WaitForIOThread(); + + // Verify that no cookies exist. + VerifyNoCookies(manager, event, true); + + // Create a domain cookie. + CreateCookie(manager, cookie, true, false, event); + + // Retrieve and verify the domain cookie. + GetCookie(manager, cookie, true, event, false); + + // Restore the original storage location. + EXPECT_TRUE(manager->SetStoragePath(original_dir, false)); + + // Wait for the storage location change to complete on the IO thread. + WaitForIOThread(); + + // Verify that no cookies exist. + VerifyNoCookies(manager, event, true); + + // Set the new temporary directory as the storage location. + EXPECT_TRUE(manager->SetStoragePath(temp_dir.path().value(), false)); + + // Wait for the storage location change to complete on the IO thread. + WaitForIOThread(); + + // Retrieve and verify the domain cookie that was set previously. + GetCookie(manager, cookie, true, event, false); + + // Restore the original storage location. + EXPECT_TRUE(manager->SetStoragePath(original_dir, false)); + + // Wait for the storage location change to complete on the IO thread. + WaitForIOThread(); +} + +} // namespace + +// Test creation of a domain cookie. +TEST(CookieTest, DomainCookieGlobal) { + CefRefPtr manager = CefCookieManager::GetGlobalManager(); + EXPECT_TRUE(manager.get()); + + TestDomainCookie(manager); +} + +// Test creation of a domain cookie. +TEST(CookieTest, DomainCookieInMemory) { + CefRefPtr manager = + CefCookieManager::CreateManager(CefString(), false); + EXPECT_TRUE(manager.get()); + + TestDomainCookie(manager); +} + +// Test creation of a domain cookie. +TEST(CookieTest, DomainCookieOnDisk) { + base::ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value(), false); + EXPECT_TRUE(manager.get()); + + TestDomainCookie(manager); +} + +// Test creation of a host cookie. +TEST(CookieTest, HostCookieGlobal) { + CefRefPtr manager = CefCookieManager::GetGlobalManager(); + EXPECT_TRUE(manager.get()); + + TestHostCookie(manager); +} + +// Test creation of a host cookie. +TEST(CookieTest, HostCookieInMemory) { + CefRefPtr manager = + CefCookieManager::CreateManager(CefString(), false); + EXPECT_TRUE(manager.get()); + + TestHostCookie(manager); +} + +// Test creation of a host cookie. +TEST(CookieTest, HostCookieOnDisk) { + base::ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value(), false); + EXPECT_TRUE(manager.get()); + + TestHostCookie(manager); +} + +// Test creation of multiple cookies. +TEST(CookieTest, MultipleCookiesGlobal) { + CefRefPtr manager = CefCookieManager::GetGlobalManager(); + EXPECT_TRUE(manager.get()); + + TestMultipleCookies(manager); +} + +// Test creation of multiple cookies. +TEST(CookieTest, MultipleCookiesInMemory) { + CefRefPtr manager = + CefCookieManager::CreateManager(CefString(), false); + EXPECT_TRUE(manager.get()); + + TestMultipleCookies(manager); +} + +// Test creation of multiple cookies. +TEST(CookieTest, MultipleCookiesOnDisk) { + base::ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value(), false); + EXPECT_TRUE(manager.get()); + + TestMultipleCookies(manager); +} + +TEST(CookieTest, AllCookiesGlobal) { + CefRefPtr manager = CefCookieManager::GetGlobalManager(); + EXPECT_TRUE(manager.get()); + + TestAllCookies(manager); +} + +TEST(CookieTest, AllCookiesInMemory) { + CefRefPtr manager = + CefCookieManager::CreateManager(CefString(), false); + EXPECT_TRUE(manager.get()); + + TestAllCookies(manager); +} + +TEST(CookieTest, AllCookiesOnDisk) { + base::ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value(), false); + EXPECT_TRUE(manager.get()); + + TestAllCookies(manager); +} + +TEST(CookieTest, ChangeDirectoryGlobal) { + CefRefPtr manager = CefCookieManager::GetGlobalManager(); + EXPECT_TRUE(manager.get()); + + std::string cache_path; + CefTestSuite::GetCachePath(cache_path); + + TestChangeDirectory(manager, cache_path); +} + +TEST(CookieTest, ChangeDirectoryCreated) { + CefRefPtr manager = + CefCookieManager::CreateManager(CefString(), false); + EXPECT_TRUE(manager.get()); + + TestChangeDirectory(manager, CefString()); +} + + +namespace { + +class TestCompletionCallback : public CefCompletionCallback { + public: + explicit TestCompletionCallback(base::WaitableEvent* event) + : event_(event) {} + + void OnComplete() override { + event_->Signal(); + } + + private: + base::WaitableEvent* event_; + + IMPLEMENT_REFCOUNTING(TestCompletionCallback); +}; + +} // namespace + +TEST(CookieTest, SessionCookieNoPersist) { + base::ScopedTempDir temp_dir; + base::WaitableEvent event(false, false); + CefCookie cookie; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value(), false); + EXPECT_TRUE(manager.get()); + + // Create a session cookie. + CreateCookie(manager, cookie, true, true, event); + + // Retrieve and verify the cookie. + GetCookie(manager, cookie, true, event, false); + + // Flush the cookie store to disk. + manager->FlushStore(new TestCompletionCallback(&event)); + event.Wait(); + + // Create a new manager to read the same cookie store. + manager = + CefCookieManager::CreateManager(temp_dir.path().value(), false); + + // Verify that the cookie doesn't exist. + VerifyNoCookies(manager, event, true); +} + +TEST(CookieTest, SessionCookieWillPersist) { + base::ScopedTempDir temp_dir; + base::WaitableEvent event(false, false); + CefCookie cookie; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value(), true); + EXPECT_TRUE(manager.get()); + + // Create a session cookie. + CreateCookie(manager, cookie, true, true, event); + + // Retrieve and verify the cookie. + GetCookie(manager, cookie, true, event, false); + + // Flush the cookie store to disk. + manager->FlushStore(new TestCompletionCallback(&event)); + event.Wait(); + + // Create a new manager to read the same cookie store. + manager = + CefCookieManager::CreateManager(temp_dir.path().value(), true); + + // Verify that the cookie exists. + GetCookie(manager, cookie, true, event, false); +} + + +namespace { + +const char* kCookieJSUrl1 = "http://tests/cookie1.html"; +const char* kCookieJSUrl2 = "http://tests/cookie2.html"; + +class CookieTestJSHandler : public TestHandler { + public: + class RequestContextHandler : public CefRequestContextHandler { + public: + explicit RequestContextHandler(CookieTestJSHandler* handler) + : handler_(handler) {} + + CefRefPtr GetCookieManager() override { + EXPECT_TRUE(handler_); + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + if (url_ == kCookieJSUrl1) { + // Return the first cookie manager. + handler_->got_cookie_manager1_.yes(); + return handler_->manager1_; + } else { + // Return the second cookie manager. + handler_->got_cookie_manager2_.yes(); + return handler_->manager2_; + } + } + + void SetURL(const std::string& url) { + url_ = url; + } + + void Detach() { + handler_ = NULL; + } + + private: + std::string url_; + CookieTestJSHandler* handler_; + + IMPLEMENT_REFCOUNTING(RequestContextHandler); + }; + + CookieTestJSHandler() {} + + void RunTest() override { + // Create =new in-memory managers. + manager1_ = CefCookieManager::CreateManager(CefString(), false); + manager2_ = CefCookieManager::CreateManager(CefString(), false); + + std::string page = + "" + "" + "COOKIE TEST1"; + AddResource(kCookieJSUrl1, page, "text/html"); + + page = + "" + "" + "COOKIE TEST2"; + AddResource(kCookieJSUrl2, page, "text/html"); + + context_handler_ = new RequestContextHandler(this); + context_handler_->SetURL(kCookieJSUrl1); + + // Create the browser + CreateBrowser(kCookieJSUrl1, + CefRequestContext::CreateContext(context_handler_.get())); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + std::string url = frame->GetURL(); + if (url == kCookieJSUrl1) { + got_load_end1_.yes(); + VerifyCookie(manager1_, url, "name1", "value1", got_cookie1_); + + // Go to the next URL + context_handler_->SetURL(kCookieJSUrl2); + frame->LoadURL(kCookieJSUrl2); + } else { + got_load_end2_.yes(); + VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_); + + DestroyTest(); + } + } + + void DestroyTest() override { + context_handler_->Detach(); + context_handler_ = NULL; + + TestHandler::DestroyTest(); + } + + // Verify that the cookie was set successfully. + void VerifyCookie(CefRefPtr manager, + const std::string& url, + const std::string& name, + const std::string& value, + TrackCallback& callback) { + base::WaitableEvent event(false, false); + CookieVector cookies; + + // Get the cookie. + VisitUrlCookies(manager, url, false, cookies, false, event); + + if (cookies.size() == 1 && CefString(&cookies[0].name) == name && + CefString(&cookies[0].value) == value) { + callback.yes(); + } + } + + CefRefPtr context_handler_; + + CefRefPtr manager1_; + CefRefPtr manager2_; + + TrackCallback got_cookie_manager1_; + TrackCallback got_cookie_manager2_; + TrackCallback got_load_end1_; + TrackCallback got_load_end2_; + TrackCallback got_cookie1_; + TrackCallback got_cookie2_; +}; + +} // namespace + +// Verify use of multiple cookie managers vis JS. +TEST(CookieTest, GetCookieManagerJS) { + CefRefPtr handler = new CookieTestJSHandler(); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_cookie_manager1_); + EXPECT_TRUE(handler->got_cookie_manager2_); + EXPECT_TRUE(handler->got_load_end1_); + EXPECT_TRUE(handler->got_load_end2_); + EXPECT_TRUE(handler->got_cookie1_); + EXPECT_TRUE(handler->got_cookie2_); + + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +class CookieTestSchemeHandler : public TestHandler { + public: + class SchemeHandler : public CefResourceHandler { + public: + explicit SchemeHandler(CookieTestSchemeHandler* handler) + : handler_(handler), + offset_(0) {} + + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override { + std::string url = request->GetURL(); + if (url == handler_->url1_) { + content_ = "COOKIE TEST1"; + cookie_ = "name1=value1"; + handler_->got_process_request1_.yes(); + } else if (url == handler_->url2_) { + content_ = "COOKIE TEST2"; + cookie_ = "name2=value2"; + handler_->got_process_request2_.yes(); + } else if (url == handler_->url3_) { + content_ = "COOKIE TEST3"; + handler_->got_process_request3_.yes(); + + // Verify that the cookie was passed in. + CefRequest::HeaderMap headerMap; + request->GetHeaderMap(headerMap); + CefRequest::HeaderMap::iterator it = headerMap.find("Cookie"); + if (it != headerMap.end() && it->second == "name2=value2") + handler_->got_process_request_cookie_.yes(); + + } + callback->Continue(); + return true; + } + + void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) override { + response_length = content_.size(); + + response->SetStatus(200); + response->SetMimeType("text/html"); + + if (!cookie_.empty()) { + CefResponse::HeaderMap headerMap; + response->GetHeaderMap(headerMap); + headerMap.insert(std::make_pair("Set-Cookie", cookie_)); + response->SetHeaderMap(headerMap); + } + } + + bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) override { + bool has_data = false; + bytes_read = 0; + + size_t size = content_.size(); + if (offset_ < size) { + int transfer_size = + std::min(bytes_to_read, static_cast(size - offset_)); + memcpy(data_out, content_.c_str() + offset_, transfer_size); + offset_ += transfer_size; + + bytes_read = transfer_size; + has_data = true; + } + + return has_data; + } + + void Cancel() override { + } + + private: + CookieTestSchemeHandler* handler_; + std::string content_; + size_t offset_; + std::string cookie_; + + IMPLEMENT_REFCOUNTING(SchemeHandler); + }; + + class SchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + explicit SchemeHandlerFactory(CookieTestSchemeHandler* handler) + : handler_(handler) {} + + CefRefPtr Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) override { + std::string url = request->GetURL(); + if (url == handler_->url3_) { + // Verify that the cookie was not passed in. + CefRequest::HeaderMap headerMap; + request->GetHeaderMap(headerMap); + CefRequest::HeaderMap::iterator it = headerMap.find("Cookie"); + if (it != headerMap.end() && it->second == "name2=value2") + handler_->got_create_cookie_.yes(); + } + + return new SchemeHandler(handler_); + } + + private: + CookieTestSchemeHandler* handler_; + + IMPLEMENT_REFCOUNTING(SchemeHandlerFactory); + }; + + class RequestContextHandler : public CefRequestContextHandler { + public: + explicit RequestContextHandler(CookieTestSchemeHandler* handler) + : handler_(handler) {} + + CefRefPtr GetCookieManager() override { + EXPECT_TRUE(handler_); + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + if (url_ == handler_->url1_) { + // Return the first cookie manager. + handler_->got_cookie_manager1_.yes(); + return handler_->manager1_; + } else { + // Return the second cookie manager. + handler_->got_cookie_manager2_.yes(); + return handler_->manager2_; + } + } + + void SetURL(const std::string& url) { + url_ = url; + } + + void Detach() { + handler_ = NULL; + } + + private: + std::string url_; + CookieTestSchemeHandler* handler_; + + IMPLEMENT_REFCOUNTING(RequestContextHandler); + }; + + CookieTestSchemeHandler(const std::string& scheme) : scheme_(scheme) { + url1_ = scheme + "://cookie-tests/cookie1.html"; + url2_ = scheme + "://cookie-tests/cookie2.html"; + url3_ = scheme + "://cookie-tests/cookie3.html"; + } + + void RunTest() override { + // Create new in-memory managers. + manager1_ = CefCookieManager::CreateManager(CefString(), false); + manager2_ = CefCookieManager::CreateManager(CefString(), false); + + if (scheme_ != "http") { + std::vector schemes; + schemes.push_back("http"); + schemes.push_back("https"); + schemes.push_back(scheme_); + + manager1_->SetSupportedSchemes(schemes); + manager2_->SetSupportedSchemes(schemes); + } + + // Register the scheme handler. + CefRegisterSchemeHandlerFactory(scheme_, "cookie-tests", + new SchemeHandlerFactory(this)); + + context_handler_ = new RequestContextHandler(this); + context_handler_->SetURL(url1_); + + // Create the browser + CreateBrowser(url1_, + CefRequestContext::CreateContext(context_handler_.get())); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + std::string url = frame->GetURL(); + if (url == url1_) { + got_load_end1_.yes(); + VerifyCookie(manager1_, url, "name1", "value1", got_cookie1_); + + // Go to the next URL + context_handler_->SetURL(url2_); + frame->LoadURL(url2_); + } else if (url == url2_) { + got_load_end2_.yes(); + VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_); + + // Go to the next URL + context_handler_->SetURL(url3_); + frame->LoadURL(url3_); + } else { + got_load_end3_.yes(); + VerifyCookie(manager2_, url, "name2", "value2", got_cookie3_); + + // Unregister the scheme handler. + CefRegisterSchemeHandlerFactory(scheme_, "cookie-tests", NULL); + + DestroyTest(); + } + } + + void DestroyTest() override { + context_handler_->Detach(); + context_handler_ = NULL; + + TestHandler::DestroyTest(); + } + + // Verify that the cookie was set successfully. + void VerifyCookie(CefRefPtr manager, + const std::string& url, + const std::string& name, + const std::string& value, + TrackCallback& callback) { + base::WaitableEvent event(false, false); + CookieVector cookies; + + // Get the cookie. + VisitUrlCookies(manager, url, false, cookies, false, event); + + if (cookies.size() == 1 && CefString(&cookies[0].name) == name && + CefString(&cookies[0].value) == value) { + callback.yes(); + } + } + + std::string scheme_; + std::string url1_; + std::string url2_; + std::string url3_; + + CefRefPtr context_handler_; + + CefRefPtr manager1_; + CefRefPtr manager2_; + + TrackCallback got_process_request1_; + TrackCallback got_process_request2_; + TrackCallback got_process_request3_; + TrackCallback got_create_cookie_; + TrackCallback got_process_request_cookie_; + TrackCallback got_cookie_manager1_; + TrackCallback got_cookie_manager2_; + TrackCallback got_load_end1_; + TrackCallback got_load_end2_; + TrackCallback got_load_end3_; + TrackCallback got_cookie1_; + TrackCallback got_cookie2_; + TrackCallback got_cookie3_; +}; + +} // namespace + +// Verify use of multiple cookie managers via HTTP. +TEST(CookieTest, GetCookieManagerHttp) { + CefRefPtr handler = + new CookieTestSchemeHandler("http"); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_process_request1_); + EXPECT_TRUE(handler->got_process_request2_); + EXPECT_TRUE(handler->got_process_request3_); + EXPECT_FALSE(handler->got_create_cookie_); + EXPECT_TRUE(handler->got_process_request_cookie_); + EXPECT_TRUE(handler->got_cookie_manager1_); + EXPECT_TRUE(handler->got_cookie_manager2_); + EXPECT_TRUE(handler->got_load_end1_); + EXPECT_TRUE(handler->got_load_end2_); + EXPECT_TRUE(handler->got_load_end3_); + EXPECT_TRUE(handler->got_cookie1_); + EXPECT_TRUE(handler->got_cookie2_); + EXPECT_TRUE(handler->got_cookie3_); + + ReleaseAndWaitForDestructor(handler); +} + +// Verify use of multiple cookie managers via a custom scheme. +TEST(CookieTest, GetCookieManagerCustom) { + CefRefPtr handler = + new CookieTestSchemeHandler("ccustom"); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_process_request1_); + EXPECT_TRUE(handler->got_process_request2_); + EXPECT_TRUE(handler->got_process_request3_); + EXPECT_FALSE(handler->got_create_cookie_); + EXPECT_TRUE(handler->got_process_request_cookie_); + EXPECT_TRUE(handler->got_cookie_manager1_); + EXPECT_TRUE(handler->got_cookie_manager2_); + EXPECT_TRUE(handler->got_load_end1_); + EXPECT_TRUE(handler->got_load_end2_); + EXPECT_TRUE(handler->got_load_end3_); + EXPECT_TRUE(handler->got_cookie1_); + EXPECT_TRUE(handler->got_cookie2_); + EXPECT_TRUE(handler->got_cookie3_); + + ReleaseAndWaitForDestructor(handler); +} + +// Entry point for registering custom schemes. +// Called from client_app_delegates.cc. +void RegisterCookieCustomSchemes( + CefRefPtr registrar, + std::vector& cookiable_schemes) { + // Used by GetCookieManagerCustom test. + registrar->AddCustomScheme("ccustom", true, false, false); +} diff --git a/tests/unittests/dialog_unittest.cc b/tests/unittests/dialog_unittest.cc new file mode 100644 index 000000000..36ea45082 --- /dev/null +++ b/tests/unittests/dialog_unittest.cc @@ -0,0 +1,350 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/base/cef_bind.h" +#include "include/wrapper/cef_closure_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_util.h" + +namespace { + +const char* kTestUrl = "http://tests/DialogTestHandler"; + +class DialogTestHandler : public TestHandler { + public: + struct TestConfig { + explicit TestConfig(FileDialogMode dialog_mode) + : mode(dialog_mode), + title("Test Title"), + default_file_name("Test File Name"), + selected_accept_filter(1), // Something other than 0 for testing. + callback_async(false), + callback_cancel(false) { + accept_types.push_back("text/*"); + accept_types.push_back(".js"); + accept_types.push_back(".css"); + } + + FileDialogMode mode; + CefString title; + CefString default_file_name; + std::vector accept_types; + int selected_accept_filter; + + bool callback_async; // True if the callback should execute asynchronously. + bool callback_cancel; // True if the callback should cancel. + std::vector callback_paths; // Resulting paths if not cancelled. + }; + + class Callback : public CefRunFileDialogCallback { + public: + explicit Callback(DialogTestHandler* handler) + : handler_(handler) { + } + + void OnFileDialogDismissed( + int selected_accept_filter, + const std::vector& file_paths) override { + handler_->got_onfiledialogdismissed_.yes(); + + if (handler_->config_.callback_cancel) { + EXPECT_EQ(0, selected_accept_filter); + EXPECT_TRUE(file_paths.empty()); + } else { + EXPECT_EQ(handler_->config_.selected_accept_filter, + selected_accept_filter); + TestStringVectorEqual(handler_->config_.callback_paths, file_paths); + } + + handler_->DestroyTest(); + handler_ = NULL; + } + + private: + DialogTestHandler* handler_; + + IMPLEMENT_REFCOUNTING(Callback); + }; + + explicit DialogTestHandler(const TestConfig& config) + : config_(config) { + } + + void RunTest() override { + AddResource(kTestUrl, "TEST", "text/html"); + + // Create the browser + CreateBrowser(kTestUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + browser->GetHost()->RunFileDialog(config_.mode, + config_.title, + config_.default_file_name, + config_.accept_types, + config_.selected_accept_filter, + new Callback(this)); + } + + void ExecuteCallback(CefRefPtr callback) { + if (config_.callback_cancel) + callback->Cancel(); + else + callback->Continue(config_.selected_accept_filter, + config_.callback_paths); + } + + // CefDialogHandler + bool OnFileDialog( + CefRefPtr browser, + FileDialogMode mode, + const CefString& title, + const CefString& default_file_name, + const std::vector& accept_types, + int selected_accept_filter, + CefRefPtr callback) override { + got_onfiledialog_.yes(); + + std::string url = browser->GetMainFrame()->GetURL(); + EXPECT_STREQ(kTestUrl, url.c_str()); + + EXPECT_EQ(config_.mode, mode); + EXPECT_STREQ(config_.title.ToString().c_str(), title.ToString().c_str()); + EXPECT_STREQ(config_.default_file_name.ToString().c_str(), + default_file_name.ToString().c_str()); + TestStringVectorEqual(config_.accept_types, accept_types); + + if (config_.callback_async) { + CefPostTask(TID_UI, + base::Bind(&DialogTestHandler::ExecuteCallback, this, callback)); + } else { + ExecuteCallback(callback); + } + + return true; + } + + void DestroyTest() override { + EXPECT_TRUE(got_onfiledialog_); + EXPECT_TRUE(got_onfiledialogdismissed_); + + TestHandler::DestroyTest(); + } + + TestConfig config_; + + TrackCallback got_onfiledialog_; + TrackCallback got_onfiledialogdismissed_; +}; + +} // namespace + +// Test with all parameters empty. +TEST(DialogTest, FileEmptyParams) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN); + config.title.clear(); + config.default_file_name.clear(); + config.accept_types.clear(); + config.callback_async = false; + config.callback_cancel = false; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileAdditionalFlags) { + DialogTestHandler::TestConfig config( + static_cast(FILE_DIALOG_OPEN | + FILE_DIALOG_HIDEREADONLY_FLAG | + FILE_DIALOG_OVERWRITEPROMPT_FLAG)); + config.title.clear(); + config.default_file_name.clear(); + config.accept_types.clear(); + config.callback_async = false; + config.callback_cancel = false; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpen) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN); + config.callback_async = false; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/file1.txt"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenAsync) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN); + config.callback_async = true; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/file1.txt"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenAsyncCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenMultiple) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_MULTIPLE); + config.callback_async = false; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/file1.txt"); + config.callback_paths.push_back("/path/to/file2.txt"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenMultipleCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_MULTIPLE); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenMultipleAsync) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_MULTIPLE); + config.callback_async = true; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/file1.txt"); + config.callback_paths.push_back("/path/to/file2.txt"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenMultipleAsyncCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_MULTIPLE); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenFolder) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_FOLDER); + config.callback_async = false; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/folder"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenFolderCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_FOLDER); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenFolderAsync) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_FOLDER); + config.callback_async = true; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/folder"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileOpenFolderAsyncCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_OPEN_FOLDER); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileSave) { + DialogTestHandler::TestConfig config(FILE_DIALOG_SAVE); + config.callback_async = false; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/file1.txt"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileSaveCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_SAVE); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileSaveAsync) { + DialogTestHandler::TestConfig config(FILE_DIALOG_SAVE); + config.callback_async = true; + config.callback_cancel = false; + config.callback_paths.push_back("/path/to/file1.txt"); + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(DialogTest, FileSaveAsyncCancel) { + DialogTestHandler::TestConfig config(FILE_DIALOG_SAVE); + config.callback_async = false; + config.callback_cancel = true; + + CefRefPtr handler = new DialogTestHandler(config); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} diff --git a/tests/unittests/display_unittest.cc b/tests/unittests/display_unittest.cc new file mode 100644 index 000000000..adca4c6ef --- /dev/null +++ b/tests/unittests/display_unittest.cc @@ -0,0 +1,116 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/unittests/test_handler.h" + +namespace { + +// How it works: +// 1. Load kTitleUrl1 (title should be kTitleStr1) +// 2. Load kTitleUrl2 (title should be kTitleStr2) +// 3. History back to kTitleUrl1 (title should be kTitleStr1) +// 4. History forward to kTitleUrl2 (title should be kTitleStr2) +// 5. Set title via JavaScript (title should be kTitleStr3) + +const char kTitleUrl1[] = "http://tests-title/nav1.html"; +const char kTitleUrl2[] = "http://tests-title/nav2.html"; +const char kTitleStr1[] = "Title 1"; +const char kTitleStr2[] = "Title 2"; +const char kTitleStr3[] = "Title 3"; + +// Browser side. +class TitleTestHandler : public TestHandler { + public: + TitleTestHandler() + : step_(0) {} + + void RunTest() override { + // Add the resources that we will navigate to/from. + AddResource(kTitleUrl1, + "" + std::string(kTitleStr1) + + "Nav1", "text/html"); + AddResource(kTitleUrl2, + "" + std::string(kTitleStr2) + + "Nav2" + + "" + + "", "text/html"); + + // Create the browser. + CreateBrowser(kTitleUrl1); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnTitleChange(CefRefPtr browser, + const CefString& title) override { + std::string title_str = title; + if (step_ == 0 || step_ == 2) { + EXPECT_STREQ(kTitleStr1, title_str.c_str()); + } else if (step_ == 1 || step_ == 3) { + EXPECT_STREQ(kTitleStr2, title_str.c_str()); + } else if (step_ == 4) { + // Ignore the unexpected notification of the page URL. + // Related bug: http://crbug.com/331351 + if (title_str == &kTitleUrl2[7]) + return; + + EXPECT_STREQ(kTitleStr3, title_str.c_str()); + } + + got_title_[step_].yes(); + + if (step_ == 4) + DestroyTest(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + switch (step_++) { + case 0: + frame->LoadURL(kTitleUrl2); + break; + case 1: + browser->GoBack(); + break; + case 2: + browser->GoForward(); + break; + case 3: + frame->ExecuteJavaScript("setTitle()", kTitleUrl2, 0); + break; + default: + EXPECT_TRUE(false); // Not reached. + } + } + + private: + void DestroyTest() override { + for (int i = 0; i < 5; ++i) + EXPECT_TRUE(got_title_[i]) << "step " << i; + + TestHandler::DestroyTest(); + } + + int step_; + + TrackCallback got_title_[5]; +}; + +} // namespace + +// Test title notifications. +TEST(DisplayTest, Title) { + CefRefPtr handler = new TitleTestHandler(); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} diff --git a/tests/unittests/dom_unittest.cc b/tests/unittests/dom_unittest.cc new file mode 100644 index 000000000..dd3b13536 --- /dev/null +++ b/tests/unittests/dom_unittest.cc @@ -0,0 +1,344 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_dom.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" + +using client::ClientApp; + +namespace { + +const char* kTestUrl = "http://tests/DOMTest.Test"; +const char* kTestMessage = "DOMTest.Message"; + +enum DOMTestType { + DOM_TEST_STRUCTURE, + DOM_TEST_MODIFY, +}; + +class TestDOMVisitor : public CefDOMVisitor { + public: + explicit TestDOMVisitor(CefRefPtr browser, DOMTestType test_type) + : browser_(browser), + test_type_(test_type) { + } + + void TestHeadNodeStructure(CefRefPtr headNode) { + EXPECT_TRUE(headNode.get()); + EXPECT_TRUE(headNode->IsElement()); + EXPECT_FALSE(headNode->IsText()); + EXPECT_EQ(headNode->GetName(), "HEAD"); + EXPECT_EQ(headNode->GetElementTagName(), "HEAD"); + + EXPECT_TRUE(headNode->HasChildren()); + EXPECT_FALSE(headNode->HasElementAttributes()); + + CefRefPtr titleNode = headNode->GetFirstChild(); + EXPECT_TRUE(titleNode.get()); + EXPECT_TRUE(titleNode->IsElement()); + EXPECT_FALSE(titleNode->IsText()); + EXPECT_EQ(titleNode->GetName(), "TITLE"); + EXPECT_EQ(titleNode->GetElementTagName(), "TITLE"); + EXPECT_TRUE(titleNode->GetParent()->IsSame(headNode)); + + EXPECT_FALSE(titleNode->GetNextSibling().get()); + EXPECT_FALSE(titleNode->GetPreviousSibling().get()); + EXPECT_TRUE(titleNode->HasChildren()); + EXPECT_FALSE(titleNode->HasElementAttributes()); + + CefRefPtr textNode = titleNode->GetFirstChild(); + EXPECT_TRUE(textNode.get()); + EXPECT_FALSE(textNode->IsElement()); + EXPECT_TRUE(textNode->IsText()); + EXPECT_EQ(textNode->GetValue(), "The Title"); + EXPECT_TRUE(textNode->GetParent()->IsSame(titleNode)); + + EXPECT_FALSE(textNode->GetNextSibling().get()); + EXPECT_FALSE(textNode->GetPreviousSibling().get()); + EXPECT_FALSE(textNode->HasChildren()); + } + + void TestBodyNodeStructure(CefRefPtr bodyNode) { + EXPECT_TRUE(bodyNode.get()); + EXPECT_TRUE(bodyNode->IsElement()); + EXPECT_FALSE(bodyNode->IsText()); + EXPECT_EQ(bodyNode->GetName(), "BODY"); + EXPECT_EQ(bodyNode->GetElementTagName(), "BODY"); + + EXPECT_TRUE(bodyNode->HasChildren()); + EXPECT_FALSE(bodyNode->HasElementAttributes()); + + CefRefPtr h1Node = bodyNode->GetFirstChild(); + EXPECT_TRUE(h1Node.get()); + EXPECT_TRUE(h1Node->IsElement()); + EXPECT_FALSE(h1Node->IsText()); + EXPECT_EQ(h1Node->GetName(), "H1"); + EXPECT_EQ(h1Node->GetElementTagName(), "H1"); + + EXPECT_FALSE(h1Node->GetNextSibling().get()); + EXPECT_FALSE(h1Node->GetPreviousSibling().get()); + EXPECT_TRUE(h1Node->HasChildren()); + EXPECT_FALSE(h1Node->HasElementAttributes()); + + CefRefPtr textNode = h1Node->GetFirstChild(); + EXPECT_TRUE(textNode.get()); + EXPECT_FALSE(textNode->IsElement()); + EXPECT_TRUE(textNode->IsText()); + EXPECT_EQ(textNode->GetValue(), "Hello From"); + + EXPECT_FALSE(textNode->GetPreviousSibling().get()); + EXPECT_FALSE(textNode->HasChildren()); + + CefRefPtr brNode = textNode->GetNextSibling(); + EXPECT_TRUE(brNode.get()); + EXPECT_TRUE(brNode->IsElement()); + EXPECT_FALSE(brNode->IsText()); + EXPECT_EQ(brNode->GetName(), "BR"); + EXPECT_EQ(brNode->GetElementTagName(), "BR"); + + EXPECT_FALSE(brNode->HasChildren()); + + EXPECT_TRUE(brNode->HasElementAttributes()); + EXPECT_TRUE(brNode->HasElementAttribute("class")); + EXPECT_EQ(brNode->GetElementAttribute("class"), "some_class"); + EXPECT_TRUE(brNode->HasElementAttribute("id")); + EXPECT_EQ(brNode->GetElementAttribute("id"), "some_id"); + EXPECT_FALSE(brNode->HasElementAttribute("no_existing")); + + CefDOMNode::AttributeMap map; + brNode->GetElementAttributes(map); + ASSERT_EQ(map.size(), (size_t)2); + EXPECT_EQ(map["class"], "some_class"); + EXPECT_EQ(map["id"], "some_id"); + + // Can also retrieve by ID. + brNode = bodyNode->GetDocument()->GetElementById("some_id"); + EXPECT_TRUE(brNode.get()); + EXPECT_TRUE(brNode->IsElement()); + EXPECT_FALSE(brNode->IsText()); + EXPECT_EQ(brNode->GetName(), "BR"); + EXPECT_EQ(brNode->GetElementTagName(), "BR"); + + textNode = brNode->GetNextSibling(); + EXPECT_TRUE(textNode.get()); + EXPECT_FALSE(textNode->IsElement()); + EXPECT_TRUE(textNode->IsText()); + EXPECT_EQ(textNode->GetValue(), "Main Frame"); + + EXPECT_FALSE(textNode->GetNextSibling().get()); + EXPECT_FALSE(textNode->HasChildren()); + } + + // Test document structure by iterating through the DOM tree. + void TestStructure(CefRefPtr document) { + EXPECT_EQ(document->GetTitle(), "The Title"); + EXPECT_EQ(document->GetBaseURL(), kTestUrl); + EXPECT_EQ(document->GetCompleteURL("foo.html"), "http://tests/foo.html"); + + // Navigate the complete document structure. + CefRefPtr docNode = document->GetDocument(); + EXPECT_TRUE(docNode.get()); + EXPECT_FALSE(docNode->IsElement()); + EXPECT_FALSE(docNode->IsText()); + + CefRefPtr htmlNode = docNode->GetFirstChild(); + EXPECT_TRUE(htmlNode.get()); + EXPECT_TRUE(htmlNode->IsElement()); + EXPECT_FALSE(htmlNode->IsText()); + EXPECT_EQ(htmlNode->GetName(), "HTML"); + EXPECT_EQ(htmlNode->GetElementTagName(), "HTML"); + + EXPECT_TRUE(htmlNode->HasChildren()); + EXPECT_FALSE(htmlNode->HasElementAttributes()); + + CefRefPtr headNode = htmlNode->GetFirstChild(); + TestHeadNodeStructure(headNode); + + CefRefPtr bodyNode = headNode->GetNextSibling(); + TestBodyNodeStructure(bodyNode); + + // Retrieve the head node directly. + headNode = document->GetHead(); + TestHeadNodeStructure(headNode); + + // Retrieve the body node directly. + bodyNode = document->GetBody(); + TestBodyNodeStructure(bodyNode); + } + + // Test document modification by changing the H1 tag. + void TestModify(CefRefPtr document) { + CefRefPtr bodyNode = document->GetBody(); + CefRefPtr h1Node = bodyNode->GetFirstChild(); + + ASSERT_EQ(h1Node->GetAsMarkup(), + "

Hello From
" + "Main Frame

"); + + CefRefPtr textNode = h1Node->GetFirstChild(); + ASSERT_EQ(textNode->GetValue(), "Hello From"); + ASSERT_TRUE(textNode->SetValue("A Different Message From")); + ASSERT_EQ(textNode->GetValue(), "A Different Message From"); + + CefRefPtr brNode = textNode->GetNextSibling(); + EXPECT_EQ(brNode->GetElementAttribute("class"), "some_class"); + EXPECT_TRUE(brNode->SetElementAttribute("class", "a_different_class")); + EXPECT_EQ(brNode->GetElementAttribute("class"), "a_different_class"); + + ASSERT_EQ(h1Node->GetAsMarkup(), + "

A Different Message From
Main Frame

"); + + ASSERT_FALSE(h1Node->SetValue("Something Different")); + } + + void Visit(CefRefPtr document) override { + if (test_type_ == DOM_TEST_STRUCTURE) + TestStructure(document); + else if (test_type_ == DOM_TEST_MODIFY) + TestModify(document); + + DestroyTest(); + } + + protected: + // Return from the test. + void DestroyTest() { + // Check if the test has failed. + bool result = !TestFailed(); + + // Return the result to the browser process. + CefRefPtr return_msg = + CefProcessMessage::Create(kTestMessage); + EXPECT_TRUE(return_msg->GetArgumentList()->SetBool(0, result)); + EXPECT_TRUE(browser_->SendProcessMessage(PID_BROWSER, return_msg)); + } + + CefRefPtr browser_; + DOMTestType test_type_; + + IMPLEMENT_REFCOUNTING(TestDOMVisitor); +}; + +// Used in the render process. +class DOMRendererTest : public ClientApp::RenderDelegate { + public: + DOMRendererTest() { + } + + bool OnProcessMessageReceived( + CefRefPtr app, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (message->GetName() == kTestMessage) { + EXPECT_EQ(message->GetArgumentList()->GetSize(), (size_t)1); + int test_type = message->GetArgumentList()->GetInt(0); + + browser->GetMainFrame()->VisitDOM( + new TestDOMVisitor(browser, static_cast(test_type))); + return true; + } + return false; + } + + private: + IMPLEMENT_REFCOUNTING(DOMRendererTest); +}; + +// Used in the browser process. +class TestDOMHandler : public TestHandler { + public: + explicit TestDOMHandler(DOMTestType test) + : test_type_(test) { + } + + void RunTest() override { + std::stringstream mainHtml; + mainHtml << + "" + "The Title" + "" + "

Hello From
" + "Main Frame

" + "" + ""; + + AddResource(kTestUrl, mainHtml.str(), "text/html"); + CreateBrowser(kTestUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + if (frame->IsMain()) { + // Start the test in the render process. + CefRefPtr message( + CefProcessMessage::Create(kTestMessage)); + message->GetArgumentList()->SetInt(0, test_type_); + EXPECT_TRUE(browser->SendProcessMessage(PID_RENDERER, message)); + } + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + EXPECT_STREQ(message->GetName().ToString().c_str(), kTestMessage); + + got_message_.yes(); + + if (message->GetArgumentList()->GetBool(0)) + got_success_.yes(); + + // Test is complete. + DestroyTest(); + + return true; + } + + DOMTestType test_type_; + TrackCallback got_message_; + TrackCallback got_success_; +}; + +} // namespace + +// Test DOM structure reading. +TEST(DOMTest, Read) { + CefRefPtr handler = + new TestDOMHandler(DOM_TEST_STRUCTURE); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_message_); + EXPECT_TRUE(handler->got_success_); + + ReleaseAndWaitForDestructor(handler); +} + +// Test DOM modifications. +TEST(DOMTest, Modify) { + CefRefPtr handler = + new TestDOMHandler(DOM_TEST_MODIFY); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_message_); + EXPECT_TRUE(handler->got_success_); + + ReleaseAndWaitForDestructor(handler); +} + +// Entry point for creating DOM renderer test objects. +// Called from client_app_delegates.cc. +void CreateDOMRendererTests(ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new DOMRendererTest); +} diff --git a/tests/unittests/download_unittest.cc b/tests/unittests/download_unittest.cc new file mode 100644 index 000000000..958e4df99 --- /dev/null +++ b/tests/unittests/download_unittest.cc @@ -0,0 +1,268 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" + +#include "include/cef_scheme.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/unittests/test_handler.h" + +namespace { + +const char kTestDomain[] = "test-download"; +const char kTestEntryUrl[] = "http://test-download/test.html"; +const char kTestDownloadUrl[] = "http://test-download/download.txt"; +const char kTestFileName[] = "download_test.txt"; +const char kTestContentDisposition[] = + "attachment; filename=\"download_test.txt\""; +const char kTestMimeType[] = "text/plain"; +const char kTestContent[] = "Download test text"; + +class DownloadSchemeHandler : public CefResourceHandler { + public: + explicit DownloadSchemeHandler(TrackCallback* got_download_request) + : got_download_request_(got_download_request), + offset_(0) {} + + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override { + std::string url = request->GetURL(); + if (url == kTestEntryUrl) { + content_ = "Download Test"; + mime_type_ = "text/html"; + } else if (url == kTestDownloadUrl) { + got_download_request_->yes(); + content_ = kTestContent; + mime_type_ = kTestMimeType; + content_disposition_ = kTestContentDisposition; + } else { + EXPECT_TRUE(false); // Not reached. + return false; + } + + callback->Continue(); + return true; + } + + void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) override { + response_length = content_.size(); + + response->SetStatus(200); + response->SetMimeType(mime_type_); + + if (!content_disposition_.empty()) { + CefResponse::HeaderMap headerMap; + response->GetHeaderMap(headerMap); + headerMap.insert( + std::make_pair("Content-Disposition", content_disposition_)); + response->SetHeaderMap(headerMap); + } + } + + bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) override { + bool has_data = false; + bytes_read = 0; + + size_t size = content_.size(); + if (offset_ < size) { + int transfer_size = + std::min(bytes_to_read, static_cast(size - offset_)); + memcpy(data_out, content_.c_str() + offset_, transfer_size); + offset_ += transfer_size; + + bytes_read = transfer_size; + has_data = true; + } + + return has_data; + } + + void Cancel() override { + } + + private: + TrackCallback* got_download_request_; + std::string content_; + std::string mime_type_; + std::string content_disposition_; + size_t offset_; + + IMPLEMENT_REFCOUNTING(DownloadSchemeHandler); +}; + +class DownloadSchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + explicit DownloadSchemeHandlerFactory(TrackCallback* got_download_request) + : got_download_request_(got_download_request) {} + + CefRefPtr Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) override { + return new DownloadSchemeHandler(got_download_request_); + } + + private: + TrackCallback* got_download_request_; + + IMPLEMENT_REFCOUNTING(DownloadSchemeHandlerFactory); +}; + +class DownloadTestHandler : public TestHandler { + public: + DownloadTestHandler() {} + + void RunTest() override { + CefRegisterSchemeHandlerFactory("http", kTestDomain, + new DownloadSchemeHandlerFactory(&got_download_request_)); + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); + test_path_ = temp_dir_.path().AppendASCII(kTestFileName); + + // Create the browser + CreateBrowser(kTestEntryUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + EXPECT_STREQ(kTestEntryUrl, frame->GetURL().ToString().c_str()); + + // Begin the download. + browser->GetHost()->StartDownload(kTestDownloadUrl); + } + + void OnBeforeDownload( + CefRefPtr browser, + CefRefPtr download_item, + const CefString& suggested_name, + CefRefPtr callback) override { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + EXPECT_FALSE(got_on_before_download_); + + got_on_before_download_.yes(); + + EXPECT_TRUE(browser->IsSame(GetBrowser())); + EXPECT_STREQ(kTestFileName, suggested_name.ToString().c_str()); + EXPECT_TRUE(download_item.get()); + EXPECT_TRUE(callback.get()); + + download_id_ = download_item->GetId(); + EXPECT_LT(0U, download_id_); + + EXPECT_TRUE(download_item->IsValid()); + EXPECT_TRUE(download_item->IsInProgress()); + EXPECT_FALSE(download_item->IsComplete()); + EXPECT_FALSE(download_item->IsCanceled()); + EXPECT_EQ(static_cast(sizeof(kTestContent)-1), + download_item->GetTotalBytes()); + EXPECT_EQ(0UL, download_item->GetFullPath().length()); + EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); + EXPECT_EQ(0UL, download_item->GetSuggestedFileName().length()); + EXPECT_STREQ(kTestContentDisposition, + download_item->GetContentDisposition().ToString().c_str()); + EXPECT_STREQ(kTestMimeType, download_item->GetMimeType().ToString().c_str()); + + callback->Continue(test_path_.value(), false); + } + + void OnDownloadUpdated( + CefRefPtr browser, + CefRefPtr download_item, + CefRefPtr callback) override { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + + got_on_download_updated_.yes(); + + EXPECT_TRUE(browser->IsSame(GetBrowser())); + EXPECT_TRUE(download_item.get()); + EXPECT_TRUE(callback.get()); + + if (got_on_before_download_) + EXPECT_EQ(download_id_, download_item->GetId()); + + EXPECT_LE(0LL, download_item->GetCurrentSpeed()); + EXPECT_LE(0, download_item->GetPercentComplete()); + + EXPECT_TRUE(download_item->IsValid()); + EXPECT_FALSE(download_item->IsCanceled()); + EXPECT_STREQ(kTestDownloadUrl, download_item->GetURL().ToString().c_str()); + EXPECT_STREQ(kTestContentDisposition, + download_item->GetContentDisposition().ToString().c_str()); + EXPECT_STREQ(kTestMimeType, + download_item->GetMimeType().ToString().c_str()); + + std::string full_path = download_item->GetFullPath(); + if (!full_path.empty()) { + got_full_path_.yes(); + EXPECT_STREQ(CefString(test_path_.value()).ToString().c_str(), + full_path.c_str()); + } + + if (download_item->IsComplete()) { + EXPECT_FALSE(download_item->IsInProgress()); + EXPECT_EQ(100, download_item->GetPercentComplete()); + EXPECT_EQ(static_cast(sizeof(kTestContent)-1), + download_item->GetReceivedBytes()); + EXPECT_EQ(static_cast(sizeof(kTestContent)-1), + download_item->GetTotalBytes()); + + DestroyTest(); + } else { + EXPECT_TRUE(download_item->IsInProgress()); + EXPECT_LE(0LL, download_item->GetReceivedBytes()); + } + } + + void DestroyTest() override { + CefRegisterSchemeHandlerFactory("http", kTestDomain, NULL); + + EXPECT_TRUE(got_download_request_); + EXPECT_TRUE(got_on_before_download_); + EXPECT_TRUE(got_on_download_updated_); + EXPECT_TRUE(got_full_path_); + + // Verify the file contents. + std::string contents; + EXPECT_TRUE(base::ReadFileToString(test_path_, &contents)); + EXPECT_STREQ(kTestContent, contents.c_str()); + + EXPECT_TRUE(temp_dir_.Delete()); + + TestHandler::DestroyTest(); + } + + private: + base::ScopedTempDir temp_dir_; + base::FilePath test_path_; + uint32 download_id_; + + TrackCallback got_download_request_; + TrackCallback got_on_before_download_; + TrackCallback got_on_download_updated_; + TrackCallback got_full_path_; +}; + +} // namespace + +// Verify that downloads work. +TEST(DownloadTest, Download) { + CefRefPtr handler = new DownloadTestHandler(); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} diff --git a/tests/unittests/frame_unittest.cc b/tests/unittests/frame_unittest.cc new file mode 100644 index 000000000..1f7edf6ad --- /dev/null +++ b/tests/unittests/frame_unittest.cc @@ -0,0 +1,2308 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/base/cef_bind.h" +#include "include/base/cef_scoped_ptr.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_stream_resource_handler.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" + +using client::ClientApp; + +namespace { + +// The frame navigation test harness work as follows: +// +// In the browser process: +// 1. TEST() function creates a new FrameNavTestHandler instance with a unique +// FrameNavFactoryId. +// 2. FrameNavTestHandler calls FrameNavExpectationsFactoryBrowser::FromID to +// create a new factory instance. +// 3. FrameNavTestHandler calls FrameNavExpectationsFactoryBrowser::Create to +// create a new FrameNavExpectationsBrowser instance for the current +// navigation. +// 4. FrameNavTestHandler retrieves the URL to load via +// FrameNavExpectationsBrowser::GetMainURL and calls either CreateBrowser +// (for the first navigation) or LoadURL (for the following navigations). +// 5. If the renderer process does not already exist CEF creates it with +// command-line arguments that specify the FrameNavFactoryId via +// FrameNavBrowserTest::OnBeforeChildProcessLaunch. +// +// In the renderer process: +// 6. If the renderer process is newly created FrameNavRendererTest calls +// FrameNavExpectationsFactoryRenderer::FromID to create a new factory +// instance. +// 7. FrameNavRendererTest calls FrameNavExpectationsFactoryRenderer::Create to +// create a new FrameNavExpectationsRenderer instance for the current +// navigation. +// +// In both processes: +// 8. Callback notifications are sent to the FrameNavExpectations* instances. +// +// In the renderer process: +// 9. When the FrameNavExpectationsRenderer instance determines that the +// renderer side of the test is complete it calls SignalComplete which +// finalizes and deletes the FrameNavExpectationsRenderer instance and +// sends an IPC message to the browser process. +// +// In the browser process: +// 11.FrameNavExpectationsBrowser::OnRendererComplete is called in response to +// renderer-side test completion message. +// 12.When the FrameNavExpectationsBrowser instance determines that the browser +// side of the test is complete it calls SignalComplete which finalizes and +// deletes the FrameNavExpectationsBrowser instance. +// 13.If FrameNavExpectationsFactoryBrowser::HasMoreNavigations returns false +// then DestroyTest is called and the test ends. Otherwise, the navigation +// count is incremented and the process repeats starting with step #3. +// +// +// To add a new test case: +// 1. Add a new value to the FrameNavFactoryId enumeration. +// 2. Provide implementations of FrameNavExpectations*. +// 3. Add a case for the new factory ID to FrameNavExpectationsFactory*::FromID. +// 4. Implement a TEST() function that creates a FrameNavTestHandler instance +// and passes the new factory ID. +// +// +// Run with the `--single-process` command-line flag to see expectation failures +// from the renderer process. +// + +// All known factory IDs. +enum FrameNavFactoryId { + FNF_ID_INVALID = 0, + FNF_ID_SINGLE_NAV_HARNESS, + FNF_ID_SINGLE_NAV, + FNF_ID_MULTI_NAV_HARNESS, + FNF_ID_MULTI_NAV, + FNF_ID_NESTED_IFRAMES_SAME_ORIGIN, + FNF_ID_NESTED_IFRAMES_DIFF_ORIGIN, +}; + +// Command-line argument names. +const char kTestArg[] = "test"; +const char kTestFactoryIdArg[] = "testfid"; + +// IPC message name. +const char kFrameNavMsg[] = "FrameTest.Navigation"; + +// Origins used in tests. +const char kFrameNavOrigin0[] = "http://tests-framenav0.com/"; +const char kFrameNavOrigin1[] = "http://tests-framenav1.com/"; +const char kFrameNavOrigin2[] = "http://tests-framenav2.com/"; + +// Maximum number of navigations. Should be kept synchronized with the number +// of kFrameNavOrigin* values. Don't modify this value without checking the +// below use cases. +const int kMaxMultiNavNavigations = 3; + +// Global variables identifying the currently running test. +bool g_frame_nav_test = false; +FrameNavFactoryId g_frame_nav_factory_id = FNF_ID_INVALID; + + +// Abstract base class representing expectations that result from a navigation. +class FrameNavExpectations { + public: + typedef base::Callback)> CompletionCallback; + + FrameNavExpectations(int nav, bool renderer) + : nav_(nav), + renderer_(renderer) { + } + virtual ~FrameNavExpectations() {} + + // Browser and renderer notifications. + virtual bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) { return true; } + virtual bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) { return true; } + virtual bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) { return true; } + + // Final expectations check before this object is deleted. + virtual bool Finalize() =0; + + // Signal that all expectations are completed. Should be called as a result of + // notifications. + void SignalComplete(CefRefPtr browser) { + if (!completion_callback_.is_null()) { + // Execute the callback asynchronously to avoid any issues with what's + // currently on the stack. + CefPostTask((renderer_ ? TID_RENDERER: TID_UI), + base::Bind(completion_callback_, browser)); + completion_callback_.Reset(); + } + } + + // Returns the current navigation count. In the browser process this value + // increments over the life span of the FrameNavTestHandler instance. In the + // renderer process this value increments over the life span of a single + // renderer instance (i.e. cross-origin navigations will cause this value to + // reset). + int nav() const { return nav_; } + + // Returns true if this is a renderer-side expectation object. + bool renderer() const { return renderer_; } + + void set_completion_callback(const CompletionCallback& completion_callback) { + completion_callback_ = completion_callback; + } + + private: + int nav_; + bool renderer_; + CompletionCallback completion_callback_; +}; + +// Browser process expectations abstact base class. +class FrameNavExpectationsBrowser : public FrameNavExpectations { + public: + explicit FrameNavExpectationsBrowser(int nav) + : FrameNavExpectations(nav, false) { + } + + // Loading information. + virtual std::string GetMainURL() =0; + virtual std::string GetContentForURL(const std::string& url) =0; + + // Browser-only notifications. + virtual bool OnAfterCreated(CefRefPtr browser) { return true; } + virtual bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame) { return true; } + virtual bool GetResourceHandler(CefRefPtr browser, + CefRefPtr frame) { return true; } + + // Called when the renderer signals completion. + virtual bool OnRendererComplete(CefRefPtr browser, + int renderer_nav, + bool renderer_result) =0; +}; + +// Renderer process expectations abstract base class. +class FrameNavExpectationsRenderer : public FrameNavExpectations { + public: + explicit FrameNavExpectationsRenderer(int nav) + : FrameNavExpectations(nav, true) { + } + + // Renderer-only notifications. + virtual bool OnBeforeNavigation(CefRefPtr browser, + CefRefPtr frame) { return true; } +}; + + +// Abstract base class for the factory that creates expectations objects. +class FrameNavExpectationsFactory { + public: + FrameNavExpectationsFactory() {} + virtual ~FrameNavExpectationsFactory() {} + + // Returns the unique ID for this factory type. + virtual FrameNavFactoryId GetID() const =0; +}; + +// Browser process expectations factory abstact base class. +class FrameNavExpectationsFactoryBrowser : public FrameNavExpectationsFactory { + public: + FrameNavExpectationsFactoryBrowser() {} + + // Create a new factory instance of the specified type. + static scoped_ptr + FromID(FrameNavFactoryId id); + + // Returns true if there will be more navigations in the browser process + // handler. + virtual bool HasMoreNavigations() const =0; + + // Verify final expectations results. + virtual bool Finalize() =0; + + scoped_ptr Create( + int nav, + const FrameNavExpectations::CompletionCallback& completion_callback) { + scoped_ptr expectations; + expectations = Create(nav); + expectations->set_completion_callback(completion_callback); + return expectations.Pass(); + } + + protected: + // Implement in the test-specific factory instance. + virtual scoped_ptr Create(int nav) =0; +}; + +// Renderer process expectations factory abstact base class. +class FrameNavExpectationsFactoryRenderer : public FrameNavExpectationsFactory { + public: + FrameNavExpectationsFactoryRenderer() {} + + // Create a new factory instance of the specified type. + static scoped_ptr + FromID(FrameNavFactoryId id); + + scoped_ptr Create( + int nav, + const FrameNavExpectations::CompletionCallback& completion_callback) { + scoped_ptr expectations; + expectations = Create(nav); + expectations->set_completion_callback(completion_callback); + return expectations.Pass(); + } + + protected: + // Implement in the test-specific factory instance. + virtual scoped_ptr Create(int nav) =0; +}; + + +// Browser side app delegate. +class FrameNavBrowserTest : public ClientApp::BrowserDelegate { + public: + FrameNavBrowserTest() {} + + void OnBeforeChildProcessLaunch( + CefRefPtr app, + CefRefPtr command_line) override { + if (!g_frame_nav_test) + return; + + std::stringstream ss; + ss << g_frame_nav_factory_id; + + // Indicate to the render process that the test should be run. + command_line->AppendSwitchWithValue(kTestArg, kFrameNavMsg); + command_line->AppendSwitchWithValue(kTestFactoryIdArg, ss.str()); + } + + protected: + IMPLEMENT_REFCOUNTING(FrameNavBrowserTest); +}; + +// Renderer side handler. +class FrameNavRendererTest : public ClientApp::RenderDelegate, + public CefLoadHandler { + public: + FrameNavRendererTest() + : run_test_(false), + nav_(0) {} + + void OnRenderThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) override { + // The g_* values will be set when running in single-process mode. + if (!g_frame_nav_test) { + // Check that the test should be run. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + const std::string& test = command_line->GetSwitchValue(kTestArg); + if (test != kFrameNavMsg) + return; + } + + FrameNavFactoryId factory_id = g_frame_nav_factory_id; + if (factory_id == FNF_ID_INVALID) { + // Retrieve the factory ID from the command-line. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + if (command_line->HasSwitch(kTestFactoryIdArg)) { + factory_id = static_cast( + atoi(command_line->GetSwitchValue( + kTestFactoryIdArg).ToString().c_str())); + if (factory_id == FNF_ID_INVALID) + return; + } + } + + run_test_ = true; + factory_ = FrameNavExpectationsFactoryRenderer::FromID(factory_id); + } + + CefRefPtr GetLoadHandler( + CefRefPtr app) override { + if (!run_test_) + return NULL; + + return this; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + CreateExpectationsIfNecessary(); + EXPECT_TRUE(expectations_->OnLoadingStateChange(browser, isLoading)) << + "isLoading = " << isLoading << ", nav = " << nav_; + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + CreateExpectationsIfNecessary(); + EXPECT_TRUE(expectations_->OnLoadStart(browser, frame)) << "nav = " << nav_; + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + CreateExpectationsIfNecessary(); + EXPECT_TRUE(expectations_->OnLoadEnd(browser, frame)) << "nav = " << nav_; + } + + bool OnBeforeNavigation(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + cef_navigation_type_t navigation_type, + bool is_redirect) override { + if (!run_test_) + return false; + + CreateExpectationsIfNecessary(); + EXPECT_TRUE(expectations_->OnBeforeNavigation(browser, frame)) << + "nav = " << nav_; + return false; + } + + protected: + // Create a new expectations object if one does not already exist for the + // current navigation. + void CreateExpectationsIfNecessary() { + if (expectations_) + return; + expectations_ = factory_->Create( + nav_, + base::Bind(&FrameNavRendererTest::SendTestResults, this)); + } + + // Send the test results. + // Will be called via FrameNavExpectations::SignalComplete. + void SendTestResults(CefRefPtr browser) { + // End of the current expectations object. + EXPECT_TRUE(expectations_->Finalize()) << "nav = " << nav_; + expectations_.reset(NULL); + + // Check if the test has failed. + bool result = !TestFailed(); + + // Return the result to the browser process. + CefRefPtr return_msg = + CefProcessMessage::Create(kFrameNavMsg); + CefRefPtr args = return_msg->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->SetInt(0, nav_)); + EXPECT_TRUE(args->SetBool(1, result)); + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, return_msg)); + + nav_++; + } + + bool run_test_; + int nav_; + scoped_ptr factory_; + scoped_ptr expectations_; + + IMPLEMENT_REFCOUNTING(FrameNavRendererTest); +}; + +// Browser side handler. +class FrameNavTestHandler : public TestHandler { + public: + explicit FrameNavTestHandler(FrameNavFactoryId factory_id) + : nav_(0), + factory_(FrameNavExpectationsFactoryBrowser::FromID(factory_id)) { + EXPECT_FALSE(g_frame_nav_test); + EXPECT_EQ(FNF_ID_INVALID, g_frame_nav_factory_id); + g_frame_nav_test = true; + g_frame_nav_factory_id = factory_id; + } + + ~FrameNavTestHandler() override { + EXPECT_TRUE(got_destroyed_); + g_frame_nav_test = false; + g_frame_nav_factory_id = FNF_ID_INVALID; + } + + void RunTest() override { + // Create the first expectations object. + expectations_ = factory_->Create( + nav_, + base::Bind(&FrameNavTestHandler::RunNextNav, this)); + + // Create the browser with the initial URL. + CreateBrowser(expectations_->GetMainURL()); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + // Transition to the next navigation. + // Will be called via FrameNavExpectations::SignalComplete. + void RunNextNav(CefRefPtr browser) { + // End of the current expectations object. + EXPECT_TRUE(expectations_->Finalize()); + expectations_.reset(NULL); + + if (!factory_->HasMoreNavigations()) { + // End of the test. + DestroyTest(); + return; + } + + nav_++; + + // Create the next expectations object. + expectations_ = factory_->Create( + nav_, + base::Bind(&FrameNavTestHandler::RunNextNav, this)); + + // Load the main URL. + browser->GetMainFrame()->LoadURL(expectations_->GetMainURL()); + } + + void OnAfterCreated(CefRefPtr browser) override { + TestHandler::OnAfterCreated(browser); + + EXPECT_TRUE(expectations_->OnAfterCreated(browser)) << "nav = " << nav_; + } + + CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + EXPECT_TRUE(expectations_->GetResourceHandler(browser, frame)) << + "nav = " << nav_; + + const std::string& url = request->GetURL(); + const std::string& content = expectations_->GetContentForURL(url); + EXPECT_TRUE(!content.empty()) << "nav = " << nav_; + + CefRefPtr stream = + CefStreamReader::CreateForData( + static_cast(const_cast(content.c_str())), + content.length()); + return new CefStreamResourceHandler("text/html", stream); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + EXPECT_TRUE(expectations_->OnBeforeBrowse(browser, frame)) << + "nav = " << nav_; + + return false; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + EXPECT_TRUE(expectations_->OnLoadingStateChange(browser, isLoading)) << + "isLoading = " << isLoading << ", nav = " << nav_;; + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_TRUE(expectations_->OnLoadStart(browser, frame)) << "nav = " << nav_; + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + EXPECT_TRUE(expectations_->OnLoadEnd(browser, frame)) << "nav = " << nav_; + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (message->GetName().ToString() == kFrameNavMsg) { + // Test that the renderer side succeeded. + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + + EXPECT_TRUE(expectations_->OnRendererComplete(browser, + args->GetInt(0), args->GetBool(1))) << "nav = " << nav_; + return true; + } + + // Message not handled. + return false; + } + + void DestroyTest() override { + if (got_destroyed_) + return; + + got_destroyed_.yes(); + + // The expectations should have been tested already. + EXPECT_FALSE(expectations_.get()); + + // Test that factory conditions we met. + EXPECT_TRUE(factory_->Finalize()) << "nav = " << nav_; + + TestHandler::DestroyTest(); + } + + int nav_; + TrackCallback got_destroyed_; + scoped_ptr factory_; + scoped_ptr expectations_; +}; + +// Helper for defining frame tests. +#define FRAME_TEST(name, factory_id) \ + TEST(FrameTest, name) { \ + CefRefPtr handler = \ + new FrameNavTestHandler(factory_id); \ + handler->ExecuteTest(); \ + ReleaseAndWaitForDestructor(handler); \ + } + + +// Browser process expectations for a single navigation. +class FrameNavExpectationsBrowserSingleNav : + public FrameNavExpectationsBrowser { + public: + explicit FrameNavExpectationsBrowserSingleNav(int nav) + : FrameNavExpectationsBrowser(nav) { + } + + ~FrameNavExpectationsBrowserSingleNav() override { + EXPECT_TRUE(got_finalize_); + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (isLoading) { + EXPECT_FALSE(got_loading_state_change_start_); + got_loading_state_change_start_.yes(); + } else { + EXPECT_FALSE(got_loading_state_change_end_); + got_loading_state_change_end_.yes(); + SignalCompleteIfDone(browser); + } + return true; + } + + bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_load_start_); + got_load_start_.yes(); + return true; + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_load_end_); + got_load_end_.yes(); + SignalCompleteIfDone(browser); + return true; + } + + bool OnAfterCreated(CefRefPtr browser) override { + EXPECT_FALSE(got_after_created_); + got_after_created_.yes(); + return true; + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_before_browse_); + got_before_browse_.yes(); + return true; + } + + bool GetResourceHandler(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_get_resource_handler_); + got_get_resource_handler_.yes(); + return true; + } + + bool OnRendererComplete(CefRefPtr browser, + int renderer_nav, + bool renderer_result) override { + EXPECT_EQ(nav(), renderer_nav); + EXPECT_TRUE(renderer_result); + EXPECT_FALSE(got_renderer_done_); + got_renderer_done_.yes(); + SignalCompleteIfDone(browser); + return true; + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_TRUE(got_load_start_); + V_EXPECT_TRUE(got_load_end_); + V_EXPECT_TRUE(got_loading_state_change_start_); + V_EXPECT_TRUE(got_loading_state_change_end_); + V_EXPECT_TRUE(got_renderer_done_); + V_EXPECT_TRUE(got_after_created_); + V_EXPECT_TRUE(got_before_browse_); + V_EXPECT_TRUE(got_get_resource_handler_); + V_EXPECT_FALSE(got_finalize_); + + got_finalize_.yes(); + + V_RETURN(); + } + + private: + void SignalCompleteIfDone(CefRefPtr browser) { + if (got_renderer_done_ && got_load_end_ && got_loading_state_change_end_) + SignalComplete(browser); + } + + TrackCallback got_load_start_; + TrackCallback got_load_end_; + TrackCallback got_loading_state_change_start_; + TrackCallback got_loading_state_change_end_; + TrackCallback got_renderer_done_; + TrackCallback got_after_created_; + TrackCallback got_before_browse_; + TrackCallback got_get_resource_handler_; + TrackCallback got_finalize_; +}; + +// Renderer process expectations for a single navigation. +class FrameNavExpectationsRendererSingleNav : + public FrameNavExpectationsRenderer { + public: + explicit FrameNavExpectationsRendererSingleNav(int nav) + : FrameNavExpectationsRenderer(nav) { + } + + ~FrameNavExpectationsRendererSingleNav() override { + EXPECT_TRUE(got_finalize_); + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (isLoading) { + EXPECT_FALSE(got_loading_state_change_start_); + got_loading_state_change_start_.yes(); + } else { + EXPECT_FALSE(got_loading_state_change_end_); + got_loading_state_change_end_.yes(); + SignalCompleteIfDone(browser); + } + return true; + } + + bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_load_start_); + got_load_start_.yes(); + return true; + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_load_end_); + got_load_end_.yes(); + SignalCompleteIfDone(browser); + return true; + } + + bool OnBeforeNavigation(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_before_navigation_); + got_before_navigation_.yes(); + return true; + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_TRUE(got_load_start_); + V_EXPECT_TRUE(got_load_end_); + V_EXPECT_TRUE(got_loading_state_change_start_); + V_EXPECT_TRUE(got_loading_state_change_end_); + V_EXPECT_TRUE(got_before_navigation_); + V_EXPECT_FALSE(got_finalize_); + + got_finalize_.yes(); + + V_RETURN(); + } + + private: + void SignalCompleteIfDone(CefRefPtr browser) { + if (got_load_end_ && got_loading_state_change_end_) + SignalComplete(browser); + } + + TrackCallback got_load_start_; + TrackCallback got_load_end_; + TrackCallback got_loading_state_change_start_; + TrackCallback got_loading_state_change_end_; + TrackCallback got_before_navigation_; + TrackCallback got_finalize_; +}; + +// Test that the single nav harness works. +class FrameNavExpectationsBrowserTestSingleNavHarness : + public FrameNavExpectationsBrowserSingleNav { + public: + typedef FrameNavExpectationsBrowserSingleNav parent; + + explicit FrameNavExpectationsBrowserTestSingleNavHarness(int nav) + : parent(nav) { + } + + ~FrameNavExpectationsBrowserTestSingleNavHarness() override { + EXPECT_TRUE(got_finalize_); + } + + std::string GetMainURL() override { + EXPECT_FALSE(got_get_main_url_); + got_get_main_url_.yes(); + return kFrameNavOrigin0; + } + + std::string GetContentForURL(const std::string& url) override { + EXPECT_FALSE(got_get_content_for_url_); + got_get_content_for_url_.yes(); + EXPECT_STREQ(kFrameNavOrigin0, url.c_str()); + return "Nav"; + } + + bool Finalize() override { + EXPECT_FALSE(got_finalize_); + got_finalize_.yes(); + + V_DECLARE(); + V_EXPECT_TRUE(got_get_main_url_); + V_EXPECT_TRUE(got_get_content_for_url_); + V_EXPECT_TRUE(parent::Finalize()); + V_RETURN(); + } + + private: + TrackCallback got_get_main_url_; + TrackCallback got_get_content_for_url_; + TrackCallback got_finalize_; +}; + +class FrameNavExpectationsRendererTestSingleNavHarness : + public FrameNavExpectationsRendererSingleNav { + public: + typedef FrameNavExpectationsRendererSingleNav parent; + + explicit FrameNavExpectationsRendererTestSingleNavHarness(int nav) + : parent(nav) { + } + + ~FrameNavExpectationsRendererTestSingleNavHarness() override { + EXPECT_TRUE(got_finalize_); + } + + bool Finalize() override { + EXPECT_FALSE(got_finalize_); + got_finalize_.yes(); + return parent::Finalize(); + } + + private: + TrackCallback got_finalize_; +}; + +class FrameNavExpectationsFactoryBrowserTestSingleNavHarness : + public FrameNavExpectationsFactoryBrowser { + public: + FrameNavExpectationsFactoryBrowserTestSingleNavHarness() {} + + ~FrameNavExpectationsFactoryBrowserTestSingleNavHarness() override { + EXPECT_TRUE(got_finalize_); + } + + FrameNavFactoryId GetID() const override { + return FNF_ID_SINGLE_NAV_HARNESS; + } + + bool HasMoreNavigations() const override { + EXPECT_FALSE(got_get_browser_navigation_count_); + got_get_browser_navigation_count_.yes(); + return false; + } + + bool Finalize() override { + EXPECT_FALSE(got_finalize_); + got_finalize_.yes(); + + V_DECLARE(); + V_EXPECT_TRUE(got_get_browser_navigation_count_); + V_EXPECT_TRUE(got_create_); + V_RETURN(); + } + + protected: + scoped_ptr Create(int nav) override { + EXPECT_FALSE(got_create_); + got_create_.yes(); + return make_scoped_ptr( + new FrameNavExpectationsBrowserTestSingleNavHarness(nav)); + } + + private: + mutable TrackCallback got_get_browser_navigation_count_; + TrackCallback got_create_; + TrackCallback got_finalize_; +}; + +class FrameNavExpectationsFactoryRendererTestSingleNavHarness : + public FrameNavExpectationsFactoryRenderer { + public: + FrameNavExpectationsFactoryRendererTestSingleNavHarness() {} + + FrameNavFactoryId GetID() const override { + return FNF_ID_SINGLE_NAV_HARNESS; + } + + protected: + scoped_ptr Create(int nav) override { + return make_scoped_ptr( + new FrameNavExpectationsRendererTestSingleNavHarness(nav)); + } +}; + +} // namespace + +// Test that the single nav harness works. +FRAME_TEST(SingleNavHarness, FNF_ID_SINGLE_NAV_HARNESS) + + +namespace { + +bool VerifySingleBrowserFrame(CefRefPtr browser, + CefRefPtr frame, + bool frame_should_exist, + const std::string& expected_url) { + V_DECLARE(); + V_EXPECT_TRUE(frame.get()); + V_EXPECT_TRUE(frame->IsValid()); + if (frame_should_exist) { + V_EXPECT_TRUE(frame->GetIdentifier() >= 0); + } else { + V_EXPECT_TRUE(frame->GetIdentifier() == -4); // kInvalidFrameId + } + V_EXPECT_TRUE(frame->IsValid()); + V_EXPECT_TRUE(frame->IsMain()); + V_EXPECT_TRUE(frame->IsFocused()); + V_EXPECT_FALSE(frame->GetParent().get()); + V_EXPECT_TRUE(frame->GetName().empty()); + V_EXPECT_TRUE(browser->GetIdentifier() == + frame->GetBrowser()->GetIdentifier()); + + const std::string& frame_url = frame->GetURL(); + V_EXPECT_TRUE(frame_url == expected_url) << "frame_url = " << frame_url << + ", expected_url = " << expected_url; + + V_RETURN(); +} + +bool VerifySingleBrowserFrames(CefRefPtr browser, + CefRefPtr frame, + bool frame_should_exist, + const std::string& expected_url) { + V_DECLARE(); + V_EXPECT_TRUE(browser.get()); + + // |frame| may be NULL for callbacks that don't specify one. + if (frame.get()) { + V_EXPECT_TRUE(VerifySingleBrowserFrame(browser, frame, + frame_should_exist, expected_url)); + } + + CefRefPtr main_frame = browser->GetMainFrame(); + V_EXPECT_TRUE(VerifySingleBrowserFrame(browser, main_frame, + frame_should_exist, expected_url)); + + CefRefPtr focused_frame = browser->GetFocusedFrame(); + V_EXPECT_TRUE(VerifySingleBrowserFrame(browser, focused_frame, + frame_should_exist, expected_url)); + + size_t frame_count = browser->GetFrameCount(); + if (frame_should_exist) { + V_EXPECT_TRUE(frame_count == 1U); + + std::vector identifiers; + browser->GetFrameIdentifiers(identifiers); + V_EXPECT_TRUE(identifiers.size() == 1U); + if (identifiers.size() == 1U) { + V_EXPECT_TRUE(identifiers[0] == main_frame->GetIdentifier()); + V_EXPECT_TRUE(identifiers[0] == focused_frame->GetIdentifier()); + } + + std::vector names; + browser->GetFrameNames(names); + V_EXPECT_TRUE(names.size() == 1U); + if (names.size() == 1U) { + V_EXPECT_TRUE(names[0].ToString() == main_frame->GetName().ToString()); + V_EXPECT_TRUE(names[0].ToString() == focused_frame->GetName().ToString()); + } + } else { + V_EXPECT_TRUE(frame_count == 0U); + } + + V_RETURN(); +} + +// Test that single navigation works. +class FrameNavExpectationsBrowserTestSingleNav : + public FrameNavExpectationsBrowserSingleNav { + public: + typedef FrameNavExpectationsBrowserSingleNav parent; + + explicit FrameNavExpectationsBrowserTestSingleNav(int nav) + : parent(nav) { + } + + std::string GetMainURL() override { + return kFrameNavOrigin0; + } + + std::string GetContentForURL(const std::string& url) override { + return "Nav"; + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + V_DECLARE(); + if (isLoading) { + // No frame exists before the first load. + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, false, + std::string())); + } else { + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + kFrameNavOrigin0)); + } + V_EXPECT_TRUE(parent::OnLoadingStateChange(browser, isLoading)); + V_RETURN(); + } + + bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + kFrameNavOrigin0)); + V_EXPECT_TRUE(parent::OnLoadStart(browser, frame)); + V_RETURN(); + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + kFrameNavOrigin0)); + V_EXPECT_TRUE(parent::OnLoadEnd(browser, frame)); + V_RETURN(); + } + + bool OnAfterCreated(CefRefPtr browser) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, false, + std::string())); + V_EXPECT_TRUE(parent::OnAfterCreated(browser)); + V_RETURN(); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + std::string())); + V_EXPECT_TRUE(parent::OnBeforeBrowse(browser, frame)); + V_RETURN(); + } + + bool GetResourceHandler(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + std::string())); + V_EXPECT_TRUE(parent::GetResourceHandler(browser, frame)); + V_RETURN(); + } + + bool OnRendererComplete(CefRefPtr browser, + int renderer_nav, + bool renderer_result) override { + return parent::OnRendererComplete(browser, renderer_nav, renderer_result); + } + + bool Finalize() override { + return parent::Finalize(); + } +}; + +class FrameNavExpectationsRendererTestSingleNav : + public FrameNavExpectationsRendererSingleNav { + public: + typedef FrameNavExpectationsRendererSingleNav parent; + + explicit FrameNavExpectationsRendererTestSingleNav(int nav) + : parent(nav) { + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + V_DECLARE(); + // A frame should always exist in the renderer process. + if (isLoading) { + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + std::string())); + } else { + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + kFrameNavOrigin0)); + } + V_EXPECT_TRUE(parent::OnLoadingStateChange(browser, isLoading)); + V_RETURN(); + } + + bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + kFrameNavOrigin0)); + V_EXPECT_TRUE(parent::OnLoadStart(browser, frame)); + V_RETURN(); + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + kFrameNavOrigin0)); + V_EXPECT_TRUE(parent::OnLoadEnd(browser, frame)); + V_RETURN(); + } + + bool Finalize() override { + return parent::Finalize(); + } +}; + +class FrameNavExpectationsFactoryBrowserTestSingleNav : + public FrameNavExpectationsFactoryBrowser { + public: + FrameNavExpectationsFactoryBrowserTestSingleNav() {} + + FrameNavFactoryId GetID() const override { + return FNF_ID_SINGLE_NAV; + } + + bool HasMoreNavigations() const override { + return false; + } + + bool Finalize() override { + return true; + } + + protected: + scoped_ptr Create(int nav) override { + return make_scoped_ptr( + new FrameNavExpectationsBrowserTestSingleNav(nav)); + } +}; + +class FrameNavExpectationsFactoryRendererTestSingleNav : + public FrameNavExpectationsFactoryRenderer { + public: + FrameNavExpectationsFactoryRendererTestSingleNav() {} + + FrameNavFactoryId GetID() const override { + return FNF_ID_SINGLE_NAV; + } + + protected: + scoped_ptr Create(int nav) override { + return make_scoped_ptr( + new FrameNavExpectationsRendererTestSingleNav(nav)); + } +}; + +} // namespace + +// Test that single navigation works. +FRAME_TEST(SingleNav, FNF_ID_SINGLE_NAV) + + +namespace { + +// Browser process expectations for a multiple navigations. +class FrameNavExpectationsBrowserMultiNav : + public FrameNavExpectationsBrowser { + public: + explicit FrameNavExpectationsBrowserMultiNav(int nav) + : FrameNavExpectationsBrowser(nav) { + } + + ~FrameNavExpectationsBrowserMultiNav() override { + EXPECT_TRUE(got_finalize_); + } + + // Returns true if all navigation is done. + virtual bool IsNavigationDone() const =0; + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (!isLoading) + SignalCompleteIfDone(browser); + return true; + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + SignalCompleteIfDone(browser); + return true; + } + + bool OnRendererComplete(CefRefPtr browser, + int renderer_nav, + bool renderer_result) override { + EXPECT_TRUE(renderer_result); + SignalCompleteIfDone(browser); + return true; + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_FALSE(got_finalize_); + + got_finalize_.yes(); + + V_RETURN(); + } + + private: + void SignalCompleteIfDone(CefRefPtr browser) { + if (IsNavigationDone()) + SignalComplete(browser); + } + + TrackCallback got_finalize_; +}; + +// Renderer process expectations for a multiple navigations. +class FrameNavExpectationsRendererMultiNav : + public FrameNavExpectationsRenderer { + public: + explicit FrameNavExpectationsRendererMultiNav(int nav) + : FrameNavExpectationsRenderer(nav) { + } + + ~FrameNavExpectationsRendererMultiNav() override { + EXPECT_TRUE(got_finalize_); + } + + // Returns true if all navigation is done. + virtual bool IsNavigationDone() const =0; + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (!isLoading) + SignalCompleteIfDone(browser); + return true; + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + SignalCompleteIfDone(browser); + return true; + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_FALSE(got_finalize_); + + got_finalize_.yes(); + + V_RETURN(); + } + + private: + void SignalCompleteIfDone(CefRefPtr browser) { + if (IsNavigationDone()) + SignalComplete(browser); + } + + TrackCallback got_finalize_; +}; + + +// Create a URL containing the nav number. +std::string GetMultiNavURL(const std::string& origin, int nav) { + std::stringstream ss; + ss << origin << "nav" << nav << ".html"; + return ss.str(); +} + +// Extract the nav number from the URL. +int GetNavFromMultiNavURL(const std::string& url) { + const size_t start = url.find("/nav"); + const size_t end = url.find(".html", start); + EXPECT_TRUE(start < end && start > 0U); + const std::string& nav = url.substr(start + 4, end - start - 4); + return atoi(nav.c_str()); +} + +// Extract the origin from the URL. +std::string GetOriginFromMultiNavURL(const std::string& url) { + const size_t pos = url.rfind("/"); + EXPECT_TRUE(pos > 0U); + return url.substr(0, pos + 1); +} + +// Test that the multi nav harness works. +class FrameNavExpectationsBrowserTestMultiNavHarness : + public FrameNavExpectationsBrowserMultiNav { + public: + typedef FrameNavExpectationsBrowserMultiNav parent; + + explicit FrameNavExpectationsBrowserTestMultiNavHarness(int nav) + : parent(nav), + navigation_done_count_(0) { + } + + ~FrameNavExpectationsBrowserTestMultiNavHarness() override { + EXPECT_TRUE(got_finalize_); + } + + std::string GetMainURL() override { + EXPECT_FALSE(got_get_main_url_); + got_get_main_url_.yes(); + return GetMultiNavURL(kFrameNavOrigin0, nav()); + } + + std::string GetContentForURL(const std::string& url) override { + EXPECT_FALSE(got_get_content_for_url_); + got_get_content_for_url_.yes(); + EXPECT_STREQ(GetMultiNavURL(kFrameNavOrigin0, nav()).c_str(), url.c_str()); + return "Nav"; + } + + bool IsNavigationDone() const override { + navigation_done_count_++; + return got_load_state_change_done_ && got_load_end_ && + got_renderer_complete_; + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (!isLoading) { + EXPECT_FALSE(got_load_state_change_done_); + got_load_state_change_done_.yes(); + } + return parent::OnLoadingStateChange(browser, isLoading); + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_load_end_); + got_load_end_.yes(); + return parent::OnLoadEnd(browser, frame); + } + + bool OnAfterCreated(CefRefPtr browser) override { + EXPECT_FALSE(got_on_after_created_); + got_on_after_created_.yes(); + return parent::OnAfterCreated(browser); + } + + bool OnRendererComplete(CefRefPtr browser, + int renderer_nav, + bool renderer_result) override { + EXPECT_FALSE(got_renderer_complete_); + got_renderer_complete_.yes(); + EXPECT_EQ(nav(), renderer_nav); + return parent::OnRendererComplete(browser, renderer_nav, renderer_result); + } + + bool Finalize() override { + EXPECT_FALSE(got_finalize_); + got_finalize_.yes(); + + V_DECLARE(); + V_EXPECT_TRUE(got_get_main_url_); + V_EXPECT_TRUE(got_get_content_for_url_); + V_EXPECT_TRUE(got_load_state_change_done_); + V_EXPECT_TRUE(got_load_end_); + if (nav() == 0) { + V_EXPECT_TRUE(got_on_after_created_); + } else { + V_EXPECT_FALSE(got_on_after_created_); + } + V_EXPECT_TRUE(got_renderer_complete_); + V_EXPECT_TRUE(navigation_done_count_ == 3); + V_EXPECT_TRUE(parent::Finalize()); + V_RETURN(); + } + + private: + TrackCallback got_get_main_url_; + TrackCallback got_get_content_for_url_; + TrackCallback got_load_state_change_done_; + TrackCallback got_load_end_; + TrackCallback got_on_after_created_; + TrackCallback got_renderer_complete_; + mutable int navigation_done_count_; + TrackCallback got_finalize_; +}; + +class FrameNavExpectationsRendererTestMultiNavHarness : + public FrameNavExpectationsRendererMultiNav { + public: + typedef FrameNavExpectationsRendererMultiNav parent; + + explicit FrameNavExpectationsRendererTestMultiNavHarness(int nav) + : parent(nav), + navigation_done_count_(0) { + } + + ~FrameNavExpectationsRendererTestMultiNavHarness() override { + EXPECT_TRUE(got_finalize_); + } + + bool IsNavigationDone() const override { + navigation_done_count_++; + return got_load_state_change_done_ && got_load_end_; + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (!isLoading) { + EXPECT_FALSE(got_load_state_change_done_); + got_load_state_change_done_.yes(); + } + return parent::OnLoadingStateChange(browser, isLoading); + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_FALSE(got_load_end_); + got_load_end_.yes(); + return parent::OnLoadEnd(browser, frame); + } + + bool Finalize() override { + EXPECT_FALSE(got_finalize_); + got_finalize_.yes(); + + V_DECLARE(); + V_EXPECT_TRUE(got_load_state_change_done_); + V_EXPECT_TRUE(got_load_end_); + V_EXPECT_TRUE(navigation_done_count_ == 2); + V_EXPECT_TRUE(parent::Finalize()); + V_RETURN(); + } + + private: + TrackCallback got_load_state_change_done_; + TrackCallback got_load_end_; + mutable int navigation_done_count_; + TrackCallback got_finalize_; +}; + +class FrameNavExpectationsFactoryBrowserTestMultiNavHarness : + public FrameNavExpectationsFactoryBrowser { + public: + FrameNavExpectationsFactoryBrowserTestMultiNavHarness() + : get_browser_navigation_count_(0), + create_count_(0) {} + + ~FrameNavExpectationsFactoryBrowserTestMultiNavHarness() override { + EXPECT_TRUE(got_finalize_); + } + + FrameNavFactoryId GetID() const override { + return FNF_ID_MULTI_NAV_HARNESS; + } + + bool HasMoreNavigations() const override { + get_browser_navigation_count_++; + return (get_browser_navigation_count_ < kMaxMultiNavNavigations); + } + + bool Finalize() override { + EXPECT_FALSE(got_finalize_); + got_finalize_.yes(); + + V_DECLARE(); + V_EXPECT_TRUE(get_browser_navigation_count_ == kMaxMultiNavNavigations); + V_EXPECT_TRUE(create_count_ == kMaxMultiNavNavigations); + V_RETURN(); + } + + protected: + scoped_ptr Create(int nav) override { + create_count_++; + return make_scoped_ptr( + new FrameNavExpectationsBrowserTestMultiNavHarness(nav)); + } + + private: + mutable int get_browser_navigation_count_; + int create_count_; + TrackCallback got_finalize_; +}; + +class FrameNavExpectationsFactoryRendererTestMultiNavHarness : + public FrameNavExpectationsFactoryRenderer { + public: + FrameNavExpectationsFactoryRendererTestMultiNavHarness() {} + + FrameNavFactoryId GetID() const override { + return FNF_ID_MULTI_NAV_HARNESS; + } + + protected: + scoped_ptr Create(int nav) override { + return make_scoped_ptr( + new FrameNavExpectationsRendererTestMultiNavHarness(nav)); + } +}; + +} // namespace + +// Test that the multiple nav harness works. +FRAME_TEST(MultiNavHarness, FNF_ID_MULTI_NAV_HARNESS) + + +namespace { + +// Test that multiple navigation works. +class FrameNavExpectationsBrowserTestMultiNav : + public FrameNavExpectationsBrowserMultiNav { + public: + typedef FrameNavExpectationsBrowserMultiNav parent; + + explicit FrameNavExpectationsBrowserTestMultiNav(int nav) + : parent(nav) { + } + + std::string GetMainURL() override { + return GetMultiNavURL(kFrameNavOrigin0, nav()); + } + + std::string GetContentForURL(const std::string& url) override { + return "Nav"; + } + + bool IsNavigationDone() const override { + return got_load_state_change_done_ && got_load_end_ && + got_renderer_complete_; + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (!isLoading) + got_load_state_change_done_.yes(); + V_DECLARE(); + // A frame should exist in all cases except for the very first load. + if (isLoading && nav() == 0) { + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, false, + std::string())); + } else if (isLoading) { + // Expect the URL from the previous load. + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + GetPreviousMainURL())); + } else { + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + GetMainURL())); + } + V_EXPECT_TRUE(parent::OnLoadingStateChange(browser, isLoading)); + V_RETURN(); + } + + bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + GetMainURL())); + V_EXPECT_TRUE(parent::OnLoadStart(browser, frame)); + V_RETURN(); + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + got_load_end_.yes(); + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + GetMainURL())); + V_EXPECT_TRUE(parent::OnLoadEnd(browser, frame)); + V_RETURN(); + } + + bool OnAfterCreated(CefRefPtr browser) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, false, + std::string())); + V_EXPECT_TRUE(parent::OnAfterCreated(browser)); + V_RETURN(); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + std::string expected_url; + if (nav() > 0) + expected_url = GetPreviousMainURL(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + expected_url)); + V_EXPECT_TRUE(parent::OnBeforeBrowse(browser, frame)); + V_RETURN(); + } + + bool GetResourceHandler(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + std::string expected_url; + if (nav() > 0) + expected_url = GetPreviousMainURL(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + expected_url)); + V_EXPECT_TRUE(parent::GetResourceHandler(browser, frame)); + V_RETURN(); + } + + bool OnRendererComplete(CefRefPtr browser, + int renderer_nav, + bool renderer_result) override { + got_renderer_complete_.yes(); + V_DECLARE(); + V_EXPECT_TRUE(nav() == renderer_nav); + V_EXPECT_TRUE(parent::OnRendererComplete(browser, renderer_nav, + renderer_result)); + V_RETURN(); + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_TRUE(got_load_state_change_done_); + V_EXPECT_TRUE(got_load_end_); + V_EXPECT_TRUE(got_renderer_complete_); + V_EXPECT_TRUE(parent::Finalize()); + V_RETURN(); + } + + private: + // Helper for VerifySingleBrowserFrames. + std::string GetPreviousMainURL() { + EXPECT_GT(nav(), 0); + return GetMultiNavURL(kFrameNavOrigin0, nav() - 1); + } + + TrackCallback got_load_state_change_done_; + TrackCallback got_load_end_; + TrackCallback got_renderer_complete_; +}; + +class FrameNavExpectationsRendererTestMultiNav : + public FrameNavExpectationsRendererMultiNav { + public: + typedef FrameNavExpectationsRendererMultiNav parent; + + explicit FrameNavExpectationsRendererTestMultiNav(int nav) + : parent(nav) { + } + + bool IsNavigationDone() const override { + return got_load_state_change_done_ && got_load_end_; + } + + bool OnLoadingStateChange(CefRefPtr browser, + bool isLoading) override { + if (!isLoading) + got_load_state_change_done_.yes(); + V_DECLARE(); + // A frame should always exist in the renderer process. + if (isLoading) { + std::string expected_url; + if (nav() > 0) + expected_url = GetPreviousMainURL(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + expected_url)); + } else { + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, NULL, true, + GetMainURL())); + } + V_EXPECT_TRUE(parent::OnLoadingStateChange(browser, isLoading)); + V_RETURN(); + } + + bool OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + GetMainURL())); + V_EXPECT_TRUE(parent::OnLoadStart(browser, frame)); + V_RETURN(); + } + + bool OnLoadEnd(CefRefPtr browser, + CefRefPtr frame) override { + got_load_end_.yes(); + V_DECLARE(); + V_EXPECT_TRUE(VerifySingleBrowserFrames(browser, frame, true, + GetMainURL())); + V_EXPECT_TRUE(parent::OnLoadEnd(browser, frame)); + V_RETURN(); + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_TRUE(got_load_state_change_done_); + V_EXPECT_TRUE(got_load_end_); + V_EXPECT_TRUE(parent::Finalize()); + V_RETURN(); + } + + private: + // Helpers for calling VerifySingleBrowserFrames. + std::string GetMainURL() const { + return GetMultiNavURL(kFrameNavOrigin0, nav()); + } + std::string GetPreviousMainURL() { + EXPECT_GT(nav(), 0); + return GetMultiNavURL(kFrameNavOrigin0, nav() - 1); + } + + TrackCallback got_load_state_change_done_; + TrackCallback got_load_end_; +}; + +class FrameNavExpectationsFactoryBrowserTestMultiNav : + public FrameNavExpectationsFactoryBrowser { + public: + FrameNavExpectationsFactoryBrowserTestMultiNav() + : nav_count_(0) {} + + FrameNavFactoryId GetID() const override { + return FNF_ID_MULTI_NAV; + } + + bool HasMoreNavigations() const override { + return (nav_count_ < kMaxMultiNavNavigations); + } + + bool Finalize() override { + V_DECLARE(); + V_EXPECT_TRUE(nav_count_ == kMaxMultiNavNavigations); + V_RETURN(); + } + + protected: + scoped_ptr Create(int nav) override { + nav_count_++; + return make_scoped_ptr( + new FrameNavExpectationsBrowserTestMultiNav(nav)); + } + + private: + int nav_count_; +}; + +class FrameNavExpectationsFactoryRendererTestMultiNav : + public FrameNavExpectationsFactoryRenderer { + public: + FrameNavExpectationsFactoryRendererTestMultiNav() {} + + FrameNavFactoryId GetID() const override { + return FNF_ID_MULTI_NAV; + } + + protected: + scoped_ptr Create(int nav) override { + return make_scoped_ptr( + new FrameNavExpectationsRendererTestMultiNav(nav)); + } +}; + +} // namespace + +// Test that multiple navigation works. +FRAME_TEST(MultiNav, FNF_ID_MULTI_NAV) + + +namespace { + +const char kFrame0Name[] = ""; +const char kFrame1Name[] = "nav2"; +const char kFrame2Name[] = "-->"; + +bool VerifyBrowserIframe(CefRefPtr browser, + CefRefPtr frame, + const std::string& origin, + int frame_number) { + V_DECLARE(); + + // frame0 contains frame1 contains frame2. + CefRefPtr frame0, frame1, frame2; + CefRefPtr frame0b, frame1b, frame2b; + int64 frame0id, frame1id, frame2id; + std::string frame0url, frame1url, frame2url; + + // Find frames by name. + frame0 = browser->GetFrame(kFrame0Name); + V_EXPECT_TRUE(frame0.get()); + frame1 = browser->GetFrame(kFrame1Name); + V_EXPECT_TRUE(frame1.get()); + frame2 = browser->GetFrame(kFrame2Name); + V_EXPECT_TRUE(frame2.get()); + + // Verify that the name matches. + V_EXPECT_TRUE(frame0->GetName().ToString() == kFrame0Name); + V_EXPECT_TRUE(frame1->GetName().ToString() == kFrame1Name); + V_EXPECT_TRUE(frame2->GetName().ToString() == kFrame2Name); + + // Verify that the URL matches. + frame0url = GetMultiNavURL(origin, 0); + V_EXPECT_TRUE(frame0->GetURL() == frame0url); + frame1url = GetMultiNavURL(origin, 1); + V_EXPECT_TRUE(frame1->GetURL() == frame1url); + frame2url = GetMultiNavURL(origin, 2); + V_EXPECT_TRUE(frame2->GetURL() == frame2url); + + // Verify that the frame id is valid. + frame0id = frame0->GetIdentifier(); + V_EXPECT_TRUE(frame0id > 0); + frame1id = frame1->GetIdentifier(); + V_EXPECT_TRUE(frame1id > 0); + frame2id = frame2->GetIdentifier(); + V_EXPECT_TRUE(frame2id > 0); + + // Verify that the current frame has the correct id. + if (frame_number == 0) { + V_EXPECT_TRUE(frame->GetIdentifier() == frame0id); + } else if (frame_number == 1) { + V_EXPECT_TRUE(frame->GetIdentifier() == frame1id); + } else if (frame_number == 2) { + V_EXPECT_TRUE(frame->GetIdentifier() == frame2id); + } + + // Find frames by id. + frame0b = browser->GetFrame(frame0->GetIdentifier()); + V_EXPECT_TRUE(frame0b.get()); + frame1b = browser->GetFrame(frame1->GetIdentifier()); + V_EXPECT_TRUE(frame1b.get()); + frame2b = browser->GetFrame(frame2->GetIdentifier()); + V_EXPECT_TRUE(frame2b.get()); + + // Verify that the id matches. + V_EXPECT_TRUE(frame0b->GetIdentifier() == frame0id); + V_EXPECT_TRUE(frame1b->GetIdentifier() == frame1id); + V_EXPECT_TRUE(frame2b->GetIdentifier() == frame2id); + + V_EXPECT_TRUE(browser->GetFrameCount() == 3U); + + // Verify the GetFrameNames result. + std::vector names; + browser->GetFrameNames(names); + V_EXPECT_TRUE(names.size() == 3U); + V_EXPECT_TRUE(names[0].ToString() == kFrame0Name); + V_EXPECT_TRUE(names[1].ToString() == kFrame1Name); + V_EXPECT_TRUE(names[2].ToString() == kFrame2Name); + + // Verify the GetFrameIdentifiers result. + std::vector idents; + browser->GetFrameIdentifiers(idents); + V_EXPECT_TRUE(idents.size() == 3U); + V_EXPECT_TRUE(idents[0] == frame0->GetIdentifier()); + V_EXPECT_TRUE(idents[1] == frame1->GetIdentifier()); + V_EXPECT_TRUE(idents[2] == frame2->GetIdentifier()); + + // Verify parent hierarchy. + V_EXPECT_FALSE(frame0->GetParent().get()); + V_EXPECT_TRUE(frame1->GetParent()->GetIdentifier() == frame0id); + V_EXPECT_TRUE(frame2->GetParent()->GetIdentifier() == frame1id); + + V_RETURN(); +} + +// Test that nested iframes work. +class FrameNavExpectationsBrowserTestNestedIframes : + public FrameNavExpectationsBrowserMultiNav { + public: + typedef FrameNavExpectationsBrowserMultiNav parent; + + FrameNavExpectationsBrowserTestNestedIframes(int nav, bool same_origin) + : parent(nav), + same_origin_(same_origin) { + // In the browser process we can rely on the |nav| value to determine the + // origin. + if (same_origin) { + origin_ = kFrameNavOrigin0; + } else switch (nav) { + case 0: + origin_ = kFrameNavOrigin0; + break; + case 1: + origin_ = kFrameNavOrigin1; + break; + case 2: + origin_ = kFrameNavOrigin2; + break; + default: + EXPECT_TRUE(false); // Not reached. + break; + } + } + + std::string GetMainURL() override { + // Load the first (main) frame. + return GetMultiNavURL(origin_, 0); + } + + std::string GetContentForURL(const std::string& url) override { + const int frame_number = GetNavFromMultiNavURL(url); + switch (frame_number) { + case 0: + // Frame 0. Contains a named iframe. + return "Nav1\n"; + } + + html += ""; + return html; + } + + void OnNotify(CefRefPtr browser, + CefRefPtr frame, + const std::string& message) { + EXPECT_TRUE(finalized_); + if (!running_) + running_ = true; + + MultiQueryManager* manager = GetManager(browser, frame); + manager->OnNotify(browser, frame, message); + } + + bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) override { + EXPECT_TRUE(finalized_); + if (!running_) + running_ = true; + + MultiQueryManager* manager = GetManager(browser, frame); + return manager->OnQuery(browser, frame, query_id, request, persistent, + callback); + } + + void OnQueryCanceled(CefRefPtr browser, + CefRefPtr frame, + int64 query_id) override { + EXPECT_TRUE(finalized_); + if (!running_) + running_ = true; + + MultiQueryManager* manager = GetManager(browser, frame); + manager->OnQueryCanceled(browser, frame, query_id); + } + + void OnManualQueriesCompleted(MultiQueryManager* manager) override { + const int size = static_cast(manager_map_.size()); + EXPECT_LT(manual_complete_count_, size); + if (++manual_complete_count_ == size) { + running_ = false; + + // Notify observers. + if (!observer_set_.empty()) { + // Use a copy of the set in case an Observer is removed while we're + // iterating. + ObserverSet observer_set = observer_set_; + + ObserverSet::const_iterator it = observer_set.begin(); + for (; it != observer_set.end(); ++it) { + (*it)->OnMapManualQueriesCompleted(this); + } + } + } + } + + void OnAllQueriesCompleted(MultiQueryManager* manager) override { + const int size = static_cast(manager_map_.size()); + EXPECT_LT(total_complete_count_, size); + if (++total_complete_count_ == size) { + running_ = false; + + // Notify observers. + if (!observer_set_.empty()) { + // Use a copy of the set in case an Observer is removed while we're + // iterating. + ObserverSet observer_set = observer_set_; + + ObserverSet::const_iterator it = observer_set.begin(); + for (; it != observer_set.end(); ++it) { + (*it)->OnMapAllQueriesCompleted(this); + } + } + } + } + + bool AllComplete() const { + EXPECT_TRUE(finalized_); + + URLManagerMap::const_iterator it = manager_map_.begin(); + for (; it != manager_map_.end(); ++it) { + if (!it->second->IsAllComplete()) + return false; + } + return true; + } + + void AssertAllComplete() const { + EXPECT_TRUE(finalized_); + EXPECT_FALSE(running_); + + URLManagerMap::const_iterator it = manager_map_.begin(); + for (; it != manager_map_.end(); ++it) + it->second->AssertAllComplete(); + } + + bool HasAutoQueries() const { + if (manager_map_.empty()) + return false; + + URLManagerMap::const_iterator it = manager_map_.begin(); + for (; it != manager_map_.end(); ++it) { + if (it->second->HasAutoQueries()) + return true; + } + + return false; + } + + MultiQueryManager* GetManager(CefRefPtr browser, + CefRefPtr frame) const { + const std::string& url = frame->GetURL(); + URLManagerMap::const_iterator it = manager_map_.find(url); + EXPECT_NE(it, manager_map_.end()); + return it->second; + } + + void RemoveAllManagers() { + if (manager_map_.empty()) + return; + + URLManagerMap::const_iterator it = manager_map_.begin(); + for (; it != manager_map_.end(); ++it) + delete it->second; + manager_map_.clear(); + } + + std::string GetURLForManager(MultiQueryManager* manager) const { + if (!manager_map_.empty()) { + URLManagerMap::const_iterator it = manager_map_.begin(); + for (; it != manager_map_.end(); ++it) { + if (it->second == manager) + return it->first; + } + } + return std::string(); + } + + static std::string GetNameForURL(const std::string& url) { + // Extract the file name without extension. + int pos1 = static_cast(url.rfind("/")); + int pos2 = static_cast(url.rfind(".")); + EXPECT_TRUE(pos1 >= 0 && pos2 >= 0 && pos1 < pos2); + return url.substr(pos1 + 1, pos2 - pos1 - 1); + } + + private: + // Map of page URL to MultiQueryManager instance. + typedef std::map URLManagerMap; + URLManagerMap manager_map_; + + typedef std::set ObserverSet; + ObserverSet observer_set_; + + // Set to true after all query managers have been added. + bool finalized_; + // Set to true while queries are pending. + bool running_; + + // Number of managers that have completed. + int manual_complete_count_; + int total_complete_count_; +}; + +// Test multiple queries in a single page load with multiple frames. +class MultiQueryMultiFrameTestHandler : + public SingleLoadTestHandler, + public MultiQueryManagerMap::Observer { + public: + MultiQueryMultiFrameTestHandler(bool synchronous, bool cancel_with_subnav) + : synchronous_(synchronous), + cancel_with_subnav_(cancel_with_subnav) { + manager_map_.AddObserver(this); + } + + void AddOtherResources() override { + AddSubFrameResource("sub1"); + AddSubFrameResource("sub2"); + AddSubFrameResource("sub3"); + manager_map_.Finalize(); + + if (manager_map_.HasAutoQueries()) { + cancel_url_ = std::string(kTestDomain1) + "cancel.html"; + AddResource(cancel_url_, "cancel", "text/html"); + } + } + + std::string GetMainHTML() override { + return manager_map_.GetMainHTML(); + } + + void OnNotify(CefRefPtr browser, + CefRefPtr frame, + const std::string& message) override { + AssertMainBrowser(browser); + EXPECT_FALSE(frame->IsMain()); + + manager_map_.OnNotify(browser, frame, message); + } + + bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) override { + AssertMainBrowser(browser); + EXPECT_FALSE(frame->IsMain()); + + return manager_map_.OnQuery(browser, frame, query_id, request, persistent, + callback); + } + + void OnQueryCanceled(CefRefPtr browser, + CefRefPtr frame, + int64 query_id) override { + AssertMainBrowser(browser); + EXPECT_FALSE(frame->IsMain()); + + manager_map_.OnQueryCanceled(browser, frame, query_id); + } + + void OnMapManualQueriesCompleted(MultiQueryManagerMap* map) override { + EXPECT_EQ(map, &manager_map_); + if (manager_map_.HasAutoQueries()) { + CefRefPtr frame = GetBrowser()->GetMainFrame(); + + // Navigate somewhere else to terminate the auto queries. + if (cancel_with_subnav_) { + // Navigate each subframe individually. + const std::string js = + "document.getElementById('sub1').src = '" + cancel_url_ + "';" + "document.getElementById('sub2').src = '" + cancel_url_ + "';" + "document.getElementById('sub3').src = '" + cancel_url_ + "';"; + + frame->ExecuteJavaScript(js, frame->GetURL(), 0); + } else { + // Navigate the main frame. + frame->LoadURL(cancel_url_); + } + } + } + + void OnMapAllQueriesCompleted(MultiQueryManagerMap* map) override { + EXPECT_EQ(map, &manager_map_); + DestroyTest(); + } + + void DestroyTest() override { + manager_map_.AssertAllComplete(); + TestHandler::DestroyTest(); + } + + private: + void AddSubFrameResource(const std::string& name) { + const std::string& url = std::string(kTestDomain1) + name + ".html"; + + MultiQueryManager* manager = manager_map_.CreateManager(url, synchronous_); + MakeTestQueries(manager, false, 100); + + const std::string& html = manager->GetHTML(false, false); + AddResource(url, html, "text/html"); + } + + const bool synchronous_; + const bool cancel_with_subnav_; + + MultiQueryManagerMap manager_map_; + + std::string cancel_url_; +}; + +} // namespace + +// Test that multiple frames can run many queries successfully in a synchronous +// manner. +TEST(MessageRouterTest, MultiQueryMultiFrameSync) { + CefRefPtr handler = + new MultiQueryMultiFrameTestHandler(true, false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple frames can run many queries successfully in an +// asynchronous manner. +TEST(MessageRouterTest, MultiQueryMultiFrameAsync) { + CefRefPtr handler = + new MultiQueryMultiFrameTestHandler(false, false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple frames can run many queries successfully in a synchronous +// manner. Cancel auto queries with sub-frame navigation. +TEST(MessageRouterTest, MultiQueryMultiFrameSyncSubnavCancel) { + CefRefPtr handler = + new MultiQueryMultiFrameTestHandler(true, true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple frames can run many queries successfully in an +// asynchronous manner. Cancel auto queries with sub-frame navigation. +TEST(MessageRouterTest, MultiQueryMultiFrameAsyncSubnavCancel) { + CefRefPtr handler = + new MultiQueryMultiFrameTestHandler(false, true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +// Implementation of MRTestHandler that loads multiple pages and/or browsers and +// executes multiple queries. +class MultiQueryMultiLoadTestHandler : + public MRTestHandler, + public CefMessageRouterBrowserSide::Handler, + public MultiQueryManagerMap::Observer, + public MultiQueryManager::Observer { + public: + MultiQueryMultiLoadTestHandler(bool some, bool synchronous) + : some_(some), + synchronous_(synchronous) { + manager_map_.AddObserver(this); + } + + void OnNotify(CefRefPtr browser, + CefRefPtr frame, + const std::string& message) override { + manager_map_.OnNotify(browser, frame, message); + } + + bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) override { + return manager_map_.OnQuery(browser, frame, query_id, request, persistent, + callback); + } + + void OnQueryCanceled(CefRefPtr browser, + CefRefPtr frame, + int64 query_id) override { + manager_map_.OnQueryCanceled(browser, frame, query_id); + } + + void OnMapManualQueriesCompleted(MultiQueryManagerMap* map) override { + EXPECT_EQ(map, &manager_map_); + if (manager_map_.HasAutoQueries()) { + // Navigate all browsers somewhere else to terminate the auto queries. + BrowserMap map; + GetAllBrowsers(&map); + + BrowserMap::const_iterator it = map.begin(); + for (; it != map.end(); ++it) { + it->second->GetMainFrame()->LoadURL(cancel_url_); + } + } + } + + void OnMapAllQueriesCompleted(MultiQueryManagerMap* map) override { + EXPECT_EQ(map, &manager_map_); + DestroyTest(); + } + + void DestroyTest() override { + manager_map_.AssertAllComplete(); + TestHandler::DestroyTest(); + } + + protected: + void AddHandlers( + CefRefPtr message_router) override { + message_router->AddHandler(this, false); + } + + void AddManagedResource(const std::string& url, + bool assert_total, + bool assert_browser) { + MultiQueryManager* manager = manager_map_.CreateManager(url, synchronous_); + manager->AddObserver(this); + MakeTestQueries(manager, some_, 75); + + const std::string& html = manager->GetHTML(assert_total, assert_browser); + AddResource(url, html, "text/html"); + } + + void Finalize() { + manager_map_.Finalize(); + + if (manager_map_.HasAutoQueries()) { + cancel_url_ = std::string(kTestDomain1) + "cancel.html"; + AddResource(cancel_url_, "cancel", "text/html"); + } + } + + MultiQueryManagerMap manager_map_; + + private: + const bool some_; + const bool synchronous_; + + std::string cancel_url_; +}; + +// Test multiple browsers that send queries at the same time. +class MultiQueryMultiBrowserTestHandler : public MultiQueryMultiLoadTestHandler { + public: + MultiQueryMultiBrowserTestHandler(bool synchronous, bool same_origin) + : MultiQueryMultiLoadTestHandler(false, synchronous), + same_origin_(same_origin) { + } + + protected: + void RunMRTest() override { + const std::string& url1 = std::string(kTestDomain1) + "browser1.html"; + const std::string& url2 = + std::string(same_origin_ ? kTestDomain1 : kTestDomain2) + + "browser2.html"; + const std::string& url3 = + std::string(same_origin_ ? kTestDomain1 : kTestDomain3) + + "browser3.html"; + + AddManagedResource(url1, false, true); + AddManagedResource(url2, false, true); + AddManagedResource(url3, false, true); + Finalize(); + + // Create 2 browsers simultaniously. + CreateBrowser(url1, NULL); + CreateBrowser(url2, NULL); + CreateBrowser(url3, NULL); + } + + private: + bool same_origin_; +}; + +} // namespace + +// Test that multiple browsers can query simultaniously from the same origin. +TEST(MessageRouterTest, MultiQueryMultiBrowserSameOriginSync) { + CefRefPtr handler = + new MultiQueryMultiBrowserTestHandler(true, true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple browsers can query simultaniously from the same origin. +TEST(MessageRouterTest, MultiQueryMultiBrowserSameOriginAsync) { + CefRefPtr handler = + new MultiQueryMultiBrowserTestHandler(false, true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple browsers can query simultaniously from different origins. +TEST(MessageRouterTest, MultiQueryMultiBrowserDifferentOriginSync) { + CefRefPtr handler = + new MultiQueryMultiBrowserTestHandler(true, false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple browsers can query simultaniously from different origins. +TEST(MessageRouterTest, MultiQueryMultiBrowserDifferentOriginAsync) { + CefRefPtr handler = + new MultiQueryMultiBrowserTestHandler(false, false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +// Test multiple navigations that send queries sequentially. +class MultiQueryMultiNavigateTestHandler : public MultiQueryMultiLoadTestHandler { + public: + MultiQueryMultiNavigateTestHandler(bool synchronous, bool same_origin) + : MultiQueryMultiLoadTestHandler(false, synchronous), + same_origin_(same_origin) { + } + + void OnManualQueriesCompleted(MultiQueryManager* manager) override { + const std::string& url = manager_map_.GetURLForManager(manager); + if (url == url1_) // 2. Load the 2nd url. + GetBrowser()->GetMainFrame()->LoadURL(url2_); + else if (url == url2_) // 3. Load the 3rd url. + GetBrowser()->GetMainFrame()->LoadURL(url3_); + } + + protected: + void RunMRTest() override { + url1_ = std::string(kTestDomain1) + "browser1.html"; + url2_ = std::string(same_origin_ ? kTestDomain1 : kTestDomain2) + + "browser2.html"; + url3_ = std::string(same_origin_ ? kTestDomain1 : kTestDomain3) + + "browser3.html"; + + AddManagedResource(url1_, true, true); + AddManagedResource(url2_, true, true); + AddManagedResource(url3_, true, true); + Finalize(); + + // 1. Load the 1st url. + CreateBrowser(url1_, NULL); + } + + private: + bool same_origin_; + + std::string url1_; + std::string url2_; + std::string url3_; +}; + +} // namespace + +// Test that multiple navigations can query from the same origin. +TEST(MessageRouterTest, MultiQueryMultiNavigateSameOriginSync) { + CefRefPtr handler = + new MultiQueryMultiNavigateTestHandler(true, true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple navigations can query from the same origin. +TEST(MessageRouterTest, MultiQueryMultiNavigateSameOriginAsync) { + CefRefPtr handler = + new MultiQueryMultiNavigateTestHandler(false, true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple navigations can query from different origins. +TEST(MessageRouterTest, MultiQueryMultiNavigateDifferentOriginSync) { + CefRefPtr handler = + new MultiQueryMultiNavigateTestHandler(true, false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that multiple navigations can query from different origins. +TEST(MessageRouterTest, MultiQueryMultiNavigateDifferentOriginAsync) { + CefRefPtr handler = + new MultiQueryMultiNavigateTestHandler(false, false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} diff --git a/tests/unittests/navigation_unittest.cc b/tests/unittests/navigation_unittest.cc new file mode 100644 index 000000000..3d21f8c0d --- /dev/null +++ b/tests/unittests/navigation_unittest.cc @@ -0,0 +1,2085 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/base/cef_bind.h" +#include "include/cef_callback.h" +#include "include/cef_scheme.h" +#include "include/wrapper/cef_closure_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_util.h" + +using client::ClientApp; + +namespace { + +const char kHNav1[] = "http://tests-hnav/nav1.html"; +const char kHNav2[] = "http://tests-hnav/nav2.html"; +const char kHNav3[] = "http://tests-hnav/nav3.html"; +const char kHistoryNavMsg[] = "NavigationTest.HistoryNav"; + +enum NavAction { + NA_LOAD = 1, + NA_BACK, + NA_FORWARD, + NA_CLEAR +}; + +typedef struct { + NavAction action; // What to do + const char* target; // Where to be after navigation + bool can_go_back; // After navigation, can go back? + bool can_go_forward; // After navigation, can go forward? +} NavListItem; + +// Array of navigation actions: X = current page, . = history exists +static NavListItem kHNavList[] = { + // kHNav1 | kHNav2 | kHNav3 + {NA_LOAD, kHNav1, false, false}, // X + {NA_LOAD, kHNav2, true, false}, // . X + {NA_BACK, kHNav1, false, true}, // X . + {NA_FORWARD, kHNav2, true, false}, // . X + {NA_LOAD, kHNav3, true, false}, // . . X + {NA_BACK, kHNav2, true, true}, // . X . + // TODO(cef): Enable once ClearHistory is implemented + // {NA_CLEAR, kHNav2, false, false}, // X +}; + +#define NAV_LIST_SIZE() (sizeof(kHNavList) / sizeof(NavListItem)) + +bool g_history_nav_test = false; + +// Browser side. +class HistoryNavBrowserTest : public ClientApp::BrowserDelegate { + public: + HistoryNavBrowserTest() {} + + void OnBeforeChildProcessLaunch( + CefRefPtr app, + CefRefPtr command_line) override { + if (!g_history_nav_test) + return; + + // Indicate to the render process that the test should be run. + command_line->AppendSwitchWithValue("test", kHistoryNavMsg); + } + + protected: + IMPLEMENT_REFCOUNTING(HistoryNavBrowserTest); +}; + +// Renderer side. +class HistoryNavRendererTest : public ClientApp::RenderDelegate, + public CefLoadHandler { + public: + HistoryNavRendererTest() + : run_test_(false), + nav_(0) {} + + void OnRenderThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) override { + if (!g_history_nav_test) { + // Check that the test should be run. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + const std::string& test = command_line->GetSwitchValue("test"); + if (test != kHistoryNavMsg) + return; + } + + run_test_ = true; + } + + CefRefPtr GetLoadHandler( + CefRefPtr app) override { + if (!run_test_) + return NULL; + + return this; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + const NavListItem& item = kHNavList[nav_]; + + const std::string& url = browser->GetMainFrame()->GetURL(); + if (isLoading) { + got_loading_state_start_.yes(); + + EXPECT_STRNE(item.target, url.c_str()); + + if (nav_ > 0) { + const NavListItem& last_item = kHNavList[nav_ - 1]; + EXPECT_EQ(last_item.can_go_back, browser->CanGoBack()); + EXPECT_EQ(last_item.can_go_back, canGoBack); + EXPECT_EQ(last_item.can_go_forward, browser->CanGoForward()); + EXPECT_EQ(last_item.can_go_forward, canGoForward); + } else { + EXPECT_FALSE(browser->CanGoBack()); + EXPECT_FALSE(canGoBack); + EXPECT_FALSE(browser->CanGoForward()); + EXPECT_FALSE(canGoForward); + } + } else { + got_loading_state_end_.yes(); + + EXPECT_STREQ(item.target, url.c_str()); + + EXPECT_EQ(item.can_go_back, browser->CanGoBack()); + EXPECT_EQ(item.can_go_back, canGoBack); + EXPECT_EQ(item.can_go_forward, browser->CanGoForward()); + EXPECT_EQ(item.can_go_forward, canGoForward); + + SendTestResultsIfDone(browser); + } + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + const NavListItem& item = kHNavList[nav_]; + + got_load_start_.yes(); + + const std::string& url = frame->GetURL(); + EXPECT_STREQ(item.target, url.c_str()); + + EXPECT_EQ(item.can_go_back, browser->CanGoBack()); + EXPECT_EQ(item.can_go_forward, browser->CanGoForward()); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + const NavListItem& item = kHNavList[nav_]; + + got_load_end_.yes(); + + const std::string& url = frame->GetURL(); + EXPECT_STREQ(item.target, url.c_str()); + + EXPECT_EQ(item.can_go_back, browser->CanGoBack()); + EXPECT_EQ(item.can_go_forward, browser->CanGoForward()); + + SendTestResultsIfDone(browser); + } + + bool OnBeforeNavigation(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + cef_navigation_type_t navigation_type, + bool is_redirect) override { + if (!run_test_) + return false; + + const NavListItem& item = kHNavList[nav_]; + + std::string url = request->GetURL(); + EXPECT_STREQ(item.target, url.c_str()); + + EXPECT_EQ(RT_SUB_RESOURCE, request->GetResourceType()); + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + + if (item.action == NA_LOAD) + EXPECT_EQ(NAVIGATION_OTHER, navigation_type); + else if (item.action == NA_BACK || item.action == NA_FORWARD) + EXPECT_EQ(NAVIGATION_BACK_FORWARD, navigation_type); + + if (nav_ > 0) { + const NavListItem& last_item = kHNavList[nav_ - 1]; + EXPECT_EQ(last_item.can_go_back, browser->CanGoBack()); + EXPECT_EQ(last_item.can_go_forward, browser->CanGoForward()); + } else { + EXPECT_FALSE(browser->CanGoBack()); + EXPECT_FALSE(browser->CanGoForward()); + } + + return false; + } + + protected: + void SendTestResultsIfDone(CefRefPtr browser) { + if (got_load_end_ && got_loading_state_end_) + SendTestResults(browser); + } + + // Send the test results. + void SendTestResults(CefRefPtr browser) { + EXPECT_TRUE(got_loading_state_start_); + EXPECT_TRUE(got_loading_state_end_); + EXPECT_TRUE(got_load_start_); + EXPECT_TRUE(got_load_end_); + + // Check if the test has failed. + bool result = !TestFailed(); + + // Return the result to the browser process. + CefRefPtr return_msg = + CefProcessMessage::Create(kHistoryNavMsg); + CefRefPtr args = return_msg->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->SetInt(0, nav_)); + EXPECT_TRUE(args->SetBool(1, result)); + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, return_msg)); + + // Reset the test results for the next navigation. + got_loading_state_start_.reset(); + got_loading_state_end_.reset(); + got_load_start_.reset(); + got_load_end_.reset(); + + nav_++; + } + + bool run_test_; + int nav_; + + TrackCallback got_loading_state_start_; + TrackCallback got_loading_state_end_; + TrackCallback got_load_start_; + TrackCallback got_load_end_; + + IMPLEMENT_REFCOUNTING(HistoryNavRendererTest); +}; + +class NavigationEntryVisitor : public CefNavigationEntryVisitor { + public: + NavigationEntryVisitor(int nav, TrackCallback* callback) + : nav_(nav), + callback_(callback), + expected_total_(0), + expected_current_index_(-1), + expected_forwardback_(), + callback_count_(0) { + // Determine the expected values. + for (int i = 0; i <= nav_; ++i) { + if (kHNavList[i].action == NA_LOAD) { + expected_total_++; + expected_current_index_++; + } else if (kHNavList[i].action == NA_BACK) { + expected_current_index_--; + } else if (kHNavList[i].action == NA_FORWARD) { + expected_current_index_++; + } + expected_forwardback_[expected_current_index_] = + (kHNavList[i].action != NA_LOAD); + } + } + + ~NavigationEntryVisitor() override { + EXPECT_EQ(callback_count_, expected_total_); + callback_->yes(); + } + + bool Visit(CefRefPtr entry, + bool current, + int index, + int total) override { + // Only 3 loads total. + EXPECT_LT(index, 3); + EXPECT_LE(total, 3); + + EXPECT_EQ((expected_current_index_ == index), current); + EXPECT_EQ(callback_count_, index); + EXPECT_EQ(expected_total_, total); + + std::string expected_url; + std::string expected_title; + if (index == 0) { + expected_url = kHNav1; + expected_title = "Nav1"; + } else if (index == 1) { + expected_url = kHNav2; + expected_title = "Nav2"; + } else if (index == 2) { + expected_url = kHNav3; + expected_title = "Nav3"; + } + + EXPECT_TRUE(entry->IsValid()); + EXPECT_STREQ(expected_url.c_str(), entry->GetURL().ToString().c_str()); + EXPECT_STREQ(expected_url.c_str(), + entry->GetDisplayURL().ToString().c_str()); + EXPECT_STREQ(expected_url.c_str(), + entry->GetOriginalURL().ToString().c_str()); + EXPECT_STREQ(expected_title.c_str(), entry->GetTitle().ToString().c_str()); + + if (expected_forwardback_[index]) + EXPECT_EQ(TT_EXPLICIT | TT_FORWARD_BACK_FLAG, entry->GetTransitionType()); + else + EXPECT_EQ(TT_EXPLICIT, entry->GetTransitionType()); + + EXPECT_FALSE(entry->HasPostData()); + EXPECT_TRUE(entry->GetFrameName().empty()); + EXPECT_GT(entry->GetCompletionTime().GetTimeT(), 0); + EXPECT_EQ(200, entry->GetHttpStatusCode()); + + callback_count_++; + return true; + } + + private: + const int nav_; + TrackCallback* callback_; + int expected_total_; + int expected_current_index_; + bool expected_forwardback_[3]; // Only 3 loads total. + int callback_count_; + + IMPLEMENT_REFCOUNTING(NavigationEntryVisitor); +}; + +// Browser side. +class HistoryNavTestHandler : public TestHandler { + public: + HistoryNavTestHandler() + : nav_(0), + load_end_confirmation_(false), + renderer_confirmation_(false) {} + + void RunTest() override { + // Add the resources that we will navigate to/from. + AddResource(kHNav1, + "Nav1Nav1", + "text/html"); + AddResource(kHNav2, + "Nav2Nav2", + "text/html"); + AddResource(kHNav3, + "Nav3Nav3", + "text/html"); + + // Create the browser. + CreateBrowser(CefString()); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void RunNav(CefRefPtr browser) { + if (nav_ == NAV_LIST_SIZE()) { + // End of the nav list. + DestroyTest(); + return; + } + + const NavListItem& item = kHNavList[nav_]; + + // Perform the action. + switch (item.action) { + case NA_LOAD: + browser->GetMainFrame()->LoadURL(item.target); + break; + case NA_BACK: + browser->GoBack(); + break; + case NA_FORWARD: + browser->GoForward(); + break; + case NA_CLEAR: + // TODO(cef): Enable once ClearHistory is implemented + // browser->GetHost()->ClearHistory(); + // Not really a navigation action so go to the next one. + nav_++; + RunNav(browser); + break; + default: + break; + } + } + + void RunNextNavIfReady(CefRefPtr browser) { + if (load_end_confirmation_ && renderer_confirmation_) { + load_end_confirmation_ = false; + renderer_confirmation_ = false; + nav_++; + RunNav(browser); + } + } + + void OnAfterCreated(CefRefPtr browser) override { + TestHandler::OnAfterCreated(browser); + + RunNav(browser); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + const NavListItem& item = kHNavList[nav_]; + + got_before_browse_[nav_].yes(); + + std::string url = request->GetURL(); + EXPECT_STREQ(item.target, url.c_str()); + + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + if (item.action == NA_LOAD) + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + else if (item.action == NA_BACK || item.action == NA_FORWARD) + EXPECT_EQ(TT_EXPLICIT | TT_FORWARD_BACK_FLAG, request->GetTransitionType()); + + if (nav_ > 0) { + const NavListItem& last_item = kHNavList[nav_ - 1]; + EXPECT_EQ(last_item.can_go_back, browser->CanGoBack()); + EXPECT_EQ(last_item.can_go_forward, browser->CanGoForward()); + } else { + EXPECT_FALSE(browser->CanGoBack()); + EXPECT_FALSE(browser->CanGoForward()); + } + + return false; + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + const NavListItem& item = kHNavList[nav_]; + + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + if (item.action == NA_LOAD) + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + else if (item.action == NA_BACK || item.action == NA_FORWARD) + EXPECT_EQ(TT_EXPLICIT | TT_FORWARD_BACK_FLAG, request->GetTransitionType()); + + got_before_resource_load_[nav_].yes(); + + std::string url = request->GetURL(); + if (url == item.target) + got_correct_target_[nav_].yes(); + + return false; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + const NavListItem& item = kHNavList[nav_]; + + got_loading_state_change_[nav_].yes(); + + if (item.can_go_back == canGoBack) + got_correct_can_go_back_[nav_].yes(); + if (item.can_go_forward == canGoForward) + got_correct_can_go_forward_[nav_].yes(); + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + if(browser->IsPopup() || !frame->IsMain()) + return; + + const NavListItem& item = kHNavList[nav_]; + + got_load_start_[nav_].yes(); + + std::string url1 = browser->GetMainFrame()->GetURL(); + std::string url2 = frame->GetURL(); + if (url1 == item.target && url2 == item.target) + got_correct_load_start_url_[nav_].yes(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + if (browser->IsPopup() || !frame->IsMain()) + return; + + const NavListItem& item = kHNavList[nav_]; + + got_load_end_[nav_].yes(); + + // Test that navigation entries are correct. + CefRefPtr visitor = + new NavigationEntryVisitor(nav_, &got_correct_history_[nav_]); + browser->GetHost()->GetNavigationEntries(visitor.get(), false); + visitor = NULL; + + std::string url1 = browser->GetMainFrame()->GetURL(); + std::string url2 = frame->GetURL(); + if (url1 == item.target && url2 == item.target) + got_correct_load_end_url_[nav_].yes(); + + if (item.can_go_back == browser->CanGoBack()) + got_correct_can_go_back2_[nav_].yes(); + if (item.can_go_forward == browser->CanGoForward()) + got_correct_can_go_forward2_[nav_].yes(); + + load_end_confirmation_ = true; + RunNextNavIfReady(browser); + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (message->GetName().ToString() == kHistoryNavMsg) { + got_before_navigation_[nav_].yes(); + + // Test that the renderer side succeeded. + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_EQ(nav_, args->GetInt(0)); + EXPECT_TRUE(args->GetBool(1)); + + renderer_confirmation_ = true; + RunNextNavIfReady(browser); + return true; + } + + // Message not handled. + return false; + } + + int nav_; + bool load_end_confirmation_; + bool renderer_confirmation_; + + TrackCallback got_before_browse_[NAV_LIST_SIZE()]; + TrackCallback got_before_navigation_[NAV_LIST_SIZE()]; + TrackCallback got_before_resource_load_[NAV_LIST_SIZE()]; + TrackCallback got_correct_target_[NAV_LIST_SIZE()]; + TrackCallback got_loading_state_change_[NAV_LIST_SIZE()]; + TrackCallback got_correct_can_go_back_[NAV_LIST_SIZE()]; + TrackCallback got_correct_can_go_forward_[NAV_LIST_SIZE()]; + TrackCallback got_load_start_[NAV_LIST_SIZE()]; + TrackCallback got_correct_load_start_url_[NAV_LIST_SIZE()]; + TrackCallback got_load_end_[NAV_LIST_SIZE()]; + TrackCallback got_correct_history_[NAV_LIST_SIZE()]; + TrackCallback got_correct_load_end_url_[NAV_LIST_SIZE()]; + TrackCallback got_correct_can_go_back2_[NAV_LIST_SIZE()]; + TrackCallback got_correct_can_go_forward2_[NAV_LIST_SIZE()]; +}; + +} // namespace + +// Verify history navigation. +TEST(NavigationTest, History) { + g_history_nav_test = true; + CefRefPtr handler = + new HistoryNavTestHandler(); + handler->ExecuteTest(); + g_history_nav_test = false; + + for (size_t i = 0; i < NAV_LIST_SIZE(); ++i) { + if (kHNavList[i].action != NA_CLEAR) { + ASSERT_TRUE(handler->got_before_browse_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_before_navigation_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_before_resource_load_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_target_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_load_start_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_load_start_url_[i]) << "i = " << i; + } + + ASSERT_TRUE(handler->got_loading_state_change_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_can_go_back_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_can_go_forward_[i]) << "i = " << i; + + if (kHNavList[i].action != NA_CLEAR) { + ASSERT_TRUE(handler->got_load_end_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_history_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_load_end_url_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_can_go_back2_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_can_go_forward2_[i]) << "i = " << i; + } + } + + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +const char kRNav1[] = "http://tests/nav1.html"; +const char kRNav2[] = "http://tests/nav2.html"; +const char kRNav3[] = "http://tests/nav3.html"; +const char kRNav4[] = "http://tests/nav4.html"; + +bool g_got_nav1_request = false; +bool g_got_nav3_request = false; +bool g_got_nav4_request = false; +bool g_got_invalid_request = false; + +class RedirectSchemeHandler : public CefResourceHandler { + public: + RedirectSchemeHandler() : offset_(0), status_(0) {} + + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + std::string url = request->GetURL(); + if (url == kRNav1) { + // Redirect using HTTP 302 + g_got_nav1_request = true; + status_ = 302; + location_ = kRNav2; + content_ = "Redirected Nav1"; + } else if (url == kRNav3) { + // Redirect using redirectUrl + g_got_nav3_request = true; + status_ = -1; + location_ = kRNav4; + content_ = "Redirected Nav3"; + } else if (url == kRNav4) { + g_got_nav4_request = true; + status_ = 200; + content_ = "Nav4"; + } + + if (status_ != 0) { + callback->Continue(); + return true; + } else { + g_got_invalid_request = true; + return false; + } + } + + void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + EXPECT_NE(status_, 0); + + response->SetStatus(status_); + response->SetMimeType("text/html"); + response_length = content_.size(); + + if (status_ == 302) { + // Redirect using HTTP 302 + EXPECT_GT(location_.size(), static_cast(0)); + response->SetStatusText("Found"); + CefResponse::HeaderMap headers; + response->GetHeaderMap(headers); + headers.insert(std::make_pair("Location", location_)); + response->SetHeaderMap(headers); + } else if (status_ == -1) { + // Rdirect using redirectUrl + EXPECT_GT(location_.size(), static_cast(0)); + redirectUrl = location_; + } + } + + void Cancel() override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + } + + bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + size_t size = content_.size(); + if (offset_ < size) { + int transfer_size = + std::min(bytes_to_read, static_cast(size - offset_)); + memcpy(data_out, content_.c_str() + offset_, transfer_size); + offset_ += transfer_size; + + bytes_read = transfer_size; + return true; + } + + return false; + } + + protected: + std::string content_; + size_t offset_; + int status_; + std::string location_; + + IMPLEMENT_REFCOUNTING(RedirectSchemeHandler); +}; + +class RedirectSchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + RedirectSchemeHandlerFactory() {} + + CefRefPtr Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + return new RedirectSchemeHandler(); + } + + IMPLEMENT_REFCOUNTING(RedirectSchemeHandlerFactory); +}; + +class RedirectTestHandler : public TestHandler { + public: + RedirectTestHandler() {} + + void RunTest() override { + // Create the browser. + CreateBrowser(kRNav1); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + // Should be called for all but the second URL. + std::string url = request->GetURL(); + + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + + if (url == kRNav1) { + got_nav1_before_resource_load_.yes(); + } else if (url == kRNav3) { + got_nav3_before_resource_load_.yes(); + } else if (url == kRNav4) { + got_nav4_before_resource_load_.yes(); + } else { + got_invalid_before_resource_load_.yes(); + } + + return false; + } + + void OnResourceRedirect(CefRefPtr browser, + CefRefPtr frame, + const CefString& old_url, + CefString& new_url) override { + // Should be called for each redirected URL. + + if (old_url == kRNav1 && new_url == kRNav2) { + // Called due to the nav1 redirect response. + got_nav1_redirect_.yes(); + + // Change the redirect to the 3rd URL. + new_url = kRNav3; + } else if (old_url == kRNav1 && new_url == kRNav3) { + // Called due to the redirect change above. + got_nav2_redirect_.yes(); + } else if (old_url == kRNav3 && new_url == kRNav4) { + // Called due to the nav3 redirect response. + got_nav3_redirect_.yes(); + } else { + got_invalid_redirect_.yes(); + } + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + // Should only be called for the final loaded URL. + std::string url = frame->GetURL(); + + if (url == kRNav4) { + got_nav4_load_start_.yes(); + } else { + got_invalid_load_start_.yes(); + } + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + // Should only be called for the final loaded URL. + std::string url = frame->GetURL(); + + if (url == kRNav4) { + got_nav4_load_end_.yes(); + DestroyTest(); + } else { + got_invalid_load_end_.yes(); + } + } + + TrackCallback got_nav1_before_resource_load_; + TrackCallback got_nav3_before_resource_load_; + TrackCallback got_nav4_before_resource_load_; + TrackCallback got_invalid_before_resource_load_; + TrackCallback got_nav4_load_start_; + TrackCallback got_invalid_load_start_; + TrackCallback got_nav4_load_end_; + TrackCallback got_invalid_load_end_; + TrackCallback got_nav1_redirect_; + TrackCallback got_nav2_redirect_; + TrackCallback got_nav3_redirect_; + TrackCallback got_invalid_redirect_; +}; + +} // namespace + +// Verify frame names and identifiers. +TEST(NavigationTest, Redirect) { + CefRegisterSchemeHandlerFactory("http", "tests", + new RedirectSchemeHandlerFactory()); + WaitForIOThread(); + + CefRefPtr handler = + new RedirectTestHandler(); + handler->ExecuteTest(); + + CefClearSchemeHandlerFactories(); + WaitForIOThread(); + + ASSERT_TRUE(handler->got_nav1_before_resource_load_); + ASSERT_TRUE(handler->got_nav3_before_resource_load_); + ASSERT_TRUE(handler->got_nav4_before_resource_load_); + ASSERT_FALSE(handler->got_invalid_before_resource_load_); + ASSERT_TRUE(handler->got_nav4_load_start_); + ASSERT_FALSE(handler->got_invalid_load_start_); + ASSERT_TRUE(handler->got_nav4_load_end_); + ASSERT_FALSE(handler->got_invalid_load_end_); + ASSERT_TRUE(handler->got_nav1_redirect_); + ASSERT_TRUE(handler->got_nav2_redirect_); + ASSERT_TRUE(handler->got_nav3_redirect_); + ASSERT_FALSE(handler->got_invalid_redirect_); + ASSERT_TRUE(g_got_nav1_request); + ASSERT_TRUE(g_got_nav3_request); + ASSERT_TRUE(g_got_nav4_request); + ASSERT_FALSE(g_got_invalid_request); + + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +const char KONav1[] = "http://tests-onav/nav1.html"; +const char KONav2[] = "http://tests-onav/nav2.html"; +const char kOrderNavMsg[] = "NavigationTest.OrderNav"; +const char kOrderNavClosedMsg[] = "NavigationTest.OrderNavClosed"; + +void SetOrderNavExtraInfo(CefRefPtr extra_info) { + // Arbitrary data for testing. + extra_info->SetBool(0, true); + CefRefPtr dict = CefDictionaryValue::Create(); + dict->SetInt("key1", 5); + dict->SetString("key2", "test string"); + extra_info->SetDictionary(1, dict); + extra_info->SetDouble(2, 5.43322); + extra_info->SetString(3, "some string"); +} + +bool g_order_nav_test = false; + +// Browser side. +class OrderNavBrowserTest : public ClientApp::BrowserDelegate { + public: + OrderNavBrowserTest() {} + + void OnBeforeChildProcessLaunch( + CefRefPtr app, + CefRefPtr command_line) override { + if (!g_order_nav_test) + return; + + // Indicate to the render process that the test should be run. + command_line->AppendSwitchWithValue("test", kOrderNavMsg); + } + + void OnRenderProcessThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) override { + if (!g_order_nav_test) + return; + + // Some data that we'll check for. + SetOrderNavExtraInfo(extra_info); + } + + protected: + IMPLEMENT_REFCOUNTING(OrderNavBrowserTest); +}; + +class OrderNavLoadState { + public: + OrderNavLoadState(bool is_popup, bool browser_side) + : is_popup_(is_popup), + browser_side_(browser_side) {} + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) { + if (isLoading) { + EXPECT_TRUE(Verify(false, false, false, false)); + + got_loading_state_start_.yes(); + } else { + EXPECT_TRUE(Verify(true, false, true, false)); + + got_loading_state_end_.yes(); + } + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) { + EXPECT_TRUE(Verify(true, false, false, false)); + + got_load_start_.yes(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) { + EXPECT_TRUE(Verify(true, true, true, false)); + + got_load_end_.yes(); + } + + bool IsStarted() { + return got_loading_state_start_ || + got_loading_state_end_ || + got_load_start_ || + got_load_end_; + } + + bool IsDone() { + return got_loading_state_start_ && + got_loading_state_end_ && + got_load_start_ && + got_load_end_; + } + + private: + bool Verify(bool got_loading_state_start, + bool got_loading_state_end, + bool got_load_start, + bool got_load_end) { + EXPECT_EQ(got_loading_state_start, got_loading_state_start_) + << "Popup: " << is_popup_ + << "; Browser Side: " << browser_side_; + EXPECT_EQ(got_loading_state_end, got_loading_state_end_) + << "Popup: " << is_popup_ + << "; Browser Side: " << browser_side_; + EXPECT_EQ(got_load_start, got_load_start_) + << "Popup: " << is_popup_ + << "; Browser Side: " << browser_side_; + EXPECT_EQ(got_load_end, got_load_end_) + << "Popup: " << is_popup_ + << "; Browser Side: " << browser_side_; + + return got_loading_state_start == got_loading_state_start_ && + got_loading_state_end == got_loading_state_end_ && + got_load_start == got_load_start_ && + got_load_end == got_load_end_; + } + + bool is_popup_; + bool browser_side_; + + TrackCallback got_loading_state_start_; + TrackCallback got_loading_state_end_; + TrackCallback got_load_start_; + TrackCallback got_load_end_; +}; + +// Renderer side. +class OrderNavRendererTest : public ClientApp::RenderDelegate, + public CefLoadHandler { + public: + OrderNavRendererTest() + : run_test_(false), + browser_id_main_(0), + browser_id_popup_(0), + state_main_(false, false), + state_popup_(true, false) {} + + void OnRenderThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) override { + if (!g_order_nav_test) { + // Check that the test should be run. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + const std::string& test = command_line->GetSwitchValue("test"); + if (test != kOrderNavMsg) + return; + } + + run_test_ = true; + + EXPECT_FALSE(got_webkit_initialized_); + + got_render_thread_created_.yes(); + + // Verify that |extra_info| transferred successfully. + CefRefPtr expected = CefListValue::Create(); + SetOrderNavExtraInfo(expected); + TestListEqual(expected, extra_info); + } + + void OnWebKitInitialized(CefRefPtr app) override { + if (!run_test_) + return; + + EXPECT_TRUE(got_render_thread_created_); + + got_webkit_initialized_.yes(); + } + + void OnBrowserCreated(CefRefPtr app, + CefRefPtr browser) override { + if (!run_test_) + return; + + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + if (browser->IsPopup()) { + EXPECT_FALSE(got_browser_created_popup_); + EXPECT_FALSE(got_browser_destroyed_popup_); + EXPECT_FALSE(state_popup_.IsStarted()); + + got_browser_created_popup_.yes(); + browser_id_popup_ = browser->GetIdentifier(); + EXPECT_GT(browser->GetIdentifier(), 0); + } else { + EXPECT_FALSE(got_browser_created_main_); + EXPECT_FALSE(got_browser_destroyed_main_); + EXPECT_FALSE(state_main_.IsStarted()); + + got_browser_created_main_.yes(); + browser_id_main_ = browser->GetIdentifier(); + EXPECT_GT(browser->GetIdentifier(), 0); + + browser_main_ = browser; + } + } + + void OnBrowserDestroyed(CefRefPtr app, + CefRefPtr browser) override { + if (!run_test_) + return; + + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + if (browser->IsPopup()) { + EXPECT_TRUE(got_browser_created_popup_); + EXPECT_FALSE(got_browser_destroyed_popup_); + EXPECT_TRUE(state_popup_.IsDone()); + + got_browser_destroyed_popup_.yes(); + EXPECT_EQ(browser_id_popup_, browser->GetIdentifier()); + EXPECT_GT(browser->GetIdentifier(), 0); + + // Use |browser_main_| to send the message otherwise it will fail. + SendTestResults(browser_main_, kOrderNavClosedMsg); + } else { + EXPECT_TRUE(got_browser_created_main_); + EXPECT_FALSE(got_browser_destroyed_main_); + EXPECT_TRUE(state_main_.IsDone()); + + got_browser_destroyed_main_.yes(); + EXPECT_EQ(browser_id_main_, browser->GetIdentifier()); + EXPECT_GT(browser->GetIdentifier(), 0); + + browser_main_ = NULL; + } + } + + CefRefPtr GetLoadHandler( + CefRefPtr app) override { + if (!run_test_) + return NULL; + + return this; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + if (browser->IsPopup()) { + EXPECT_TRUE(got_browser_created_popup_); + EXPECT_FALSE(got_browser_destroyed_popup_); + + state_popup_.OnLoadingStateChange(browser, isLoading, canGoBack, + canGoForward); + } else { + EXPECT_TRUE(got_browser_created_main_); + EXPECT_FALSE(got_browser_destroyed_main_); + + state_main_.OnLoadingStateChange(browser, isLoading, canGoBack, + canGoForward); + } + + if (!isLoading) + SendTestResultsIfDone(browser); + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + if (browser->IsPopup()) { + EXPECT_TRUE(got_browser_created_popup_); + EXPECT_FALSE(got_browser_destroyed_popup_); + + state_popup_.OnLoadStart(browser, frame); + } else { + EXPECT_TRUE(got_browser_created_main_); + EXPECT_FALSE(got_browser_destroyed_main_); + + state_main_.OnLoadStart(browser, frame); + } + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + if (browser->IsPopup()) { + EXPECT_TRUE(got_browser_created_popup_); + EXPECT_FALSE(got_browser_destroyed_popup_); + + state_popup_.OnLoadEnd(browser, frame, httpStatusCode); + } else { + EXPECT_TRUE(got_browser_created_main_); + EXPECT_FALSE(got_browser_destroyed_main_); + + state_main_.OnLoadEnd(browser, frame, httpStatusCode); + } + + SendTestResultsIfDone(browser); + } + + protected: + void SendTestResultsIfDone(CefRefPtr browser) { + bool done = false; + if (browser->IsPopup()) + done = state_popup_.IsDone(); + else + done = state_main_.IsDone(); + + if (done) + SendTestResults(browser, kOrderNavMsg); + } + + // Send the test results. + void SendTestResults(CefRefPtr browser, const char* msg_name) { + // Check if the test has failed. + bool result = !TestFailed(); + + // Return the result to the browser process. + CefRefPtr return_msg = + CefProcessMessage::Create(msg_name); + CefRefPtr args = return_msg->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->SetBool(0, result)); + if (browser->IsPopup()) + EXPECT_TRUE(args->SetInt(1, browser_id_popup_)); + else + EXPECT_TRUE(args->SetInt(1, browser_id_main_)); + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, return_msg)); + } + + bool run_test_; + + int browser_id_main_; + int browser_id_popup_; + CefRefPtr browser_main_; + TrackCallback got_render_thread_created_; + TrackCallback got_webkit_initialized_; + TrackCallback got_browser_created_main_; + TrackCallback got_browser_destroyed_main_; + TrackCallback got_browser_created_popup_; + TrackCallback got_browser_destroyed_popup_; + + OrderNavLoadState state_main_; + OrderNavLoadState state_popup_; + + IMPLEMENT_REFCOUNTING(OrderNavRendererTest); +}; + +// Browser side. +class OrderNavTestHandler : public TestHandler { + public: + OrderNavTestHandler() + : browser_id_main_(0), + browser_id_popup_(0), + state_main_(false, true), + state_popup_(true, true), + got_message_(false) {} + + void RunTest() override { + // Add the resources that we will navigate to/from. + AddResource(KONav1, "Nav1", "text/html"); + AddResource(KONav2, "Nav2", "text/html"); + + // Create the browser. + CreateBrowser(KONav1); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void ContinueIfReady(CefRefPtr browser) { + if (!got_message_) + return; + + bool done = false; + if (browser->IsPopup()) + done = state_popup_.IsDone(); + else + done = state_main_.IsDone(); + if (!done) + return; + + got_message_ = false; + + if (!browser->IsPopup()) { + // Create the popup window. + browser->GetMainFrame()->ExecuteJavaScript( + "window.open('" + std::string(KONav2) + "');", CefString(), 0); + } else { + // Close the popup window. + browser_popup_->GetHost()->CloseBrowser(false); + } + } + + void OnAfterCreated(CefRefPtr browser) override { + TestHandler::OnAfterCreated(browser); + + if (browser->IsPopup()) { + browser_id_popup_ = browser->GetIdentifier(); + EXPECT_GT(browser_id_popup_, 0); + browser_popup_ = browser; + } else { + browser_id_main_ = browser->GetIdentifier(); + EXPECT_GT(browser_id_main_, 0); + } + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + + if (browser->IsPopup()) { + EXPECT_EQ(TT_LINK, request->GetTransitionType()); + EXPECT_GT(browser->GetIdentifier(), 0); + EXPECT_EQ(browser_id_popup_, browser->GetIdentifier()); + got_before_browse_popup_.yes(); + } else { + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + EXPECT_GT(browser->GetIdentifier(), 0); + EXPECT_EQ(browser_id_main_, browser->GetIdentifier()); + got_before_browse_main_.yes(); + } + + std::string url = request->GetURL(); + if (url == KONav1) + EXPECT_FALSE(browser->IsPopup()); + else if (url == KONav2) + EXPECT_TRUE(browser->IsPopup()); + else + EXPECT_TRUE(false); // not reached + + return false; + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + + if (browser->IsPopup()) { + EXPECT_EQ(TT_LINK, request->GetTransitionType()); + EXPECT_GT(browser->GetIdentifier(), 0); + EXPECT_EQ(browser_id_popup_, browser->GetIdentifier()); + } else { + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + EXPECT_GT(browser->GetIdentifier(), 0); + EXPECT_EQ(browser_id_main_, browser->GetIdentifier()); + } + + return false; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + if (browser->IsPopup()) { + state_popup_.OnLoadingStateChange(browser, isLoading, canGoBack, + canGoForward); + } else { + state_main_.OnLoadingStateChange(browser, isLoading, canGoBack, + canGoForward); + } + + if (!isLoading) + ContinueIfReady(browser); + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + if (browser->IsPopup()) { + state_popup_.OnLoadStart(browser, frame); + } else { + state_main_.OnLoadStart(browser, frame); + } + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + if (browser->IsPopup()) { + state_popup_.OnLoadEnd(browser, frame, httpStatusCode); + } else { + state_main_.OnLoadEnd(browser, frame, httpStatusCode); + } + + ContinueIfReady(browser); + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (browser->IsPopup()) { + EXPECT_GT(browser->GetIdentifier(), 0); + EXPECT_EQ(browser_id_popup_, browser->GetIdentifier()); + } else { + EXPECT_GT(browser->GetIdentifier(), 0); + EXPECT_EQ(browser_id_main_, browser->GetIdentifier()); + } + + const std::string& msg_name = message->GetName(); + if (msg_name == kOrderNavMsg || msg_name == kOrderNavClosedMsg) { + // Test that the renderer side succeeded. + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->GetBool(0)); + + if (browser->IsPopup()) { + EXPECT_EQ(browser_id_popup_, args->GetInt(1)); + } else { + EXPECT_EQ(browser_id_main_, args->GetInt(1)); + } + + if (msg_name == kOrderNavMsg) { + // Continue with the test. + got_message_ = true; + ContinueIfReady(browser); + } else { + // Popup was closed. End the test. + browser_popup_ = NULL; + DestroyTest(); + } + + return true; + } + + // Message not handled. + return false; + } + + protected: + void DestroyTest() override { + // Verify test expectations. + EXPECT_TRUE(got_before_browse_main_); + EXPECT_TRUE(got_before_browse_popup_); + + TestHandler::DestroyTest(); + } + + int browser_id_main_; + int browser_id_popup_; + CefRefPtr browser_popup_; + + TrackCallback got_before_browse_main_; + TrackCallback got_before_browse_popup_; + + OrderNavLoadState state_main_; + OrderNavLoadState state_popup_; + + bool got_message_; +}; + +} // namespace + +// Verify the order of navigation-related callbacks. +TEST(NavigationTest, Order) { + g_order_nav_test = true; + CefRefPtr handler = + new OrderNavTestHandler(); + handler->ExecuteTest(); + g_order_nav_test = false; + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +const char kCrossOriginNav1[] = "http://tests-conav1/nav1.html"; +const char kCrossOriginNav2[] = "http://tests-conav2/nav2.html"; +const char kCrossOriginNavMsg[] = "NavigationTest.CrossOriginNav"; + +bool g_cross_origin_nav_test = false; + +// Browser side. +class CrossOriginNavBrowserTest : public ClientApp::BrowserDelegate { + public: + CrossOriginNavBrowserTest() {} + + void OnBeforeChildProcessLaunch( + CefRefPtr app, + CefRefPtr command_line) override { + if (!g_cross_origin_nav_test) + return; + + // Indicate to the render process that the test should be run. + command_line->AppendSwitchWithValue("test", kCrossOriginNavMsg); + } + + protected: + IMPLEMENT_REFCOUNTING(CrossOriginNavBrowserTest); +}; + +// Renderer side. +class CrossOriginNavRendererTest : public ClientApp::RenderDelegate, + public CefLoadHandler { + public: + CrossOriginNavRendererTest() + : run_test_(false) {} + ~CrossOriginNavRendererTest() override { + EXPECT_TRUE(status_list_.empty()); + } + + void OnRenderThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) override { + if (!g_cross_origin_nav_test) { + // Check that the test should be run. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + const std::string& test = command_line->GetSwitchValue("test"); + if (test != kCrossOriginNavMsg) + return; + } + + run_test_ = true; + + EXPECT_FALSE(got_webkit_initialized_); + + got_render_thread_created_.yes(); + } + + void OnWebKitInitialized(CefRefPtr app) override { + if (!run_test_) + return; + + EXPECT_TRUE(got_render_thread_created_); + + got_webkit_initialized_.yes(); + } + + void OnBrowserCreated(CefRefPtr app, + CefRefPtr browser) override { + if (!run_test_) + return; + + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + EXPECT_FALSE(GetStatus(browser)); + Status* status = AddStatus(browser); + status->got_browser_created.yes(); + } + + void OnBrowserDestroyed(CefRefPtr app, + CefRefPtr browser) override { + if (!run_test_) + return; + + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + Status* status = GetStatus(browser); + EXPECT_TRUE(status); + + EXPECT_TRUE(status->got_browser_created); + EXPECT_TRUE(status->got_loading_state_end); + + EXPECT_EQ(status->browser_id, browser->GetIdentifier()); + + EXPECT_TRUE(RemoveStatus(browser)); + } + + CefRefPtr GetLoadHandler( + CefRefPtr app) override { + if (!run_test_) + return NULL; + + return this; + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + if (!isLoading) { + EXPECT_TRUE(got_render_thread_created_); + EXPECT_TRUE(got_webkit_initialized_); + + Status* status = GetStatus(browser); + EXPECT_TRUE(status); + + EXPECT_TRUE(status->got_browser_created); + EXPECT_FALSE(status->got_loading_state_end); + + status->got_loading_state_end.yes(); + + EXPECT_EQ(status->browser_id, browser->GetIdentifier()); + + SendTestResults(browser); + } + } + + protected: + // Send the test results. + void SendTestResults(CefRefPtr browser) { + // Check if the test has failed. + bool result = !TestFailed(); + + // Return the result to the browser process. + CefRefPtr return_msg = + CefProcessMessage::Create(kCrossOriginNavMsg); + CefRefPtr args = return_msg->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->SetBool(0, result)); + EXPECT_TRUE(args->SetInt(1, browser->GetIdentifier())); + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, return_msg)); + } + + bool run_test_; + + TrackCallback got_render_thread_created_; + TrackCallback got_webkit_initialized_; + + struct Status { + Status() : browser_id(0) {} + + CefRefPtr browser; + int browser_id; + TrackCallback got_browser_created; + TrackCallback got_loading_state_end; + }; + typedef std::list StatusList; + StatusList status_list_; + + Status* GetStatus(CefRefPtr browser) { + StatusList::iterator it = status_list_.begin(); + for (; it != status_list_.end(); ++it) { + Status& status = (*it); + if (status.browser->IsSame(browser)) + return &status; + } + + return NULL; + } + + Status* AddStatus(CefRefPtr browser) { + Status status; + status.browser = browser; + status.browser_id = browser->GetIdentifier(); + EXPECT_GT(status.browser_id, 0); + status_list_.push_back(status); + return &status_list_.back(); + } + + bool RemoveStatus(CefRefPtr browser) { + StatusList::iterator it = status_list_.begin(); + for (; it != status_list_.end(); ++it) { + Status& status = (*it); + if (status.browser->IsSame(browser)) { + status_list_.erase(it); + return true; + } + } + + return false; + } + + IMPLEMENT_REFCOUNTING(CrossOriginNavRendererTest); +}; + +// Browser side. +class CrossOriginNavTestHandler : public TestHandler { + public: + CrossOriginNavTestHandler() + : browser_id_current_(0), + got_message_(false), + got_load_end_(false) {} + + void RunTest() override { + // Add the resources that we will navigate to/from. + AddResource(kCrossOriginNav1, "Nav1", "text/html"); + AddResource(kCrossOriginNav2, "Nav2", "text/html"); + + // Create the browser. + CreateBrowser(kCrossOriginNav1); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void ContinueIfReady(CefRefPtr browser) { + if (!got_message_ || !got_load_end_) + return; + + got_message_ = false; + got_load_end_ = false; + + std::string url = browser->GetMainFrame()->GetURL(); + if (url == kCrossOriginNav1) { + // Load the next url. + browser->GetMainFrame()->LoadURL(kCrossOriginNav2); + } else { + // Done with the test. + DestroyTest(); + } + } + + void OnAfterCreated(CefRefPtr browser) override { + TestHandler::OnAfterCreated(browser); + + EXPECT_EQ(browser_id_current_, 0); + browser_id_current_ = browser->GetIdentifier(); + EXPECT_GT(browser_id_current_, 0); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + + EXPECT_GT(browser_id_current_, 0); + EXPECT_EQ(browser_id_current_, browser->GetIdentifier()); + + return false; + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + EXPECT_EQ(TT_EXPLICIT, request->GetTransitionType()); + + EXPECT_GT(browser_id_current_, 0); + EXPECT_EQ(browser_id_current_, browser->GetIdentifier()); + + return false; + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + EXPECT_GT(browser_id_current_, 0); + EXPECT_EQ(browser_id_current_, browser->GetIdentifier()); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + EXPECT_GT(browser_id_current_, 0); + EXPECT_EQ(browser_id_current_, browser->GetIdentifier()); + + got_load_end_ = true; + ContinueIfReady(browser); + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + EXPECT_GT(browser_id_current_, 0); + EXPECT_EQ(browser_id_current_, browser->GetIdentifier()); + + const std::string& msg_name = message->GetName(); + if (msg_name == kCrossOriginNavMsg) { + // Test that the renderer side succeeded. + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->GetBool(0)); + + EXPECT_EQ(browser_id_current_, args->GetInt(1)); + + // Continue with the test. + got_message_ = true; + ContinueIfReady(browser); + + return true; + } + + // Message not handled. + return false; + } + + protected: + int browser_id_current_; + + bool got_message_; + bool got_load_end_; +}; + +} // namespace + +// Verify navigation-related callbacks when browsing cross-origin. +TEST(NavigationTest, CrossOrigin) { + g_cross_origin_nav_test = true; + CefRefPtr handler = + new CrossOriginNavTestHandler(); + handler->ExecuteTest(); + g_cross_origin_nav_test = false; + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +const char kPopupNavPageUrl[] = "http://tests-popup.com/page.html"; +const char kPopupNavPopupUrl[] = "http://tests-popup.com/popup.html"; +const char kPopupNavPopupUrl2[] = "http://tests-popup2.com/popup.html"; +const char kPopupNavPopupName[] = "my_popup"; + +// Browser side. +class PopupNavTestHandler : public TestHandler { + public: + enum Mode { + ALLOW, + DENY, + NAVIGATE_AFTER_CREATION, + }; + + PopupNavTestHandler(Mode mode) + : mode_(mode) {} + + void RunTest() override { + // Add the resources that we will navigate to/from. + std::string page = "Page"; + AddResource(kPopupNavPageUrl, page, "text/html"); + AddResource(kPopupNavPopupUrl, "Popup", "text/html"); + if (mode_ == NAVIGATE_AFTER_CREATION) + AddResource(kPopupNavPopupUrl2, "Popup2", "text/html"); + + // Create the browser. + CreateBrowser(kPopupNavPageUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + bool OnBeforePopup(CefRefPtr browser, + CefRefPtr frame, + const CefString& target_url, + const CefString& target_frame_name, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + CefRefPtr& client, + CefBrowserSettings& settings, + bool* no_javascript_access) override { + got_on_before_popup_.yes(); + + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + EXPECT_EQ(GetBrowserId(), browser->GetIdentifier()); + EXPECT_STREQ(kPopupNavPageUrl, frame->GetURL().ToString().c_str()); + EXPECT_STREQ(kPopupNavPopupUrl, target_url.ToString().c_str()); + EXPECT_STREQ(kPopupNavPopupName, target_frame_name.ToString().c_str()); + EXPECT_FALSE(*no_javascript_access); + + return (mode_ == DENY); // Return true to cancel the popup. + } + + void OnAfterCreated(CefRefPtr browser) override { + TestHandler::OnAfterCreated(browser); + + if (mode_ == NAVIGATE_AFTER_CREATION && browser->IsPopup()) + browser->GetMainFrame()->LoadURL(kPopupNavPopupUrl2); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + std::string url = frame->GetURL(); + if (url == kPopupNavPageUrl) { + frame->ExecuteJavaScript("doPopup()", kPopupNavPageUrl, 0); + + if (mode_ == DENY) { + // Wait a bit to make sure the popup window isn't created. + CefPostDelayedTask(TID_UI, + base::Bind(&PopupNavTestHandler::DestroyTest, this), 200); + } + } else if (url == kPopupNavPopupUrl) { + if (mode_ != NAVIGATE_AFTER_CREATION) { + if (mode_ != DENY) { + got_popup_load_end_.yes(); + browser->GetHost()->CloseBrowser(false); + DestroyTest(); + } else { + EXPECT_FALSE(true); // Not reached. + } + } + } else if (url == kPopupNavPopupUrl2) { + if (mode_ == NAVIGATE_AFTER_CREATION) { + got_popup_load_end_.yes(); + browser->GetHost()->CloseBrowser(false); + DestroyTest(); + } else { + EXPECT_FALSE(true); // Not reached. + } + } else { + EXPECT_FALSE(true); // Not reached. + } + } + + private: + void DestroyTest() override { + EXPECT_TRUE(got_on_before_popup_); + if (mode_ != DENY) + EXPECT_TRUE(got_popup_load_end_); + else + EXPECT_FALSE(got_popup_load_end_); + + TestHandler::DestroyTest(); + } + + const Mode mode_; + + TrackCallback got_on_before_popup_; + TrackCallback got_popup_load_end_; +}; + +} // namespace + +// Test allowing popups. +TEST(NavigationTest, PopupAllow) { + CefRefPtr handler = + new PopupNavTestHandler(PopupNavTestHandler::ALLOW); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test denying popups. +TEST(NavigationTest, PopupDeny) { + CefRefPtr handler = + new PopupNavTestHandler(PopupNavTestHandler::DENY); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test navigation to a different origin after popup creation to verify that +// internal objects are tracked correctly (see issue #1392). +TEST(NavigationTest, PopupNavigateAfterCreation) { + CefRefPtr handler = + new PopupNavTestHandler(PopupNavTestHandler::NAVIGATE_AFTER_CREATION); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + + +namespace { + +const char kBrowseNavPageUrl[] = "http://tests-browsenav/nav.html"; + +// Browser side. +class BrowseNavTestHandler : public TestHandler { + public: + BrowseNavTestHandler(bool allow) + : allow_(allow), + destroyed_(false) {} + + void RunTest() override { + AddResource(kBrowseNavPageUrl, "Test", "text/html"); + + // Create the browser. + CreateBrowser(kBrowseNavPageUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + const std::string& url = request->GetURL(); + EXPECT_STREQ(kBrowseNavPageUrl, url.c_str()); + EXPECT_EQ(GetBrowserId(), browser->GetIdentifier()); + EXPECT_TRUE(frame->IsMain()); + + got_before_browse_.yes(); + + return !allow_; + } + + void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) override { + const std::string& url = frame->GetURL(); + EXPECT_STREQ(kBrowseNavPageUrl, url.c_str()); + EXPECT_EQ(GetBrowserId(), browser->GetIdentifier()); + EXPECT_TRUE(frame->IsMain()); + + got_load_start_.yes(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + const std::string& url = frame->GetURL(); + EXPECT_STREQ(kBrowseNavPageUrl, url.c_str()); + EXPECT_EQ(GetBrowserId(), browser->GetIdentifier()); + EXPECT_TRUE(frame->IsMain()); + + got_load_end_.yes(); + DestroyTestIfDone(); + } + + void OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) override { + const std::string& url = frame->GetURL(); + EXPECT_STREQ("", url.c_str()); + EXPECT_EQ(GetBrowserId(), browser->GetIdentifier()); + EXPECT_TRUE(frame->IsMain()); + + EXPECT_EQ(ERR_ABORTED, errorCode); + EXPECT_STREQ(kBrowseNavPageUrl, failedUrl.ToString().c_str()); + + got_load_error_.yes(); + DestroyTestIfDone(); + } + + void OnLoadingStateChange(CefRefPtr browser, + bool isLoading, + bool canGoBack, + bool canGoForward) override { + const std::string& url = browser->GetMainFrame()->GetURL(); + EXPECT_EQ(GetBrowserId(), browser->GetIdentifier()); + + if (isLoading) { + EXPECT_STREQ("", url.c_str()); + + got_loading_state_changed_start_.yes(); + } else { + if (allow_) + EXPECT_STREQ(kBrowseNavPageUrl, url.c_str()); + else + EXPECT_STREQ("", url.c_str()); + + got_loading_state_changed_end_.yes(); + DestroyTestIfDone(); + } + } + + private: + void DestroyTestIfDone() { + if (destroyed_) + return; + + if (got_loading_state_changed_end_) { + if (allow_) { + if (got_load_end_) + DestroyTest(); + } else if (got_load_error_) { + DestroyTest(); + } + } + } + + void DestroyTest() override { + if (destroyed_) + return; + destroyed_ = true; + + EXPECT_TRUE(got_before_browse_); + EXPECT_TRUE(got_loading_state_changed_start_); + EXPECT_TRUE(got_loading_state_changed_end_); + + if (allow_) { + EXPECT_TRUE(got_load_start_); + EXPECT_TRUE(got_load_end_); + EXPECT_FALSE(got_load_error_); + } else { + EXPECT_FALSE(got_load_start_); + EXPECT_FALSE(got_load_end_); + EXPECT_TRUE(got_load_error_); + } + + TestHandler::DestroyTest(); + } + + bool allow_; + bool destroyed_; + + TrackCallback got_before_browse_; + TrackCallback got_load_start_; + TrackCallback got_load_end_; + TrackCallback got_load_error_; + TrackCallback got_loading_state_changed_start_; + TrackCallback got_loading_state_changed_end_; +}; + +} // namespace + +// Test allowing navigation. +TEST(NavigationTest, BrowseAllow) { + CefRefPtr handler = new BrowseNavTestHandler(true); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test denying navigation. +TEST(NavigationTest, BrowseDeny) { + CefRefPtr handler = new BrowseNavTestHandler(false); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + + +// Entry point for creating navigation browser test objects. +// Called from client_app_delegates.cc. +void CreateNavigationBrowserTests(ClientApp::BrowserDelegateSet& delegates) { + delegates.insert(new HistoryNavBrowserTest); + delegates.insert(new OrderNavBrowserTest); + delegates.insert(new CrossOriginNavBrowserTest); +} + +// Entry point for creating navigation renderer test objects. +// Called from client_app_delegates.cc. +void CreateNavigationRendererTests(ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new HistoryNavRendererTest); + delegates.insert(new OrderNavRendererTest); + delegates.insert(new CrossOriginNavRendererTest); +} diff --git a/tests/unittests/os_rendering_unittest.cc b/tests/unittests/os_rendering_unittest.cc new file mode 100644 index 000000000..497922df5 --- /dev/null +++ b/tests/unittests/os_rendering_unittest.cc @@ -0,0 +1,1077 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "ui/events/keycodes/keyboard_codes.h" +#include "ui/events/keycodes/keyboard_code_conversion.h" +#include "ui/gfx/geometry/dip_util.h" +#include "ui/gfx/geometry/rect.h" + +#include "include/base/cef_bind.h" +#include "include/base/cef_logging.h" +#include "include/cef_v8.h" +#include "include/wrapper/cef_closure_task.h" +#include "include/wrapper/cef_stream_resource_handler.h" +#include "tests/cefclient/client_app.h" +#include "tests/cefclient/resource_util.h" +#include "tests/unittests/routing_test_handler.h" + +#if defined(OS_MACOSX) +#include "tests/unittests/os_rendering_unittest_mac.h" +#elif defined(OS_LINUX) +#include +#elif defined(OS_WIN) +// Required for resource_util_win, which uses this as an extern +HINSTANCE hInst = ::GetModuleHandle(NULL); +#endif + +namespace { + +const char kTestUrl[] = "http://tests/osrtest"; + +// this html should render on a 600 x 400 window with a little vertical +// offset with scrollbar. + +// default osr widget size +const int kOsrWidth = 600; +const int kOsrHeight = 400; + +// precomputed bounding client rects for html elements (h1 and li). +#if defined(OS_WIN) || defined(OS_LINUX) +const CefRect kExpectedRectLI[] = { + CefRect(8, 8, 567, 74), // LI00 + CefRect(27, 103, 548, 20), // LI01 + CefRect(27, 123, 548, 20), // LI02 + CefRect(27, 143, 548, 20), // LI03 + CefRect(27, 163, 548, 20), // LI04 + CefRect(27, 183, 548, 20), // LI05 + CefRect(27, 203, 548, 20), // LI06 + CefRect(27, 223, 548, 20), // LI07 + CefRect(27, 243, 548, 26), // LI08 + CefRect(27, 269, 548, 26), // LI09 + CefRect(27, 295, 548, 20), // LI10 +}; +#elif defined(OS_MACOSX) +const CefRect kExpectedRectLI[] = { + CefRect(8, 8, 584, 74), // LI00 + CefRect(28, 103, 564, 18), // LI01 + CefRect(28, 121, 564, 18), // LI02 + CefRect(28, 139, 564, 18), // LI03 + CefRect(28, 157, 564, 18), // LI04 + CefRect(28, 175, 564, 18), // LI05 + CefRect(28, 193, 564, 18), // LI06 + CefRect(28, 211, 564, 18), // LI07 + CefRect(28, 229, 564, 23), // LI08 + CefRect(28, 252, 564, 26), // LI09 + CefRect(18, 291, 360, 21), // LI10 +}; +#else +#error "Unsupported platform" +#endif // defined(OS_WIN) + +// bounding client rects for edit box and navigate button +#if defined(OS_WIN) +const CefRect kEditBoxRect(412, 245, 60, 22); +const CefRect kNavigateButtonRect(360, 271, 140, 22); +const CefRect kSelectRect(467, 22, 75, 20); +const CefRect kExpandedSelectRect(465, 42, 81, 302); +const CefRect kDropDivRect(8, 332, 52, 52); +const CefRect kDragDivRect(71, 342, 30, 30); +const int kDefaultVerticalScrollbarWidth = 17; +const int kVerticalScrollbarWidth = GetSystemMetrics(SM_CXVSCROLL); +#elif defined(OS_MACOSX) +const CefRect kEditBoxRect(442, 251, 46, 16); +const CefRect kNavigateButtonRect(375, 275, 130, 20); +const CefRect kSelectRect(461, 21, 87, 26); +const CefRect kExpandedSelectRect(465, 42, 80, 262); +const CefRect kDropDivRect(9, 330, 52, 52); +const CefRect kDragDivRect(60, 330, 52, 52); +const int kVerticalScrollbarWidth = 15; +#elif defined(OS_LINUX) +const CefRect kEditBoxRect(434, 246, 60, 20); +const CefRect kNavigateButtonRect(380, 271, 140, 22); +const CefRect kSelectRect(467, 22, 75, 20); +const CefRect kExpandedSelectRect(465, 42, 80, 302); +const CefRect kDropDivRect(8, 332, 52, 52); +const CefRect kDragDivRect(71, 342, 30, 30); +const int kDefaultVerticalScrollbarWidth = 14; +const int kVerticalScrollbarWidth = 14; +#else +#error "Unsupported platform" +#endif // defined(OS_WIN) + +// word to be written into edit box +const char kKeyTestWord[] = "done"; + +#if defined(OS_MACOSX) || defined(OS_LINUX) +const ui::KeyboardCode kKeyTestCodes[] = { + ui::VKEY_D, + ui::VKEY_O, + ui::VKEY_N, + ui::VKEY_E +}; +#endif +#if defined(OS_LINUX) +const unsigned int kNativeKeyTestCodes[] = { + XK_d, + XK_o, + XK_n, + XK_e +}; +#endif + +// width for the icon that appear on the screen when pressing +// middle mouse button +const int kMiddleButtonIconWidth = 16; + +// test type +enum OSRTestType { + // IsWindowRenderingDisabled should be true + OSR_TEST_IS_WINDOWLESS, + // focusing webview, LI00 will get red & repainted + OSR_TEST_FOCUS, + // loading webview should trigger a full paint (L01) + OSR_TEST_PAINT, + // same as OSR_TEST_PAINT but with alpha values + OSR_TEST_TRANSPARENCY, + // moving mouse over L02, OnCursorChange will be called + OSR_TEST_CURSOR, + // moving mouse on L03, OnPaint will be called for its bounding rectangle + OSR_TEST_MOUSE_MOVE, + // right clicking an element (L04), OnBeforeContextMenu should be called + OSR_TEST_CLICK_RIGHT, + // right clicking an element (L04), context menu will query screen point + OSR_TEST_SCREEN_POINT, + // left click in text box should query repainting edit box area + OSR_TEST_CLICK_LEFT, + // clicking middle mouse button, will draw the scroll icon + OSR_TEST_CLICK_MIDDLE, + // Resize should trigger a full repaint with the new given size + OSR_TEST_RESIZE, + // Invalidate should trigger repaint synchronously + OSR_TEST_INVALIDATE, + // write into editbox LI08, click to navigate on LI09 + OSR_TEST_KEY_EVENTS, + // mouse over LI10 will show a tooltip + OSR_TEST_TOOLTIP, + // mouse wheel will trigger a scroll event + OSR_TEST_SCROLLING, + // Right click will trigger a context menu, and on destroying the test, it + // should not crash + OSR_TEST_CONTEXT_MENU, + // clicking on dropdown box, PET_POPUP OnPaint is triggered + OSR_TEST_POPUP_PAINT, + // clicking on dropdown box, a popup will show up + OSR_TEST_POPUP_SHOW, + // clicking on dropdown box, OnPopupSize should be called + OSR_TEST_POPUP_SIZE, + // taking focus away from the webview, will close popup + OSR_TEST_POPUP_HIDE_ON_BLUR, + // clicking outside the popup widget will close popup + OSR_TEST_POPUP_HIDE_ON_CLICK, + // scrolling outside the popup widget will close popup + OSR_TEST_POPUP_HIDE_ON_SCROLL, + // pressing ESC will close popup + OSR_TEST_POPUP_HIDE_ON_ESC, + // scrolling inside the popup should trigger repaint for popup area + OSR_TEST_POPUP_SCROLL_INSIDE, + // clicking and moving the mouse will call StartDragging + OSR_TEST_DRAG_DROP_START_DRAGGING, + // starting dragging over the drop region will call UpdateDragCursor + OSR_TEST_DRAG_DROP_UPDATE_CURSOR, + // dropping element inside drop region will move the element + OSR_TEST_DRAG_DROP_DROP, +}; + +// Used in the browser process. +class OSRTestHandler : public RoutingTestHandler, + public CefRenderHandler, + public CefContextMenuHandler { + public: + OSRTestHandler(OSRTestType test_type, + float scale_factor) + : test_type_(test_type), + scale_factor_(scale_factor), + event_count_(0), + event_total_(1), + started_(false) { + } + + // TestHandler methods + void RunTest() override { + CreateOSRBrowser(kTestUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnAfterCreated(CefRefPtr browser) override { + if (test_type_ == OSR_TEST_IS_WINDOWLESS) { + EXPECT_TRUE(browser->GetHost()->IsWindowRenderingDisabled()); + DestroySucceededTestSoon(); + } + RoutingTestHandler::OnAfterCreated(browser); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + if (!started()) + return; + + switch(test_type_) { + case OSR_TEST_KEY_EVENTS: { + const std::string& expected_url = + std::string(kTestUrl) + "?k=" + kKeyTestWord; + EXPECT_STREQ(expected_url.c_str(), + frame->GetURL().ToString().c_str()); + DestroySucceededTestSoon(); + } break; + default: + // Intentionally left blank + break; + } + } + + bool OnQuery(CefRefPtr browser, + CefRefPtr frame, + int64 query_id, + const CefString& request, + bool persistent, + CefRefPtr callback) override { + EXPECT_TRUE(browser.get()); + + if (!started()) + return false; + + const std::string& messageStr = request; + switch(test_type_) { + case OSR_TEST_FOCUS: + EXPECT_STREQ(messageStr.c_str(), "osrfocus"); + DestroySucceededTestSoon(); + break; + case OSR_TEST_CLICK_LEFT: + EXPECT_STREQ(messageStr.c_str(), "osrclick0"); + DestroySucceededTestSoon(); + break; + case OSR_TEST_CLICK_MIDDLE: + EXPECT_STREQ(messageStr.c_str(), "osrclick1"); + DestroySucceededTestSoon(); + break; + case OSR_TEST_MOUSE_MOVE: + EXPECT_STREQ(messageStr.c_str(), "osrmousemove"); + DestroySucceededTestSoon(); + break; + case OSR_TEST_DRAG_DROP_DROP: + EXPECT_STREQ(messageStr.c_str(), "osrdrop"); + DestroySucceededTestSoon(); + break; + default: + // Intentionally left blank + break; + } + + callback->Success(""); + return true; + } + + // CefClient methods, providing handlers + CefRefPtr GetRenderHandler() override { + return this; + } + + CefRefPtr GetContextMenuHandler() override { + return this; + } + + CefRefPtr GetRequestHandler() override { + return this; + } + + CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + std::string url = request->GetURL(); + + if (url.find(kTestUrl) == 0) { + // Show the osr test contents + CefRefPtr stream = + client::GetBinaryResourceReader("osr_test.html"); + return new CefStreamResourceHandler("text/html", stream); + } + + return NULL; + } + + // CefRenderHandler methods + bool GetViewRect(CefRefPtr browser, + CefRect& rect) override { + if (test_type_ == OSR_TEST_RESIZE && started()) { + rect = CefRect(0, 0, kOsrWidth * 2, kOsrHeight * 2); + return true; + } + rect = CefRect(0, 0, kOsrWidth, kOsrHeight); + return true; + } + + bool GetScreenPoint(CefRefPtr browser, + int viewX, + int viewY, + int& screenX, + int& screenY) override { + if (test_type_ == OSR_TEST_SCREEN_POINT && started()) { + const CefRect& expected_rect = GetExpectedRect(4); + EXPECT_EQ(viewX, MiddleX(expected_rect)); + EXPECT_EQ(viewY, MiddleY(expected_rect)); + DestroySucceededTestSoon(); + } else if (test_type_ == OSR_TEST_CONTEXT_MENU && started()){ + screenX = 0; + screenY = 0; + return true; + } + // we don't want to see a contextual menu. stop here. + return false; + } + + bool GetScreenInfo(CefRefPtr browser, + CefScreenInfo& screen_info) override { + screen_info.device_scale_factor = scale_factor_; + + // The screen info rectangles are used by the renderer to create and + // position popups. If not overwritten in this function, the rectangle + // returned from GetViewRect will be used to popuplate them. + // The popup in the test fits without modifications in the test window, so + // setting the screen to the test window size does not affect its rectangle. + screen_info.rect = CefRect(0, 0, kOsrWidth, kOsrHeight); + screen_info.available_rect = screen_info.rect; + return true; + } + + void OnPopupShow(CefRefPtr browser, + bool show) override { + if (show && started()) { + switch (test_type_) { + case OSR_TEST_POPUP_SHOW: + if (!succeeded()) { + EXPECT_TRUE(show); + DestroySucceededTestSoon(); + } + break; + default: + break; + } + } + if (!show && started()) { + switch (test_type_) { + case OSR_TEST_POPUP_HIDE_ON_BLUR: + case OSR_TEST_POPUP_HIDE_ON_CLICK: + case OSR_TEST_POPUP_HIDE_ON_ESC: + case OSR_TEST_POPUP_HIDE_ON_SCROLL: + DestroySucceededTestSoon(); + break; + default: + break; + } + } + } + + void OnPopupSize(CefRefPtr browser, + const CefRect& rect) override { + if (started()) { + switch (test_type_) { + case OSR_TEST_POPUP_SIZE: + EXPECT_EQ(kExpandedSelectRect, rect); + DestroySucceededTestSoon(); + break; + default: + break; + } + } + } + + void OnPaint(CefRefPtr browser, + PaintElementType type, + const RectList& dirtyRects, + const void* buffer, + int width, int height) override { + // bitmap must as big as GetViewRect said + if (test_type_ != OSR_TEST_RESIZE && type == PET_VIEW) { + EXPECT_EQ(GetScaledInt(kOsrWidth), width); + EXPECT_EQ(GetScaledInt(kOsrHeight), height); + } else if (type == PET_POPUP) { + const CefRect& expanded_select_rect = GetScaledRect(kExpandedSelectRect); + EXPECT_EQ(expanded_select_rect.width, width); + EXPECT_EQ(expanded_select_rect.height, height); + } + + EXPECT_TRUE(browser->GetHost()->IsWindowRenderingDisabled()); + + // start test only when painting something else then background + if (IsBackgroundInBuffer(reinterpret_cast(buffer), + width * height, + test_type_ == OSR_TEST_TRANSPARENCY ? + 0x00000000 : + 0xFFFFFFFF)) + return; + + // Send events after the first full repaint + switch (test_type_) { + case OSR_TEST_PAINT: + if (StartTest()) { + // test that we have a full repaint + EXPECT_EQ(dirtyRects.size(), 1U); + EXPECT_TRUE(IsFullRepaint(dirtyRects[0], GetScaledInt(kOsrWidth), + GetScaledInt(kOsrHeight))); + EXPECT_EQ(*(reinterpret_cast(buffer)), 0xffff8080); + DestroySucceededTestSoon(); + } + break; + case OSR_TEST_TRANSPARENCY: + if (StartTest()) { + // test that we have a full repaint + EXPECT_EQ(dirtyRects.size(), 1U); + EXPECT_TRUE(IsFullRepaint(dirtyRects[0], GetScaledInt(kOsrWidth), + GetScaledInt(kOsrHeight))); + EXPECT_EQ(*(reinterpret_cast(buffer)), 0x7f7f0000U); + DestroySucceededTestSoon(); + } + break; + case OSR_TEST_FOCUS: + if (StartTest()) { + // body.onfocus will make LI00 red + browser->GetHost()->SendFocusEvent(true); + } + break; + case OSR_TEST_CURSOR: + if (StartTest()) { + // make mouse leave first + CefMouseEvent mouse_event; + mouse_event.x = 0; + mouse_event.y = 0; + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseMoveEvent(mouse_event, true); + // enter mouse in the LI2 element having hand cursor + const CefRect& expected_rect = GetExpectedRect(2); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + browser->GetHost()->SendMouseMoveEvent(mouse_event, false); + } + break; + case OSR_TEST_MOUSE_MOVE: + if (StartTest()) { + CefMouseEvent mouse_event; + const CefRect& expected_rect = GetExpectedRect(3); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseMoveEvent(mouse_event, false); + } + break; + case OSR_TEST_CLICK_RIGHT: + case OSR_TEST_SCREEN_POINT: + case OSR_TEST_CONTEXT_MENU: + if (StartTest()) { + CefMouseEvent mouse_event; + const CefRect& expected_rect = GetExpectedRect(4); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_RIGHT, false, 1); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_RIGHT, true, 1); + } + break; + case OSR_TEST_CLICK_LEFT: + if (StartTest()) { + CefMouseEvent mouse_event; + const CefRect& expected_rect = GetExpectedRect(0); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, false, 1); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, true, 1); + } + break; + case OSR_TEST_CLICK_MIDDLE: + if (StartTest()) { + CefMouseEvent mouse_event; + const CefRect& expected_rect = GetExpectedRect(0); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_MIDDLE, false, 1); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_MIDDLE, true, 1); + } else { + EXPECT_EQ(dirtyRects.size(), 1U); + const CefRect& expected_rect = GetExpectedRect(0); + CefRect button_icon_rect( + MiddleX(expected_rect) - kMiddleButtonIconWidth / 2, + MiddleY(expected_rect) - kMiddleButtonIconWidth / 2, + kMiddleButtonIconWidth, kMiddleButtonIconWidth); + button_icon_rect = GetScaledRect(button_icon_rect); + EXPECT_EQ(dirtyRects[0], button_icon_rect); + DestroySucceededTestSoon(); + } + break; + case OSR_TEST_RESIZE: + if (StartTest()) { + browser->GetHost()->WasResized(); + } else { + EXPECT_EQ(GetScaledInt(kOsrWidth) * 2, width); + EXPECT_EQ(GetScaledInt(kOsrHeight) * 2, height); + EXPECT_EQ(dirtyRects.size(), 1U); + EXPECT_TRUE(IsFullRepaint(dirtyRects[0], width, height)); + DestroySucceededTestSoon(); + } + break; + case OSR_TEST_INVALIDATE: { + if (StartTest()) { + browser->GetHost()->Invalidate(PET_VIEW); + } else { + EXPECT_EQ(dirtyRects.size(), 1U); + EXPECT_EQ(dirtyRects[0], + GetScaledRect(CefRect(0, 0, kOsrWidth, kOsrHeight))); + DestroySucceededTestSoon(); + } + break; + } + case OSR_TEST_KEY_EVENTS: + if (StartTest()) { + // click inside edit box + CefMouseEvent mouse_event; + mouse_event.x = MiddleX(kEditBoxRect); + mouse_event.y = MiddleY(kEditBoxRect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, false, 1); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, true, 1); + + // write "done" word + CefKeyEvent event; + event.is_system_key = false; + event.modifiers = 0; + + size_t word_length = strlen(kKeyTestWord); + for (size_t i = 0; i < word_length; ++i) { +#if defined(OS_WIN) + BYTE VkCode = LOBYTE(VkKeyScanA(kKeyTestWord[i])); + UINT scanCode = MapVirtualKey(VkCode, MAPVK_VK_TO_VSC); + event.native_key_code = (scanCode << 16) | // key scan code + 1; // key repeat count + event.windows_key_code = VkCode; +#elif defined(OS_MACOSX) + osr_unittests::GetKeyEvent(event, kKeyTestCodes[i], 0); +#elif defined(OS_LINUX) + event.native_key_code = kNativeKeyTestCodes[i]; + event.windows_key_code = kKeyTestCodes[i]; + event.character = event.unmodified_character = + kNativeKeyTestCodes[i]; +#else + NOTREACHED(); +#endif + event.type = KEYEVENT_RAWKEYDOWN; + browser->GetHost()->SendKeyEvent(event); +#if defined(OS_WIN) + event.windows_key_code = kKeyTestWord[i]; +#elif defined(OS_MACOSX) + osr_unittests::GetKeyEvent(event, kKeyTestCodes[i], 0); +#elif defined(OS_LINUX) + event.native_key_code = kNativeKeyTestCodes[i]; + event.windows_key_code = kKeyTestCodes[i]; + event.character = event.unmodified_character = + kNativeKeyTestCodes[i]; +#endif + event.type = KEYEVENT_CHAR; + browser->GetHost()->SendKeyEvent(event); +#if defined(OS_WIN) + event.windows_key_code = VkCode; + // bits 30 and 31 should be always 1 for WM_KEYUP + event.native_key_code |= 0xC0000000; +#elif defined(OS_MACOSX) + osr_unittests::GetKeyEvent(event, kKeyTestCodes[i], 0); +#elif defined(OS_LINUX) + event.native_key_code = kKeyTestCodes[i]; +#endif + event.type = KEYEVENT_KEYUP; + browser->GetHost()->SendKeyEvent(event); + } + // click button to navigate + mouse_event.x = MiddleX(kNavigateButtonRect); + mouse_event.y = MiddleY(kNavigateButtonRect); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, false, 1); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, true, 1); + } + break; + case OSR_TEST_TOOLTIP: + if (StartTest()) { + CefMouseEvent mouse_event; + const CefRect& expected_rect = GetExpectedRect(10); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseMoveEvent(mouse_event, false); + } + break; + case OSR_TEST_SCROLLING: { + static const int deltaY = 10; + if (StartTest()) { + // scroll down once + CefMouseEvent mouse_event; + const CefRect& expected_rect = GetExpectedRect(0); + mouse_event.x = MiddleX(expected_rect); + mouse_event.y = MiddleY(expected_rect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseWheelEvent(mouse_event, 0, - deltaY); + } else { + EXPECT_EQ(dirtyRects.size(), 1U); +#if defined(OS_MACOSX) + const CefRect& expected_rect1 = + GetScaledRect(CefRect(0, 0, kOsrWidth, kOsrHeight)); + const CefRect& expected_rect2 = + GetScaledRect(CefRect(0, 0, kOsrWidth - kVerticalScrollbarWidth, + kOsrHeight)); + EXPECT_TRUE(dirtyRects[0] == expected_rect1 || + dirtyRects[0] == expected_rect2); +#else + const CefRect& expected_rect = + GetScaledRect(CefRect(0, 0, kOsrWidth, kOsrHeight)); + EXPECT_EQ(expected_rect, dirtyRects[0]); +#endif + DestroySucceededTestSoon(); + } + break; + } + case OSR_TEST_POPUP_HIDE_ON_CLICK: + if (StartTest()) { + ExpandDropDown(); + // Wait for the first popup paint to occur + } else if (type == PET_POPUP) { + CefMouseEvent mouse_event; + mouse_event.x = 1; + mouse_event.y = 1; + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, false, 1); + } + break; + case OSR_TEST_POPUP_HIDE_ON_SCROLL: + if (StartTest()) { + ExpandDropDown(); + // Wait for the first popup paint to occur + } else if (type == PET_POPUP) { + CefMouseEvent mouse_event; + mouse_event.x = mouse_event.y = 1; + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseWheelEvent(mouse_event, 0, -10); + } + break; + case OSR_TEST_POPUP_HIDE_ON_BLUR: + if (StartTest()) { + ExpandDropDown(); + // Wait for the first popup paint to occur + } else if (type == PET_POPUP) { + browser->GetHost()->SendFocusEvent(false); + } + break; + case OSR_TEST_POPUP_HIDE_ON_ESC: + if (StartTest()) { + ExpandDropDown(); + // Wait for the first popup paint to occur + } else if (type == PET_POPUP) { + CefKeyEvent event; + event.is_system_key = false; +#if defined(OS_WIN) + BYTE VkCode = LOBYTE(VK_ESCAPE); + UINT scanCode = MapVirtualKey(VkCode, MAPVK_VK_TO_VSC); + event.native_key_code = (scanCode << 16) | // key scan code + 1; // key repeat count + event.windows_key_code = VkCode; +#elif defined(OS_MACOSX) + osr_unittests::GetKeyEvent(event, ui::VKEY_ESCAPE, 0); +#elif defined(OS_LINUX) + event.windows_key_code = ui::VKEY_ESCAPE; + event.native_key_code = XK_Escape; + event.character = event.unmodified_character = XK_Escape; +#else +#error "Unsupported platform" +#endif // defined(OS_WIN) + event.type = KEYEVENT_CHAR; + browser->GetHost()->SendKeyEvent(event); + } + break; + case OSR_TEST_POPUP_SHOW: + case OSR_TEST_POPUP_SIZE: + if (StartTest()) { + ExpandDropDown(); + } + break; + case OSR_TEST_POPUP_PAINT: + if (StartTest()) { + ExpandDropDown(); + } else if (type == PET_POPUP) { + EXPECT_EQ(dirtyRects.size(), 1U); + const CefRect& expanded_select_rect = + GetScaledRect(kExpandedSelectRect); + EXPECT_EQ(dirtyRects[0], + CefRect(0, 0, + expanded_select_rect.width, + expanded_select_rect.height)); + // first pixel of border + EXPECT_EQ(*(reinterpret_cast(buffer)), 0xff7f9db9); + EXPECT_EQ(expanded_select_rect.width, width); + EXPECT_EQ(expanded_select_rect.height, height); + DestroySucceededTestSoon(); + } + break; + case OSR_TEST_POPUP_SCROLL_INSIDE: + { + static enum {NotStarted, Started, Scrolled} + scroll_inside_state = NotStarted; + if (StartTest()) { + ExpandDropDown(); + scroll_inside_state = Started; + } else if (type == PET_POPUP) { + if (scroll_inside_state == Started) { + CefMouseEvent mouse_event; + mouse_event.x = MiddleX(kExpandedSelectRect); + mouse_event.y = MiddleY(kExpandedSelectRect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseWheelEvent(mouse_event, 0, -10); + scroll_inside_state = Scrolled; + } else if (scroll_inside_state == Scrolled) { + const CefRect& expanded_select_rect = + GetScaledRect(kExpandedSelectRect); + EXPECT_EQ(dirtyRects.size(), 1U); + EXPECT_EQ(dirtyRects[0], + CefRect(0, + 0, + expanded_select_rect.width, + expanded_select_rect.height)); + DestroySucceededTestSoon(); + } + } + } + break; + case OSR_TEST_DRAG_DROP_START_DRAGGING: + case OSR_TEST_DRAG_DROP_UPDATE_CURSOR: + case OSR_TEST_DRAG_DROP_DROP: + { + // trigger the StartDragging event + if (StartTest()) { + // move the mouse over the element to drag + CefMouseEvent mouse_event; + mouse_event.x = MiddleX(kDragDivRect); + mouse_event.y = MiddleY(kDragDivRect); + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseMoveEvent(mouse_event, false); + // click on the element to drag + mouse_event.modifiers = EVENTFLAG_LEFT_MOUSE_BUTTON; + browser->GetHost()->SendMouseClickEvent(mouse_event, MBT_LEFT, + false, 1); + // move the mouse to start dragging + mouse_event.x -= 5; + mouse_event.y -= 5; + browser->GetHost()->SendMouseMoveEvent(mouse_event, false); + } + } + break; + default: + break; + } + } + + void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor, + CursorType type, + const CefCursorInfo& custom_cursor_info) override { + if (test_type_ == OSR_TEST_CURSOR && started()) { + EXPECT_EQ(CT_HAND, type); + EXPECT_EQ(NULL, custom_cursor_info.buffer); + DestroySucceededTestSoon(); + } + } + + bool StartDragging(CefRefPtr browser, + CefRefPtr drag_data, + DragOperationsMask allowed_ops, + int x, int y) override { + if (test_type_ == OSR_TEST_DRAG_DROP_START_DRAGGING && started()) { + DestroySucceededTestSoon(); + return false; + } else if ((test_type_ == OSR_TEST_DRAG_DROP_UPDATE_CURSOR || + test_type_ == OSR_TEST_DRAG_DROP_DROP) && started()) { + // place the mouse over the drop area to trigger UpdateDragCursor + CefRefPtr data = drag_data->Clone(); + data->ResetFileContents(); + CefMouseEvent ev; + ev.x = MiddleX(kDragDivRect) - 5; + ev.y = MiddleY(kDragDivRect) - 5; + ev.modifiers = EVENTFLAG_LEFT_MOUSE_BUTTON; + browser->GetHost()->DragTargetDragEnter(data, ev, allowed_ops); + + ev.x = MiddleX(kDropDivRect); + ev.y = MiddleY(kDropDivRect); + browser->GetHost()->SendMouseMoveEvent(ev, false); + browser->GetHost()->DragTargetDragOver(ev, allowed_ops); + + ev.x += 5; + ev.y += 5; + browser->GetHost()->SendMouseMoveEvent(ev, false); + browser->GetHost()->DragTargetDragOver(ev, allowed_ops); + return true; + } + return false; + } + + void UpdateDragCursor(CefRefPtr browser, + DragOperation operation) override { + if (test_type_ == OSR_TEST_DRAG_DROP_UPDATE_CURSOR && started()) { + if (operation != DRAG_OPERATION_NONE) { + browser->GetHost()->DragSourceEndedAt(MiddleX(kDropDivRect), + MiddleY(kDropDivRect), + DRAG_OPERATION_NONE); + browser->GetHost()->DragSourceSystemDragEnded(); + DestroySucceededTestSoon(); + } + } else if (test_type_ == OSR_TEST_DRAG_DROP_DROP && started()) { + // Don't end the drag multiple times. + if (got_update_cursor_) + return; + got_update_cursor_.yes(); + + CefMouseEvent ev; + ev.x = MiddleX(kDropDivRect); + ev.y = MiddleY(kDropDivRect); + ev.modifiers = 0; + browser->GetHost()->SendMouseClickEvent(ev, MBT_LEFT, true, 1); + browser->GetHost()->DragTargetDrop(ev); + browser->GetHost()->DragSourceEndedAt(ev.x, ev.y, operation); + browser->GetHost()->DragSourceSystemDragEnded(); + } + } + + bool OnTooltip(CefRefPtr browser, + CefString& text) override { + if (test_type_ == OSR_TEST_TOOLTIP && started()) { + EXPECT_STREQ("EXPECTED_TOOLTIP", text.ToString().c_str()); + DestroySucceededTestSoon(); + } + return false; + } + + void OnBeforeContextMenu(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr params, + CefRefPtr model) override { + if (!started()) + return; + if (test_type_ == OSR_TEST_CLICK_RIGHT) { + const CefRect& expected_rect = GetExpectedRect(4); + EXPECT_EQ(params->GetXCoord(), MiddleX(expected_rect)); + EXPECT_EQ(params->GetYCoord(), MiddleY(expected_rect)); + DestroySucceededTestSoon(); + } else if (test_type_ == OSR_TEST_CONTEXT_MENU) { + // This test will pass if it does not crash on destruction + DestroySucceededTestSoon(); + } + } + + // OSRTestHandler functions + void CreateOSRBrowser(const CefString& url) { + CefWindowInfo windowInfo; + CefBrowserSettings settings; + + const bool transparent = (test_type_ == OSR_TEST_TRANSPARENCY); + +#if defined(OS_WIN) + windowInfo.SetAsWindowless(GetDesktopWindow(), transparent); +#elif defined(OS_MACOSX) + // An actual vies is needed only for the ContextMenu test. The menu runner + // checks if the view is not nil before showing the context menu. + if (test_type_ == OSR_TEST_CONTEXT_MENU) + windowInfo.SetAsWindowless(osr_unittests::GetFakeView(), transparent); + else + windowInfo.SetAsWindowless(kNullWindowHandle, transparent); +#elif defined(OS_LINUX) + windowInfo.SetAsWindowless(kNullWindowHandle, transparent); +#else +#error "Unsupported platform" +#endif + CefBrowserHost::CreateBrowser(windowInfo, this, url, settings, NULL); + } + + CefRect GetScaledRect(const CefRect& rect) const { + const gfx::Rect& gfx_rect = gfx::ConvertRectToPixel( + scale_factor_, + gfx::Rect(rect.x, rect.y, rect.width, rect.height)); + return CefRect(gfx_rect.x(), gfx_rect.y(), + gfx_rect.width(), gfx_rect.height()); + } + + int GetScaledInt(int value) const { + const gfx::Point& gfx_point = gfx::ConvertPointToPixel( + scale_factor_, gfx::Point(value, 0)); + return gfx_point.x(); + } + + CefRect GetExpectedRect(int index) { + CefRect rect = kExpectedRectLI[index]; +#if defined(OS_WIN) || defined(OS_LINUX) + // Adjust the rect to include system vertical scrollbar width. + rect.width += kDefaultVerticalScrollbarWidth - kVerticalScrollbarWidth; +#elif !defined(OS_MACOSX) + #error "Unsupported platform" +#endif + + return rect; + } + + static bool IsFullRepaint(const CefRect& rc, int width, int height) { + return rc.width == width && rc.height == height; + } + + static bool IsBackgroundInBuffer(const uint32* buffer, size_t size, + uint32 rgba) { + for (size_t i = 0; i < size; i++) { + if (buffer[i] != rgba) { + return false; + } + } + return true; + } + + static inline int MiddleX(const CefRect& rect) { + return rect.x + rect.width / 2; + } + + static inline int MiddleY(const CefRect& rect) { + return rect.y + rect.height / 2; + } + + void DestroySucceededTestSoon() { + if (succeeded()) + return; + if (++event_count_ == event_total_) + CefPostTask(TID_UI, base::Bind(&OSRTestHandler::DestroyTest, this)); + } + + void ExpandDropDown() { + GetBrowser()->GetHost()->SendFocusEvent(true); + CefMouseEvent mouse_event; + mouse_event.x = MiddleX(kSelectRect); + mouse_event.y = MiddleY(kSelectRect); + mouse_event.modifiers = 0; + GetBrowser()->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, false, 1); + } + + // true if the events for this test are already sent + bool started() { return started_; } + + // true if the exit point was reached, even the result is not + // the expected one + bool succeeded() { return (event_count_ == event_total_); } + + // will mark test as started and will return true only the first time + // it is called + bool StartTest() { + if (started_) + return false; + started_ = true; + return true; + } + + private: + OSRTestType test_type_; + float scale_factor_; + int event_count_; + int event_total_; + bool started_; + TrackCallback got_update_cursor_; + + IMPLEMENT_REFCOUNTING(OSRTestHandler); +}; + +} // namespace + +// generic test +#define OSR_TEST(name, test_mode, scale_factor)\ +TEST(OSRTest, name) {\ + CefRefPtr handler = \ + new OSRTestHandler(test_mode, scale_factor);\ + handler->ExecuteTest();\ + EXPECT_TRUE(handler->succeeded());\ + ReleaseAndWaitForDestructor(handler);\ +} + +// tests +OSR_TEST(Windowless, OSR_TEST_IS_WINDOWLESS, 1.0f); +OSR_TEST(Windowless2x, OSR_TEST_IS_WINDOWLESS, 2.0f); +OSR_TEST(Focus, OSR_TEST_FOCUS, 1.0f); +OSR_TEST(Focus2x, OSR_TEST_FOCUS, 2.0f); +OSR_TEST(Paint, OSR_TEST_PAINT, 1.0f); +OSR_TEST(Paint2x, OSR_TEST_PAINT, 2.0f); +OSR_TEST(TransparentPaint, OSR_TEST_TRANSPARENCY, 1.0f); +OSR_TEST(TransparentPaint2x, OSR_TEST_TRANSPARENCY, 2.0f); +OSR_TEST(Cursor, OSR_TEST_CURSOR, 1.0f); +OSR_TEST(Cursor2x, OSR_TEST_CURSOR, 2.0f); +OSR_TEST(MouseMove, OSR_TEST_MOUSE_MOVE, 1.0f); +OSR_TEST(MouseMove2x, OSR_TEST_MOUSE_MOVE, 2.0f); +OSR_TEST(MouseRightClick, OSR_TEST_CLICK_RIGHT, 1.0f); +OSR_TEST(MouseRightClick2x, OSR_TEST_CLICK_RIGHT, 2.0f); +OSR_TEST(MouseLeftClick, OSR_TEST_CLICK_LEFT, 1.0f); +OSR_TEST(MouseLeftClick2x, OSR_TEST_CLICK_LEFT, 2.0f); +#if !defined(OS_WIN) +// The middle mouse click scroll icon is not currently shown on Windows. +OSR_TEST(MouseMiddleClick, OSR_TEST_CLICK_MIDDLE, 1.0f); +OSR_TEST(MouseMiddleClick2x, OSR_TEST_CLICK_MIDDLE, 2.0f); +#endif +OSR_TEST(ScreenPoint, OSR_TEST_SCREEN_POINT, 1.0f); +OSR_TEST(ScreenPoint2x, OSR_TEST_SCREEN_POINT, 2.0f); +OSR_TEST(Resize, OSR_TEST_RESIZE, 1.0f); +OSR_TEST(Resize2x, OSR_TEST_RESIZE, 2.0f); +OSR_TEST(Invalidate, OSR_TEST_INVALIDATE, 1.0f); +OSR_TEST(Invalidate2x, OSR_TEST_INVALIDATE, 2.0f); +OSR_TEST(KeyEvents, OSR_TEST_KEY_EVENTS, 1.0f); +OSR_TEST(KeyEvents2x, OSR_TEST_KEY_EVENTS, 2.0f); +OSR_TEST(Tooltip, OSR_TEST_TOOLTIP, 1.0f); +OSR_TEST(Tooltip2x, OSR_TEST_TOOLTIP, 2.0f); +OSR_TEST(Scrolling, OSR_TEST_SCROLLING, 1.0f); +OSR_TEST(Scrolling2x, OSR_TEST_SCROLLING, 2.0f); +OSR_TEST(ContextMenu, OSR_TEST_CONTEXT_MENU, 1.0f); +OSR_TEST(ContextMenu2x, OSR_TEST_CONTEXT_MENU, 2.0f); +OSR_TEST(PopupPaint, OSR_TEST_POPUP_PAINT, 1.0f); +OSR_TEST(PopupPaint2x, OSR_TEST_POPUP_PAINT, 2.0f); +OSR_TEST(PopupShow, OSR_TEST_POPUP_SHOW, 1.0f); +OSR_TEST(PopupShow2x, OSR_TEST_POPUP_SHOW, 2.0f); +OSR_TEST(PopupSize, OSR_TEST_POPUP_SIZE, 1.0f); +OSR_TEST(PopupSize2x, OSR_TEST_POPUP_SIZE, 2.0f); +OSR_TEST(PopupHideOnBlur, OSR_TEST_POPUP_HIDE_ON_BLUR, 1.0f); +OSR_TEST(PopupHideOnBlur2x, OSR_TEST_POPUP_HIDE_ON_BLUR, 2.0f); +OSR_TEST(PopupHideOnClick, OSR_TEST_POPUP_HIDE_ON_CLICK, 1.0f); +OSR_TEST(PopupHideOnClick2x, OSR_TEST_POPUP_HIDE_ON_CLICK, 2.0f); +OSR_TEST(PopupHideOnScroll, OSR_TEST_POPUP_HIDE_ON_SCROLL, 1.0f); +OSR_TEST(PopupHideOnScroll2x, OSR_TEST_POPUP_HIDE_ON_SCROLL, 2.0f); +OSR_TEST(PopupHideOnEsc, OSR_TEST_POPUP_HIDE_ON_ESC, 1.0f); +OSR_TEST(PopupHideOnEsc2x, OSR_TEST_POPUP_HIDE_ON_ESC, 2.0f); +OSR_TEST(PopupScrollInside, OSR_TEST_POPUP_SCROLL_INSIDE, 1.0f); +OSR_TEST(PopupScrollInside2x, OSR_TEST_POPUP_SCROLL_INSIDE, 2.0f); +OSR_TEST(DragDropStartDragging, OSR_TEST_DRAG_DROP_START_DRAGGING, 1.0f); +OSR_TEST(DragDropStartDragging2x, OSR_TEST_DRAG_DROP_START_DRAGGING, 2.0f); +OSR_TEST(DragDropUpdateCursor, OSR_TEST_DRAG_DROP_UPDATE_CURSOR, 1.0f); +OSR_TEST(DragDropUpdateCursor2x, OSR_TEST_DRAG_DROP_UPDATE_CURSOR, 2.0f); +OSR_TEST(DragDropDropElement, OSR_TEST_DRAG_DROP_DROP, 1.0f); +OSR_TEST(DragDropDropElement2x, OSR_TEST_DRAG_DROP_DROP, 2.0f); diff --git a/tests/unittests/os_rendering_unittest_mac.h b/tests/unittests/os_rendering_unittest_mac.h new file mode 100644 index 000000000..e1df01d1a --- /dev/null +++ b/tests/unittests/os_rendering_unittest_mac.h @@ -0,0 +1,18 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +#ifndef CEF_TESTS_UNITTESTS_OS_RENDERING_UNITTEST_MAC_H_ +#define CEF_TESTS_UNITTESTS_OS_RENDERING_UNITTEST_MAC_H_ + +#include "include/cef_base.h" +#include "ui/events/keycodes/keyboard_codes.h" + +namespace osr_unittests { + +CefWindowHandle GetFakeView(); +void GetKeyEvent(CefKeyEvent& event, ui::KeyboardCode keyCode, int modifiers); + +} // namespace osr_unittests + +#endif diff --git a/tests/unittests/os_rendering_unittest_mac.mm b/tests/unittests/os_rendering_unittest_mac.mm new file mode 100644 index 000000000..75251a0df --- /dev/null +++ b/tests/unittests/os_rendering_unittest_mac.mm @@ -0,0 +1,42 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#import +#import + +#include "os_rendering_unittest_mac.h" + +#include "ui/events/keycodes/keyboard_code_conversion_mac.h" + +#include "include/cef_base.h" + +namespace osr_unittests { + +CefWindowHandle GetFakeView() { + NSScreen *mainScreen = [NSScreen mainScreen]; + NSRect screenRect = [mainScreen visibleFrame]; + NSView* fakeView = [[NSView alloc] initWithFrame: screenRect]; + return fakeView; +} + +void GetKeyEvent(CefKeyEvent& event, ui::KeyboardCode keyCode, int modifiers) { + unichar character; + unichar unmodified_character; + + // TODO(port): translate modifiers from the input format to NSFlags + // MacKeyCodeForWindowsKeyCode takes a NSUinteger as flags. + int macKeyCode = ui::MacKeyCodeForWindowsKeyCode(keyCode, + modifiers, + &character, + &unmodified_character); + + event.native_key_code = macKeyCode; + event.character = character; + event.unmodified_character = unmodified_character; +} + +} // namespace osr_unittests diff --git a/tests/unittests/print_unittest.cc b/tests/unittests/print_unittest.cc new file mode 100644 index 000000000..eae9352c7 --- /dev/null +++ b/tests/unittests/print_unittest.cc @@ -0,0 +1,104 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_print_settings.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +bool IsEqual(CefRefPtr expected, + CefRefPtr actual) { + if (expected->IsLandscape() != actual->IsLandscape() || + expected->GetDeviceName() != actual->GetDeviceName() || + expected->GetDPI() != actual->GetDPI() || + expected->GetPageRangesCount() != actual->GetPageRangesCount() || + expected->IsSelectionOnly() != actual->IsSelectionOnly() || + expected->WillCollate() != actual->WillCollate() || + expected->GetColorModel() != actual->GetColorModel() || + expected->GetCopies() != actual->GetCopies() || + expected->GetDuplexMode() != actual->GetDuplexMode()) { + return false; + } + + CefPrintSettings::PageRangeList expected_ranges, actual_ranges; + expected->GetPageRanges(expected_ranges); + actual->GetPageRanges(actual_ranges); + return std::equal(expected_ranges.begin(), + expected_ranges.begin() + expected_ranges.size(), + actual_ranges.begin()); +} + +} // namespace + +// Verify Set/Get methods for CefPrintSettings. +TEST(PrintTest, SettingsSetGet) { + // CefRequest CreateRequest + CefRefPtr settings(CefPrintSettings::Create()); + EXPECT_TRUE(settings.get() != NULL); + EXPECT_TRUE(settings->IsValid()); + EXPECT_FALSE(settings->IsReadOnly()); + + bool landscape = true; + settings->SetOrientation(landscape); + EXPECT_EQ(landscape, settings->IsLandscape()); + landscape = false; + settings->SetOrientation(landscape); + EXPECT_EQ(landscape, settings->IsLandscape()); + + const char device_name[] = "my_device_name"; + settings->SetDeviceName(device_name); + EXPECT_STREQ(device_name, settings->GetDeviceName().ToString().c_str()); + + int dpi = 25; + settings->SetDPI(dpi); + EXPECT_EQ(dpi, settings->GetDPI()); + + CefPrintSettings::PageRangeList page_ranges; + page_ranges.push_back(CefPageRange(1, 3)); + page_ranges.push_back(CefPageRange(5, 6)); + settings->SetPageRanges(page_ranges); + EXPECT_EQ(page_ranges.size(), settings->GetPageRangesCount()); + CefPrintSettings::PageRangeList page_ranges2; + settings->GetPageRanges(page_ranges2); + EXPECT_EQ(page_ranges.size(), page_ranges2.size()); + for (size_t i = 0; i < page_ranges.size(); ++i) + EXPECT_EQ(page_ranges[i], page_ranges2[i]); + + bool selection_only = true; + settings->SetSelectionOnly(selection_only); + EXPECT_EQ(selection_only, settings->IsSelectionOnly()); + selection_only = false; + settings->SetSelectionOnly(selection_only); + EXPECT_EQ(selection_only, settings->IsSelectionOnly()); + + bool collate = true; + settings->SetCollate(collate); + EXPECT_EQ(collate, settings->WillCollate()); + collate = false; + settings->SetCollate(collate); + EXPECT_EQ(collate, settings->WillCollate()); + + CefPrintSettings::ColorModel color_model = COLOR_MODEL_CMYK; + settings->SetColorModel(color_model); + EXPECT_EQ(color_model, settings->GetColorModel()); + + int copies = 3; + settings->SetCopies(copies); + EXPECT_EQ(copies, settings->GetCopies()); + + CefPrintSettings::DuplexMode duplex_mode = DUPLEX_MODE_SIMPLEX; + settings->SetDuplexMode(duplex_mode); + EXPECT_EQ(duplex_mode, settings->GetDuplexMode()); + + CefRefPtr settings2 = settings->Copy(); + EXPECT_TRUE(IsEqual(settings, settings2)); + + settings2->SetOrientation(!landscape); + EXPECT_FALSE(IsEqual(settings, settings2)); +} diff --git a/tests/unittests/process_message_unittest.cc b/tests/unittests/process_message_unittest.cc new file mode 100644 index 000000000..12ad6bd28 --- /dev/null +++ b/tests/unittests/process_message_unittest.cc @@ -0,0 +1,163 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_process_message.h" +#include "include/cef_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_util.h" + +using client::ClientApp; + +namespace { + +// Unique values for the SendRecv test. +const char kSendRecvUrl[] = "http://tests/ProcessMessageTest.SendRecv"; +const char kSendRecvMsg[] = "ProcessMessageTest.SendRecv"; + +// Creates a test message. +CefRefPtr CreateTestMessage() { + CefRefPtr msg = CefProcessMessage::Create(kSendRecvMsg); + EXPECT_TRUE(msg.get()); + + CefRefPtr args = msg->GetArgumentList(); + EXPECT_TRUE(args.get()); + + int index = 0; + args->SetNull(index++); + args->SetInt(index++, 5); + args->SetDouble(index++, 10.543); + args->SetBool(index++, true); + args->SetString(index++, "test string"); + args->SetList(index++, args->Copy()); + + EXPECT_EQ((size_t)index, args->GetSize()); + + return msg; +} + +// Renderer side. +class SendRecvRendererTest : public ClientApp::RenderDelegate { + public: + SendRecvRendererTest() {} + + bool OnProcessMessageReceived( + CefRefPtr app, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (message->GetName() == kSendRecvMsg) { + EXPECT_TRUE(browser.get()); + EXPECT_EQ(PID_BROWSER, source_process); + EXPECT_TRUE(message.get()); + + std::string url = browser->GetMainFrame()->GetURL(); + if (url == kSendRecvUrl) { + // Echo the message back to the sender natively. + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, message)); + return true; + } + } + + // Message not handled. + return false; + } + + IMPLEMENT_REFCOUNTING(SendRecvRendererTest); +}; + +// Browser side. +class SendRecvTestHandler : public TestHandler { + public: + SendRecvTestHandler() { + } + + void RunTest() override { + message_ = CreateTestMessage(); + + AddResource(kSendRecvUrl, "TEST", "text/html"); + CreateBrowser(kSendRecvUrl); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + // Send the message to the renderer process. + EXPECT_TRUE(browser->SendProcessMessage(PID_RENDERER, message_)); + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + EXPECT_TRUE(browser.get()); + EXPECT_EQ(PID_RENDERER, source_process); + EXPECT_TRUE(message.get()); + EXPECT_TRUE(message->IsReadOnly()); + + // Verify that the recieved message is the same as the sent message. + TestProcessMessageEqual(message_, message); + + got_message_.yes(); + + // Test is complete. + DestroyTest(); + + return true; + } + + CefRefPtr message_; + TrackCallback got_message_; +}; + +} // namespace + +// Verify send and recieve. +TEST(ProcessMessageTest, SendRecv) { + CefRefPtr handler = new SendRecvTestHandler(); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_message_); + + ReleaseAndWaitForDestructor(handler); +} + +// Verify create. +TEST(ProcessMessageTest, Create) { + CefRefPtr message = + CefProcessMessage::Create(kSendRecvMsg); + EXPECT_TRUE(message.get()); + EXPECT_TRUE(message->IsValid()); + EXPECT_FALSE(message->IsReadOnly()); + EXPECT_STREQ(kSendRecvMsg, message->GetName().ToString().c_str()); + + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->IsValid()); + EXPECT_TRUE(args->IsOwned()); + EXPECT_FALSE(args->IsReadOnly()); +} + +// Verify copy. +TEST(ProcessMessageTest, Copy) { + CefRefPtr message = CreateTestMessage(); + CefRefPtr message2 = message->Copy(); + TestProcessMessageEqual(message, message2); +} + + +// Entry point for creating process message renderer test objects. +// Called from client_app_delegates.cc. +void CreateProcessMessageRendererTests( + ClientApp::RenderDelegateSet& delegates) { + // For ProcessMessageTest.SendRecv + delegates.insert(new SendRecvRendererTest); +} diff --git a/tests/unittests/request_context_unittest.cc b/tests/unittests/request_context_unittest.cc new file mode 100644 index 000000000..bbe3bcd2e --- /dev/null +++ b/tests/unittests/request_context_unittest.cc @@ -0,0 +1,489 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/base/cef_bind.h" +#include "include/cef_request_context.h" +#include "include/cef_request_context_handler.h" +#include "include/wrapper/cef_closure_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/unittests/test_handler.h" + +TEST(RequestContextTest, GetGlobalContext) { + CefRefPtr context1 = + CefRequestContext::GetGlobalContext(); + EXPECT_TRUE(context1.get()); + EXPECT_TRUE(context1->IsGlobal()); + EXPECT_TRUE(context1->IsSame(context1)); + + CefRefPtr context2 = + CefRequestContext::GetGlobalContext(); + EXPECT_TRUE(context2.get()); + EXPECT_TRUE(context2->IsGlobal()); + EXPECT_TRUE(context2->IsSame(context2)); + + EXPECT_TRUE(context1->IsSame(context2)); + EXPECT_TRUE(context2->IsSame(context1)); +} + +TEST(RequestContextTest, CreateContext) { + class Handler : public CefRequestContextHandler { + public: + Handler() {} + CefRefPtr GetCookieManager() override { return NULL; } + private: + IMPLEMENT_REFCOUNTING(Handler); + }; + + CefRefPtr handler = new Handler(); + + CefRefPtr context1 = + CefRequestContext::CreateContext(handler.get()); + EXPECT_TRUE(context1.get()); + EXPECT_FALSE(context1->IsGlobal()); + EXPECT_TRUE(context1->IsSame(context1)); + EXPECT_EQ(context1->GetHandler().get(), handler.get()); + + CefRefPtr context2 = + CefRequestContext::CreateContext(handler.get()); + EXPECT_TRUE(context2.get()); + EXPECT_FALSE(context2->IsGlobal()); + EXPECT_TRUE(context2->IsSame(context2)); + EXPECT_EQ(context2->GetHandler().get(), handler.get()); + + EXPECT_FALSE(context1->IsSame(context2)); + EXPECT_FALSE(context2->IsSame(context1)); + + CefRefPtr context3 = + CefRequestContext::GetGlobalContext(); + EXPECT_TRUE(context3.get()); + EXPECT_FALSE(context3->IsSame(context1)); + EXPECT_FALSE(context3->IsSame(context2)); + EXPECT_FALSE(context1->IsSame(context3)); + EXPECT_FALSE(context2->IsSame(context3)); +} + +TEST(RequestContextTest, CreateContextNoHandler) { + CefRefPtr context1 = + CefRequestContext::CreateContext(NULL); + EXPECT_TRUE(context1.get()); + EXPECT_FALSE(context1->IsGlobal()); + EXPECT_TRUE(context1->IsSame(context1)); + EXPECT_FALSE(context1->GetHandler().get()); + + CefRefPtr context2 = + CefRequestContext::CreateContext(NULL); + EXPECT_TRUE(context2.get()); + EXPECT_FALSE(context2->IsGlobal()); + EXPECT_TRUE(context2->IsSame(context2)); + EXPECT_FALSE(context2->GetHandler().get()); + + EXPECT_FALSE(context1->IsSame(context2)); + EXPECT_FALSE(context2->IsSame(context1)); + + CefRefPtr context3 = + CefRequestContext::GetGlobalContext(); + EXPECT_TRUE(context3.get()); + EXPECT_FALSE(context3->IsSame(context1)); + EXPECT_FALSE(context3->IsSame(context2)); + EXPECT_FALSE(context1->IsSame(context3)); + EXPECT_FALSE(context2->IsSame(context3)); +} + +namespace { + +class CookieTestHandler : public TestHandler { + public: + class RequestContextHandler : public CefRequestContextHandler { + public: + explicit RequestContextHandler(CookieTestHandler* handler) + : handler_(handler) {} + + CefRefPtr GetCookieManager() override { + EXPECT_TRUE(handler_); + handler_->got_get_cookie_manager_.yes(); + return handler_->cookie_manager_; + } + + void Detach() { + handler_ = NULL; + } + + private: + CookieTestHandler* handler_; + + IMPLEMENT_REFCOUNTING(RequestContextHandler); + }; + + CookieTestHandler(const std::string& url) + : url_(url) {} + + void RunTest() override { + AddResource(url_, + "" + "" + "Nav1" + "", "text/html"); + + context_handler_ = new RequestContextHandler(this); + context_ = CefRequestContext::CreateContext(context_handler_.get()); + cookie_manager_ = CefCookieManager::CreateManager(CefString(), true); + + // Create browser that loads the 1st URL. + CreateBrowser(url_, context_); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + CefRefPtr context = browser->GetHost()->GetRequestContext(); + EXPECT_TRUE(context.get()); + EXPECT_TRUE(context->IsSame(context_)); + EXPECT_FALSE(context->IsGlobal()); + EXPECT_EQ(context->GetHandler().get(), context_handler_.get()); + + FinishTest(); + } + + protected: + void FinishTest() { + // Verify that the cookie was set correctly. + class TestVisitor : public CefCookieVisitor { + public: + explicit TestVisitor(CookieTestHandler* handler) + : handler_(handler) { + } + ~TestVisitor() override { + // Destroy the test. + CefPostTask(TID_UI, + base::Bind(&CookieTestHandler::DestroyTest, handler_)); + } + + bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) override { + const std::string& name = CefString(&cookie.name); + const std::string& value = CefString(&cookie.value); + if (name == "name1" && value == "value1") + handler_->got_cookie_.yes(); + return true; + } + + private: + CookieTestHandler* handler_; + IMPLEMENT_REFCOUNTING(TestVisitor); + }; + + cookie_manager_->VisitAllCookies(new TestVisitor(this)); + } + + void DestroyTest() override { + // Verify test expectations. + EXPECT_TRUE(got_get_cookie_manager_); + EXPECT_TRUE(got_cookie_); + + context_handler_->Detach(); + context_handler_ = NULL; + context_ = NULL; + + TestHandler::DestroyTest(); + } + + std::string url_; + CefRefPtr context_; + CefRefPtr context_handler_; + CefRefPtr cookie_manager_; + + TrackCallback got_get_cookie_manager_; + TrackCallback got_cookie_; +}; + +} // namespace + +// Test that the cookie manager is retrieved via the associated request context. +TEST(RequestContextTest, GetCookieManager) { + CefRefPtr handler = + new CookieTestHandler( + "http://tests-simple-rch.com/nav1.html"); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +namespace { + +class PopupTestHandler : public TestHandler { + public: + class RequestContextHandler : public CefRequestContextHandler { + public: + explicit RequestContextHandler(PopupTestHandler* handler) + : handler_(handler) {} + + CefRefPtr GetCookieManager() override { + EXPECT_TRUE(handler_); + if (url_ == handler_->url_) + handler_->got_get_cookie_manager1_.yes(); + else if (url_ == handler_->popup_url_) + handler_->got_get_cookie_manager2_.yes(); + return handler_->cookie_manager_; + } + + void SetURL(const std::string& url) { + url_ = url; + } + + void Detach() { + handler_ = NULL; + } + + private: + PopupTestHandler* handler_; + std::string url_; + + IMPLEMENT_REFCOUNTING(RequestContextHandler); + }; + + enum Mode { + MODE_WINDOW_OPEN, + MODE_TARGETED_LINK, + MODE_NOREFERRER_LINK, + }; + + PopupTestHandler(bool same_origin, + Mode mode) + : mode_(mode) { + url_ = "http://tests-simple-rch1.com/nav1.html"; + if (same_origin) + popup_url_ = "http://tests-simple-rch1.com/pop1.html"; + else + popup_url_ = "http://tests-simple-rch2.com/pop1.html"; + } + + void RunTest() override { + std::string link; + if (mode_ == MODE_TARGETED_LINK) { + link = "CLICK ME"; + } else if (mode_ == MODE_NOREFERRER_LINK) { + link = "CLICK ME"; + } + + AddResource(url_, + "" + "" + "

" + link + "

" + "", "text/html"); + + AddResource(popup_url_, + "" + "" + "Nav1" + "", "text/html"); + + context_handler_ = new RequestContextHandler(this); + context_handler_->SetURL(url_); + context_ = CefRequestContext::CreateContext(context_handler_.get()); + cookie_manager_ = CefCookieManager::CreateManager(CefString(), true); + + // Create browser that loads the 1st URL. + CreateBrowser(url_, context_); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + CefRefPtr context = browser->GetHost()->GetRequestContext(); + EXPECT_TRUE(context.get()); + EXPECT_TRUE(context->IsSame(context_)); + EXPECT_FALSE(context->IsGlobal()); + + EXPECT_TRUE(frame->IsMain()); + + const std::string& url = frame->GetURL(); + if (url == url_) { + got_load_end1_.yes(); + context_handler_->SetURL(popup_url_); + LaunchPopup(browser); + } if (url == popup_url_) { + got_load_end2_.yes(); + EXPECT_TRUE(browser->IsPopup()); + // Close the popup window. + browser->GetHost()->CloseBrowser(true); + } + } + + bool OnBeforePopup(CefRefPtr browser, + CefRefPtr frame, + const CefString& target_url, + const CefString& target_frame_name, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + CefRefPtr& client, + CefBrowserSettings& settings, + bool* no_javascript_access) override { + got_on_before_popup_.yes(); + + const std::string& url = target_url; + EXPECT_STREQ(url.c_str(), popup_url_.c_str()); + return false; + } + + void OnBeforeClose(CefRefPtr browser) override { + TestHandler::OnBeforeClose(browser); + + if (browser->IsPopup()) + FinishTest(); + } + + protected: + void LaunchPopup(CefRefPtr browser) { + if (mode_ == MODE_WINDOW_OPEN) { + browser->GetMainFrame()->ExecuteJavaScript("doPopup()", url_, 0); + } else if (mode_ == MODE_TARGETED_LINK || + mode_ == MODE_NOREFERRER_LINK) { + CefMouseEvent mouse_event; + mouse_event.x = 20; + mouse_event.y = 20; + mouse_event.modifiers = 0; + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, false, 1); + browser->GetHost()->SendMouseClickEvent( + mouse_event, MBT_LEFT, true, 1); + } else { + EXPECT_TRUE(false); // Not reached. + } + } + + void FinishTest() { + // Verify that the cookies were set correctly. + class TestVisitor : public CefCookieVisitor { + public: + explicit TestVisitor(PopupTestHandler* handler) + : handler_(handler) { + } + ~TestVisitor() override { + // Destroy the test. + CefPostTask(TID_UI, + base::Bind(&PopupTestHandler::DestroyTest, handler_)); + } + + bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) override { + const std::string& name = CefString(&cookie.name); + const std::string& value = CefString(&cookie.value); + if (name == "name1" && value == "value1") + handler_->got_cookie1_.yes(); + else if (name == "name2" && value == "value2") + handler_->got_cookie2_.yes(); + return true; + } + + private: + PopupTestHandler* handler_; + IMPLEMENT_REFCOUNTING(TestVisitor); + }; + + cookie_manager_->VisitAllCookies(new TestVisitor(this)); + } + + void DestroyTest() override { + // Verify test expectations. + EXPECT_TRUE(got_get_cookie_manager1_); + EXPECT_TRUE(got_load_end1_); + EXPECT_TRUE(got_on_before_popup_); + EXPECT_TRUE(got_get_cookie_manager2_); + EXPECT_TRUE(got_load_end2_); + EXPECT_TRUE(got_cookie1_); + EXPECT_TRUE(got_cookie2_); + + context_handler_->Detach(); + context_handler_ = NULL; + context_ = NULL; + + TestHandler::DestroyTest(); + } + + std::string url_; + std::string popup_url_; + Mode mode_; + + CefRefPtr context_; + CefRefPtr context_handler_; + CefRefPtr cookie_manager_; + + TrackCallback got_get_cookie_manager1_; + TrackCallback got_load_end1_; + TrackCallback got_on_before_popup_; + TrackCallback got_get_cookie_manager2_; + TrackCallback got_load_end2_; + TrackCallback got_cookie1_; + TrackCallback got_cookie2_; +}; + +} // namespace + +// Test that a popup created using window.open() will get the same request +// context as the parent browser. +TEST(RequestContextTest, WindowOpenSameOrigin) { + CefRefPtr handler = + new PopupTestHandler(true, + PopupTestHandler::MODE_WINDOW_OPEN); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(RequestContextTest, WindowOpenDifferentOrigin) { + CefRefPtr handler = + new PopupTestHandler(false, + PopupTestHandler::MODE_WINDOW_OPEN); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +// Test that a popup created using a targeted link will get the same request +// context as the parent browser. +TEST(RequestContextTest, TargetedLinkSameOrigin) { + CefRefPtr handler = + new PopupTestHandler(true, + PopupTestHandler::MODE_TARGETED_LINK); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(RequestContextTest, TargetedLinkDifferentOrigin) { + CefRefPtr handler = + new PopupTestHandler(false, + PopupTestHandler::MODE_TARGETED_LINK); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + + +// Test that a popup created using a noreferrer link will get the same +// request context as the parent browser. A new render process will +// be created for the popup browser. +TEST(RequestContextTest, NoReferrerLinkSameOrigin) { + CefRefPtr handler = + new PopupTestHandler(true, + PopupTestHandler::MODE_NOREFERRER_LINK); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + +TEST(RequestContextTest, NoReferrerLinkDifferentOrigin) { + CefRefPtr handler = + new PopupTestHandler(false, + PopupTestHandler::MODE_NOREFERRER_LINK); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} diff --git a/tests/unittests/request_handler_unittest.cc b/tests/unittests/request_handler_unittest.cc new file mode 100644 index 000000000..37c97e147 --- /dev/null +++ b/tests/unittests/request_handler_unittest.cc @@ -0,0 +1,518 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "base/strings/stringprintf.h" + +#include "include/base/cef_bind.h" +#include "include/cef_cookie.h" +#include "include/wrapper/cef_closure_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" + +using client::ClientApp; + +namespace { + +enum NetNotifyTestType { + NNTT_NONE = 0, + NNTT_NORMAL, + NNTT_DELAYED_RENDERER, + NNTT_DELAYED_BROWSER, +}; + +const char kNetNotifyOrigin1[] = "http://tests-netnotify1/"; +const char kNetNotifyOrigin2[] = "http://tests-netnotify2/"; +const char kNetNotifyMsg[] = "RequestHandlerTest.NetNotify"; + +bool g_net_notify_test = false; + +// Browser side. +class NetNotifyBrowserTest : public ClientApp::BrowserDelegate { + public: + NetNotifyBrowserTest() {} + + void OnBeforeChildProcessLaunch( + CefRefPtr app, + CefRefPtr command_line) override { + if (!g_net_notify_test) + return; + + // Indicate to the render process that the test should be run. + command_line->AppendSwitchWithValue("test", kNetNotifyMsg); + } + + protected: + IMPLEMENT_REFCOUNTING(NetNotifyBrowserTest); +}; + +// Browser side. +class NetNotifyTestHandler : public TestHandler { + public: + class RequestContextHandler : public CefRequestContextHandler { + public: + explicit RequestContextHandler(NetNotifyTestHandler* handler) + : handler_(handler) {} + + CefRefPtr GetCookieManager() override { + EXPECT_TRUE(handler_); + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + if (url_.find(handler_->url1_) == 0) + handler_->got_get_cookie_manager1_.yes(); + else if (url_.find(handler_->url2_) == 0) + handler_->got_get_cookie_manager2_.yes(); + else + EXPECT_TRUE(false); // Not reached + + return handler_->cookie_manager_; + } + + void SetURL(const std::string& url) { + url_ = url; + } + + void Detach() { + handler_ = NULL; + } + + private: + std::string url_; + NetNotifyTestHandler* handler_; + + IMPLEMENT_REFCOUNTING(RequestContextHandler); + }; + + NetNotifyTestHandler(CompletionState* completion_state, + NetNotifyTestType test_type, + bool same_origin) + : TestHandler(completion_state), + test_type_(test_type), + same_origin_(same_origin) {} + + void SetupTest() override { + url1_ = base::StringPrintf("%snav1.html?t=%d", + kNetNotifyOrigin1, test_type_); + url2_ = base::StringPrintf("%snav2.html?t=%d", + same_origin_ ? kNetNotifyOrigin1 : kNetNotifyOrigin2, test_type_); + + cookie_manager_ = CefCookieManager::CreateManager(CefString(), true); + + AddResource(url1_, + "" + "" + "Nav1" + "", "text/html"); + AddResource(url2_, + "" + "" + "Nav2" + "", "text/html"); + + context_handler_ = new RequestContextHandler(this); + context_handler_->SetURL(url1_); + + // Create browser that loads the 1st URL. + CreateBrowser(url1_, + CefRequestContext::CreateContext(context_handler_.get())); + } + + void RunTest() override { + // Navigate to the 2nd URL. + context_handler_->SetURL(url2_); + GetBrowser()->GetMainFrame()->LoadURL(url2_); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + const std::string& url = request->GetURL(); + if (url.find(url1_) == 0) + got_before_resource_load1_.yes(); + else if (url.find(url2_) == 0) + got_before_resource_load2_.yes(); + else + EXPECT_TRUE(false); // Not reached + + return false; + } + + CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + const std::string& url = request->GetURL(); + if (url.find(url1_) == 0) + got_get_resource_handler1_.yes(); + else if (url.find(url2_) == 0) + got_get_resource_handler2_.yes(); + else + EXPECT_TRUE(false); // Not reached + + return TestHandler::GetResourceHandler(browser, frame, request); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + std::string url = request->GetURL(); + + // Check if the load has already been delayed. + bool delay_loaded = (url.find("delayed=true") != std::string::npos); + + if (url.find(url1_) == 0) { + got_before_browse1_.yes(); + EXPECT_FALSE(delay_loaded); + } else if (url.find(url2_) == 0) { + got_before_browse2_.yes(); + if (delay_loaded) { + got_before_browse2_delayed_.yes(); + } else if (test_type_ == NNTT_DELAYED_RENDERER || + test_type_ == NNTT_DELAYED_BROWSER) { + got_before_browse2_will_delay_.yes(); + + // Navigating cross-origin from the browser process will cause a new + // render process to be created. We therefore need some information in + // the request itself to tell us that the navigation has already been + // delayed. + url += "&delayed=true"; + + if (test_type_ == NNTT_DELAYED_RENDERER) { + // Load the URL from the render process. + CefRefPtr message = + CefProcessMessage::Create(kNetNotifyMsg); + CefRefPtr args = message->GetArgumentList(); + args->SetInt(0, test_type_); + args->SetString(1, url); + EXPECT_TRUE(browser->SendProcessMessage(PID_RENDERER, message)); + } else { + // Load the URL from the browser process. + browser->GetMainFrame()->LoadURL(url); + } + + // Cancel the load. + return true; + } + } else { + EXPECT_TRUE(false); // Not reached + } + + // Allow the load to continue. + return false; + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + const std::string& url = frame->GetURL(); + if (url.find(url1_) == 0) { + got_load_end1_.yes(); + SetupCompleteIfDone(); + } else if (url.find(url2_) == 0) { + got_load_end2_.yes(); + FinishTestIfDone(); + } else { + EXPECT_TRUE(false); // Not reached + } + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (message->GetName().ToString() == kNetNotifyMsg) { + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + + std::string url = args->GetString(0); + if (url.find(url1_) == 0) { + got_process_message1_.yes(); + SetupCompleteIfDone(); + } else if (url.find(url2_) == 0) { + got_process_message2_.yes(); + FinishTestIfDone(); + } else { + EXPECT_TRUE(false); // Not reached + } + + return true; + } + + // Message not handled. + return false; + } + + protected: + void SetupCompleteIfDone() { + if (got_load_end1_ && got_process_message1_) + SetupComplete(); + } + + void FinishTestIfDone() { + if (got_load_end2_ && got_process_message2_) + FinishTest(); + } + + void FinishTest() { + // Verify that cookies were set correctly. + class TestVisitor : public CefCookieVisitor { + public: + explicit TestVisitor(NetNotifyTestHandler* handler) + : handler_(handler) { + } + ~TestVisitor() override { + // Destroy the test. + CefPostTask(TID_UI, + base::Bind(&NetNotifyTestHandler::DestroyTest, handler_)); + } + + bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) override { + const std::string& name = CefString(&cookie.name); + const std::string& value = CefString(&cookie.value); + if (name == "name1" && value == "value1") + handler_->got_cookie1_.yes(); + else if (name == "name2" && value == "value2") + handler_->got_cookie2_.yes(); + return true; + } + + private: + NetNotifyTestHandler* handler_; + IMPLEMENT_REFCOUNTING(TestVisitor); + }; + + cookie_manager_->VisitAllCookies(new TestVisitor(this)); + } + + void DestroyTest() override { + int browser_id = GetBrowser()->GetIdentifier(); + + // Verify test expectations. + EXPECT_TRUE(got_before_browse1_) << " browser " << browser_id; + EXPECT_TRUE(got_load_end1_) << " browser " << browser_id; + EXPECT_TRUE(got_before_resource_load1_) << " browser " << browser_id; + EXPECT_TRUE(got_get_resource_handler1_) << " browser " << browser_id; + EXPECT_TRUE(got_get_cookie_manager1_) << " browser " << browser_id; + EXPECT_TRUE(got_cookie1_) << " browser " << browser_id; + EXPECT_TRUE(got_process_message1_) << " browser " << browser_id; + EXPECT_TRUE(got_before_browse2_) << " browser " << browser_id; + EXPECT_TRUE(got_load_end2_) << " browser " << browser_id; + EXPECT_TRUE(got_before_resource_load2_) << " browser " << browser_id; + EXPECT_TRUE(got_get_resource_handler2_) << " browser " << browser_id; + EXPECT_TRUE(got_get_cookie_manager2_) << " browser " << browser_id; + EXPECT_TRUE(got_cookie2_) << " browser " << browser_id; + EXPECT_TRUE(got_process_message2_) << " browser " << browser_id; + + if (test_type_ == NNTT_DELAYED_RENDERER || + test_type_ == NNTT_DELAYED_BROWSER) { + EXPECT_TRUE(got_before_browse2_will_delay_) << " browser " << browser_id; + EXPECT_TRUE(got_before_browse2_delayed_) << " browser " << browser_id; + } else { + EXPECT_FALSE(got_before_browse2_will_delay_) << " browser " << browser_id; + EXPECT_FALSE(got_before_browse2_delayed_) << " browser " << browser_id; + } + + context_handler_->Detach(); + context_handler_ = NULL; + cookie_manager_ = NULL; + + TestHandler::DestroyTest(); + } + + NetNotifyTestType test_type_; + bool same_origin_; + std::string url1_; + std::string url2_; + + CefRefPtr context_handler_; + + CefRefPtr cookie_manager_; + + TrackCallback got_before_browse1_; + TrackCallback got_load_end1_; + TrackCallback got_before_resource_load1_; + TrackCallback got_get_resource_handler1_; + TrackCallback got_get_cookie_manager1_; + TrackCallback got_cookie1_; + TrackCallback got_process_message1_; + TrackCallback got_before_browse2_; + TrackCallback got_load_end2_; + TrackCallback got_before_resource_load2_; + TrackCallback got_get_resource_handler2_; + TrackCallback got_get_cookie_manager2_; + TrackCallback got_cookie2_; + TrackCallback got_process_message2_; + TrackCallback got_before_browse2_will_delay_; + TrackCallback got_before_browse2_delayed_; +}; + +// Renderer side. +class NetNotifyRendererTest : public ClientApp::RenderDelegate, + public CefLoadHandler { + public: + NetNotifyRendererTest() + : run_test_(false) {} + + void OnRenderThreadCreated( + CefRefPtr app, + CefRefPtr extra_info) override { + if (!g_net_notify_test) { + // Check that the test should be run. + CefRefPtr command_line = + CefCommandLine::GetGlobalCommandLine(); + const std::string& test = command_line->GetSwitchValue("test"); + if (test != kNetNotifyMsg) + return; + } + + run_test_ = true; + } + + CefRefPtr GetLoadHandler( + CefRefPtr app) override { + if (run_test_) + return this; + return NULL; + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + if (!run_test_) + return; + + const std::string& url = frame->GetURL(); + + // Continue in the browser process. + CefRefPtr message = + CefProcessMessage::Create(kNetNotifyMsg); + CefRefPtr args = message->GetArgumentList(); + args->SetString(0, url); + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, message)); + } + + bool OnProcessMessageReceived( + CefRefPtr app, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + if (message->GetName().ToString() == kNetNotifyMsg) { + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + + NetNotifyTestType test_type = + static_cast(args->GetInt(0)); + EXPECT_EQ(test_type, NNTT_DELAYED_RENDERER); + + const std::string& url = args->GetString(1); + + // Load the URL from the render process. + browser->GetMainFrame()->LoadURL(url); + return true; + } + + // Message not handled. + return false; + } + + private: + bool run_test_; + + IMPLEMENT_REFCOUNTING(NetNotifyRendererTest); +}; + +void RunNetNotifyTest(NetNotifyTestType test_type, bool same_origin) { + g_net_notify_test = true; + + TestHandler::CompletionState completion_state(3); + + CefRefPtr handler1 = + new NetNotifyTestHandler(&completion_state, test_type, same_origin); + CefRefPtr handler2 = + new NetNotifyTestHandler(&completion_state, test_type, same_origin); + CefRefPtr handler3 = + new NetNotifyTestHandler(&completion_state, test_type, same_origin); + + TestHandler::Collection collection(&completion_state); + collection.AddTestHandler(handler1.get()); + collection.AddTestHandler(handler2.get()); + collection.AddTestHandler(handler3.get()); + + collection.ExecuteTests(); + + ReleaseAndWaitForDestructor(handler1); + ReleaseAndWaitForDestructor(handler2); + ReleaseAndWaitForDestructor(handler3); + + g_net_notify_test = false; +} + +} // namespace + +// Verify network notifications for multiple browsers existing simultaniously. +// URL loading is from the same origin and is not delayed. +TEST(RequestHandlerTest, NotificationsSameOriginDirect) { + RunNetNotifyTest(NNTT_NORMAL, true); +} + +// Verify network notifications for multiple browsers existing simultaniously. +// URL loading is from the same origin and is continued asynchronously from the +// render process. +TEST(RequestHandlerTest, NotificationsSameOriginDelayedRenderer) { + RunNetNotifyTest(NNTT_DELAYED_RENDERER, true); +} + +// Verify network notifications for multiple browsers existing simultaniously. +// URL loading is from the same origin and is continued asynchronously from the +// browser process. +TEST(RequestHandlerTest, NotificationsSameOriginDelayedBrowser) { + RunNetNotifyTest(NNTT_DELAYED_BROWSER, true); +} + +// Verify network notifications for multiple browsers existing simultaniously. +// URL loading is from a different origin and is not delayed. +TEST(RequestHandlerTest, NotificationsCrossOriginDirect) { + RunNetNotifyTest(NNTT_NORMAL, false); +} + +// Verify network notifications for multiple browsers existing simultaniously. +// URL loading is from a different origin and is continued asynchronously from +// the render process. +TEST(RequestHandlerTest, NotificationsCrossOriginDelayedRenderer) { + RunNetNotifyTest(NNTT_DELAYED_RENDERER, false); +} + +// Verify network notifications for multiple browsers existing simultaniously. +// URL loading is from a different origin and is continued asynchronously from +// the browser process. +TEST(RequestHandlerTest, NotificationsCrossOriginDelayedBrowser) { + RunNetNotifyTest(NNTT_DELAYED_BROWSER, false); +} + + +// Entry point for creating request handler browser test objects. +// Called from client_app_delegates.cc. +void CreateRequestHandlerBrowserTests( + ClientApp::BrowserDelegateSet& delegates) { + delegates.insert(new NetNotifyBrowserTest); +} + +// Entry point for creating request handler renderer test objects. +// Called from client_app_delegates.cc. +void CreateRequestHandlerRendererTests( + ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new NetNotifyRendererTest); +} diff --git a/tests/unittests/request_unittest.cc b/tests/unittests/request_unittest.cc new file mode 100644 index 000000000..2755bc1ac --- /dev/null +++ b/tests/unittests/request_unittest.cc @@ -0,0 +1,548 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/base/cef_bind.h" +#include "include/cef_request.h" +#include "include/wrapper/cef_closure_task.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_util.h" + +using client::ClientApp; + +// Verify Set/Get methods for CefRequest, CefPostData and CefPostDataElement. +TEST(RequestTest, SetGet) { + // CefRequest CreateRequest + CefRefPtr request(CefRequest::Create()); + ASSERT_TRUE(request.get() != NULL); + + CefString url = "http://tests/run.html"; + CefString method = "POST"; + CefRequest::HeaderMap setHeaders, getHeaders; + setHeaders.insert(std::make_pair("HeaderA", "ValueA")); + setHeaders.insert(std::make_pair("HeaderB", "ValueB")); + + // CefPostData CreatePostData + CefRefPtr postData(CefPostData::Create()); + ASSERT_TRUE(postData.get() != NULL); + + // CefPostDataElement CreatePostDataElement + CefRefPtr element1(CefPostDataElement::Create()); + ASSERT_TRUE(element1.get() != NULL); + CefRefPtr element2(CefPostDataElement::Create()); + ASSERT_TRUE(element2.get() != NULL); + + // CefPostDataElement SetToFile + CefString file = "c:\\path\\to\\file.ext"; + element1->SetToFile(file); + ASSERT_EQ(PDE_TYPE_FILE, element1->GetType()); + ASSERT_EQ(file, element1->GetFile()); + + // CefPostDataElement SetToBytes + char bytes[] = "Test Bytes"; + element2->SetToBytes(sizeof(bytes), bytes); + ASSERT_EQ(PDE_TYPE_BYTES, element2->GetType()); + ASSERT_EQ(sizeof(bytes), element2->GetBytesCount()); + char bytesOut[sizeof(bytes)]; + element2->GetBytes(sizeof(bytes), bytesOut); + ASSERT_TRUE(!memcmp(bytes, bytesOut, sizeof(bytes))); + + // CefPostData AddElement + postData->AddElement(element1); + postData->AddElement(element2); + ASSERT_EQ((size_t)2, postData->GetElementCount()); + + // CefPostData RemoveElement + postData->RemoveElement(element1); + ASSERT_EQ((size_t)1, postData->GetElementCount()); + + // CefPostData RemoveElements + postData->RemoveElements(); + ASSERT_EQ((size_t)0, postData->GetElementCount()); + + postData->AddElement(element1); + postData->AddElement(element2); + ASSERT_EQ((size_t)2, postData->GetElementCount()); + CefPostData::ElementVector elements; + postData->GetElements(elements); + CefPostData::ElementVector::const_iterator it = elements.begin(); + for (size_t i = 0; it != elements.end(); ++it, ++i) { + if (i == 0) + TestPostDataElementEqual(element1, (*it).get()); + else if (i == 1) + TestPostDataElementEqual(element2, (*it).get()); + } + + // CefRequest SetURL + request->SetURL(url); + ASSERT_EQ(url, request->GetURL()); + + // CefRequest SetMethod + request->SetMethod(method); + ASSERT_EQ(method, request->GetMethod()); + + // CefRequest SetHeaderMap + request->SetHeaderMap(setHeaders); + request->GetHeaderMap(getHeaders); + TestMapEqual(setHeaders, getHeaders, false); + getHeaders.clear(); + + // CefRequest SetPostData + request->SetPostData(postData); + TestPostDataEqual(postData, request->GetPostData()); + + request = CefRequest::Create(); + ASSERT_TRUE(request.get() != NULL); + + // CefRequest Set + request->Set(url, method, postData, setHeaders); + ASSERT_EQ(url, request->GetURL()); + ASSERT_EQ(method, request->GetMethod()); + request->GetHeaderMap(getHeaders); + TestMapEqual(setHeaders, getHeaders, false); + getHeaders.clear(); + TestPostDataEqual(postData, request->GetPostData()); +} + +namespace { + +void CreateRequest(CefRefPtr& request) { + request = CefRequest::Create(); + ASSERT_TRUE(request.get() != NULL); + + request->SetURL("http://tests/run.html"); + request->SetMethod("POST"); + + CefRequest::HeaderMap headers; + headers.insert(std::make_pair("HeaderA", "ValueA")); + headers.insert(std::make_pair("HeaderB", "ValueB")); + request->SetHeaderMap(headers); + + CefRefPtr postData(CefPostData::Create()); + ASSERT_TRUE(postData.get() != NULL); + + CefRefPtr element1( + CefPostDataElement::Create()); + ASSERT_TRUE(element1.get() != NULL); + char bytes[] = "Test Bytes"; + element1->SetToBytes(sizeof(bytes), bytes); + postData->AddElement(element1); + + request->SetPostData(postData); +} + +class RequestSendRecvTestHandler : public TestHandler { + public: + RequestSendRecvTestHandler() {} + + void RunTest() override { + // Create the test request + CreateRequest(request_); + + // Create the browser + CreateBrowser("about:blank"); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnAfterCreated(CefRefPtr browser) override { + TestHandler::OnAfterCreated(browser); + + // Load the test request + browser->GetMainFrame()->LoadRequest(request_); + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + // Verify that the request is the same + TestRequestEqual(request_, request, true); + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + EXPECT_EQ(TT_LINK, request->GetTransitionType()); + + got_before_resource_load_.yes(); + + return false; + } + + CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + // Verify that the request is the same + TestRequestEqual(request_, request, true); + EXPECT_EQ(RT_MAIN_FRAME, request->GetResourceType()); + EXPECT_EQ(TT_LINK, request->GetTransitionType()); + + got_resource_handler_.yes(); + + DestroyTest(); + + // No results + return NULL; + } + + CefRefPtr request_; + + TrackCallback got_before_resource_load_; + TrackCallback got_resource_handler_; +}; + +} // namespace + +// Verify send and recieve +TEST(RequestTest, SendRecv) { + CefRefPtr handler = + new RequestSendRecvTestHandler(); + handler->ExecuteTest(); + + ASSERT_TRUE(handler->got_before_resource_load_); + ASSERT_TRUE(handler->got_resource_handler_); + + ReleaseAndWaitForDestructor(handler); +} + +namespace { + +const char kTypeTestCompleteMsg[] = "RequestTest.Type"; +const char kTypeTestOrigin[] = "http://tests-requesttt.com/"; + +static struct TypeExpected { + const char* file; + bool browser_side; // True if this expectation applies to the browser side. + bool navigation; // True if this expectation represents a navigation. + cef_transition_type_t transition_type; + cef_resource_type_t resource_type; + int expected_count; +} g_type_expected[] = { + // Initial main frame load due to browser creation. + {"main.html", true, true, TT_EXPLICIT, RT_MAIN_FRAME, 1}, + {"main.html", false, true, TT_EXPLICIT, RT_SUB_RESOURCE, 1}, + + // Sub frame load. + {"sub.html", true, true, TT_LINK, RT_SUB_FRAME, 1}, + {"sub.html", false, true, TT_EXPLICIT, RT_SUB_RESOURCE, 1}, + + // Stylesheet load. + {"style.css", true, false, TT_LINK, RT_STYLESHEET, 1}, + + // Script load. + {"script.js", true, false, TT_LINK, RT_SCRIPT, 1}, + + // Image load. + {"image.png", true, false, TT_LINK, RT_IMAGE, 1}, + + // Font load. + {"font.ttf", true, false, TT_LINK, RT_FONT_RESOURCE, 1}, + + // XHR load. + {"xhr.html", true, false, TT_LINK, RT_XHR, 1}, +}; + +class TypeExpectations { + public: + TypeExpectations(bool browser_side, bool navigation) + : browser_side_(browser_side), + navigation_(navigation) { + // Build the map of relevant requests. + for (int i = 0; + i < static_cast(sizeof(g_type_expected) / sizeof(TypeExpected)); + ++i) { + if (g_type_expected[i].browser_side != browser_side_ || + (navigation_ && g_type_expected[i].navigation != navigation_)) + continue; + + request_count_.insert(std::make_pair(i, 0)); + } + } + + // Notify that a request has been received. Returns true if the request is + // something we care about. + bool GotRequest(CefRefPtr request) { + const std::string& url = request->GetURL(); + if (url.find(kTypeTestOrigin) != 0) + return false; + + const std::string& file = url.substr(sizeof(kTypeTestOrigin)-1); + cef_transition_type_t transition_type = request->GetTransitionType(); + cef_resource_type_t resource_type = request->GetResourceType(); + + const int index = GetExpectedIndex(file, transition_type, resource_type); + EXPECT_GE(index, 0) + << "File: " << file.c_str() + << "; Browser Side: " << browser_side_ + << "; Navigation: " << navigation_ + << "; Transition Type: " << transition_type + << "; Resource Type: " << resource_type; + + RequestCount::iterator it = request_count_.find(index); + EXPECT_TRUE(it != request_count_.end()); + + const int actual_count = ++it->second; + const int expected_count = g_type_expected[index].expected_count; + EXPECT_LE(actual_count, expected_count) + << "File: " << file.c_str() + << "; Browser Side: " << browser_side_ + << "; Navigation: " << navigation_ + << "; Transition Type: " << transition_type + << "; Resource Type: " << resource_type; + + return true; + } + + // Test if all expectations have been met. + bool IsDone(bool assert) { + for (int i = 0; + i < static_cast(sizeof(g_type_expected) / sizeof(TypeExpected)); + ++i) { + if (g_type_expected[i].browser_side != browser_side_ || + (navigation_ && g_type_expected[i].navigation != navigation_)) + continue; + + RequestCount::const_iterator it = request_count_.find(i); + EXPECT_TRUE(it != request_count_.end()); + if (it->second != g_type_expected[i].expected_count) { + if (assert) { + EXPECT_EQ(g_type_expected[i].expected_count, it->second) + << "File: " << g_type_expected[i].file + << "; Browser Side: " << browser_side_ + << "; Navigation: " << navigation_ + << "; Transition Type: " << g_type_expected[i].transition_type + << "; Resource Type: " << g_type_expected[i].resource_type; + } + return false; + } + } + return true; + } + + private: + // Returns the index for the specified navigation. + int GetExpectedIndex(const std::string& file, + cef_transition_type_t transition_type, + cef_resource_type_t resource_type) { + for (int i = 0; + i < static_cast(sizeof(g_type_expected) / sizeof(TypeExpected)); + ++i) { + if (g_type_expected[i].file == file && + g_type_expected[i].browser_side == browser_side_ && + (!navigation_ || g_type_expected[i].navigation == navigation_) && + g_type_expected[i].transition_type == transition_type && + g_type_expected[i].resource_type == resource_type) { + return i; + } + } + return -1; + } + + bool browser_side_; + bool navigation_; + + // Map of TypeExpected index to actual request count. + typedef std::map RequestCount; + RequestCount request_count_; +}; + +// Renderer side. +class TypeRendererTest : public ClientApp::RenderDelegate { + public: + TypeRendererTest() : + expectations_(false, true) {} + + bool OnBeforeNavigation(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + cef_navigation_type_t navigation_type, + bool is_redirect) override { + if (expectations_.GotRequest(request) && expectations_.IsDone(false)) + SendTestResults(browser); + return false; + } + + private: + // Send the test results. + void SendTestResults(CefRefPtr browser) { + // Check if the test has failed. + bool result = !TestFailed(); + + // Return the result to the browser process. + CefRefPtr return_msg = + CefProcessMessage::Create(kTypeTestCompleteMsg); + CefRefPtr args = return_msg->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->SetBool(0, result)); + EXPECT_TRUE(browser->SendProcessMessage(PID_BROWSER, return_msg)); + } + + TypeExpectations expectations_; + + IMPLEMENT_REFCOUNTING(TypeRendererTest); +}; + +// Browser side. +class TypeTestHandler : public TestHandler { + public: + TypeTestHandler() : + browse_expectations_(true, true), + load_expectations_(true, false), + get_expectations_(true, false), + completed_browser_side_(false), + completed_render_side_(false), + destroyed_(false) {} + + void RunTest() override { + AddResource(std::string(kTypeTestOrigin) + "main.html", + "" + "" + "" + "" + "" + "

Main

" + "" + "" + "" + "", + "text/html"); + AddResource(std::string(kTypeTestOrigin) + "sub.html", + "Sub", + "text/html"); + AddResource(std::string(kTypeTestOrigin) + "style.css", + "@font-face {" + " font-family: custom_font;" + " src: url('font.ttf');" + "}" + "p {" + " font-family: custom_font;" + "}", + "text/css"); + AddResource(std::string(kTypeTestOrigin) + "script.js", + "", + "text/javascript"); + AddResource(std::string(kTypeTestOrigin) + "image.png", + "", + "image/png"); + AddResource(std::string(kTypeTestOrigin) + "font.ttf", + "", + "font/ttf"); + AddResource(std::string(kTypeTestOrigin) + "xhr.html", + "XHR", + "text/html"); + + CreateBrowser(std::string(kTypeTestOrigin) + "main.html"); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override { + browse_expectations_.GotRequest(request); + + return false; + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + load_expectations_.GotRequest(request); + + return false; + } + + CefRefPtr GetResourceHandler( + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + if (get_expectations_.GotRequest(request) && + get_expectations_.IsDone(false)) { + completed_browser_side_ = true; + // Destroy the test on the UI thread. + CefPostTask(TID_UI, + base::Bind(&TypeTestHandler::DestroyTestIfComplete, this)); + } + + return TestHandler::GetResourceHandler(browser, frame, request); + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + const std::string& msg_name = message->GetName(); + if (msg_name == kTypeTestCompleteMsg) { + // Test that the renderer side succeeded. + CefRefPtr args = message->GetArgumentList(); + EXPECT_TRUE(args.get()); + EXPECT_TRUE(args->GetBool(0)); + + completed_render_side_ = true; + DestroyTestIfComplete(); + return true; + } + + // Message not handled. + return false; + } + + private: + void DestroyTestIfComplete() { + if (destroyed_) + return; + + if (completed_browser_side_ && completed_render_side_) + DestroyTest(); + } + + void DestroyTest() override { + if (destroyed_) + return; + destroyed_ = true; + + // Verify test expectations. + EXPECT_TRUE(completed_browser_side_); + EXPECT_TRUE(completed_render_side_); + EXPECT_TRUE(browse_expectations_.IsDone(true)); + EXPECT_TRUE(load_expectations_.IsDone(true)); + EXPECT_TRUE(get_expectations_.IsDone(true)); + + TestHandler::DestroyTest(); + } + + TypeExpectations browse_expectations_; + TypeExpectations load_expectations_; + TypeExpectations get_expectations_; + + bool completed_browser_side_; + bool completed_render_side_; + bool destroyed_; +}; + +} // namespace + +// Verify the order of navigation-related callbacks. +TEST(RequestTest, ResourceAndTransitionType) { + CefRefPtr handler = + new TypeTestHandler(); + handler->ExecuteTest(); + ReleaseAndWaitForDestructor(handler); +} + + +// Entry point for creating request renderer test objects. +// Called from client_app_delegates.cc. +void CreateRequestRendererTests(ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new TypeRendererTest); +} diff --git a/tests/unittests/routing_test_handler.cc b/tests/unittests/routing_test_handler.cc new file mode 100644 index 000000000..075c92ec2 --- /dev/null +++ b/tests/unittests/routing_test_handler.cc @@ -0,0 +1,109 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "tests/unittests/routing_test_handler.h" +#include "tests/cefclient/client_app.h" + +using client::ClientApp; + +namespace { + +void SetRouterConfig(CefMessageRouterConfig& config) { + config.js_query_function = "testQuery"; + config.js_cancel_function = "testQueryCancel"; +} + +// Handle the renderer side of the routing implementation. +class RoutingRenderDelegate : public ClientApp::RenderDelegate { + public: + RoutingRenderDelegate() {} + + void OnWebKitInitialized(CefRefPtr app) override { + // Create the renderer-side router for query handling. + CefMessageRouterConfig config; + SetRouterConfig(config); + message_router_ = CefMessageRouterRendererSide::Create(config); + } + + void OnContextCreated(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) override { + message_router_->OnContextCreated(browser, frame, context); + } + + void OnContextReleased(CefRefPtr app, + CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) override { + message_router_->OnContextReleased(browser, frame, context); + } + + bool OnProcessMessageReceived( + CefRefPtr app, + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + return message_router_->OnProcessMessageReceived( + browser, source_process, message); + } + + private: + CefRefPtr message_router_; + + IMPLEMENT_REFCOUNTING(RoutingRenderDelegate); +}; + +} // namespace + +RoutingTestHandler::RoutingTestHandler() { +} + +void RoutingTestHandler::OnAfterCreated(CefRefPtr browser) { + if (!message_router_.get()) { + // Create the browser-side router for query handling. + CefMessageRouterConfig config; + SetRouterConfig(config); + message_router_ = CefMessageRouterBrowserSide::Create(config); + message_router_->AddHandler(this, false); + } + TestHandler::OnAfterCreated(browser); +} + +void RoutingTestHandler::OnBeforeClose(CefRefPtr browser) { + message_router_->OnBeforeClose(browser); + TestHandler::OnBeforeClose(browser); +} + +void RoutingTestHandler::OnRenderProcessTerminated( + CefRefPtr browser, + TerminationStatus status) { + message_router_->OnRenderProcessTerminated(browser); +} + +bool RoutingTestHandler::OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) { + message_router_->OnBeforeBrowse(browser, frame); + return false; +} + +bool RoutingTestHandler::OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) { + return message_router_->OnProcessMessageReceived( + browser, source_process, message); +} + +// Entry point for creating the test delegate. +// Called from client_app_delegates.cc. +void CreateRoutingTestHandlerDelegate( + ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new RoutingRenderDelegate); +} diff --git a/tests/unittests/routing_test_handler.h b/tests/unittests/routing_test_handler.h new file mode 100644 index 000000000..d8b411a52 --- /dev/null +++ b/tests/unittests/routing_test_handler.h @@ -0,0 +1,44 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#ifndef CEF_TESTS_UNITTESTS_ROUTING_TEST_HANDLER_H_ +#define CEF_TESTS_UNITTESTS_ROUTING_TEST_HANDLER_H_ +#pragma once + +#include "include/wrapper/cef_message_router.h" +#include "tests/unittests/test_handler.h" + +// Extends TestHandler to provide message routing functionality. The +// RoutingTestHandler implementation must be called from subclass +// overrides unless otherwise indicated. +class RoutingTestHandler : + public TestHandler, + public CefMessageRouterBrowserSide::Handler { + public: + RoutingTestHandler(); + + void OnAfterCreated(CefRefPtr browser) override; + void OnBeforeClose(CefRefPtr browser) override; + void OnRenderProcessTerminated( + CefRefPtr browser, + TerminationStatus status) override; + + // Only call this method if the navigation isn't canceled. + bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + bool is_redirect) override; + + // Returns true if the router handled the navigation. + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override; + + private: + CefRefPtr message_router_; +}; + + +#endif // CEF_TESTS_UNITTESTS_ROUTING_TEST_HANDLER_H_ diff --git a/tests/unittests/run_all_unittests.cc b/tests/unittests/run_all_unittests.cc new file mode 100644 index 000000000..02080fb81 --- /dev/null +++ b/tests/unittests/run_all_unittests.cc @@ -0,0 +1,180 @@ +// Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#if defined(OS_LINUX) +#include +// Definitions conflict with gtest. +#undef None +#undef Bool +#endif + +#include "base/threading/thread.h" + +#include "include/base/cef_bind.h" +#include "include/cef_app.h" +#include "include/cef_task.h" +#include "include/wrapper/cef_helpers.h" +#include "include/wrapper/cef_closure_task.h" +#include "tests/cefclient/client_app.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_suite.h" + +#if defined(OS_WIN) +#include "include/cef_sandbox_win.h" +#endif + +using client::ClientApp; + +namespace { + +// Thread used to run the test suite. +class CefTestThread : public base::Thread { + public: + explicit CefTestThread(CefTestSuite* test_suite) + : base::Thread("test_thread"), + test_suite_(test_suite) { + } + + void RunTests() { + // Run the test suite. + retval_ = test_suite_->Run(); + + // Wait for all browsers to exit. + while (TestHandler::HasBrowser()) + base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); + + // Quit the CEF message loop. + CefPostTask(TID_UI, base::Bind(&CefQuitMessageLoop)); + } + + int retval() { return retval_; } + + protected: + CefTestSuite* test_suite_; + int retval_; +}; + +// Called on the UI thread. +void RunTests(CefTestThread* thread) { + // Run the test suite on the test thread. + thread->message_loop()->PostTask(FROM_HERE, + base::Bind(&CefTestThread::RunTests, base::Unretained(thread))); +} + +#if defined(OS_LINUX) +int XErrorHandlerImpl(Display *display, XErrorEvent *event) { + LOG(WARNING) + << "X error received: " + << "type " << event->type << ", " + << "serial " << event->serial << ", " + << "error_code " << static_cast(event->error_code) << ", " + << "request_code " << static_cast(event->request_code) << ", " + << "minor_code " << static_cast(event->minor_code); + return 0; +} + +int XIOErrorHandlerImpl(Display *display) { + return 0; +} +#endif // defined(OS_LINUX) + +} // namespace + + +int main(int argc, char* argv[]) { +#if defined(OS_LINUX) + // Create a copy of |argv| on Linux because Chromium mangles the value + // internally (see issue #620). + CefScopedArgArray scoped_arg_array(argc, argv); + char** argv_copy = scoped_arg_array.array(); +#else + char** argv_copy = argv; +#endif + +#if defined(OS_WIN) + CefMainArgs main_args(::GetModuleHandle(NULL)); +#else + CefMainArgs main_args(argc, argv); +#endif + + void* windows_sandbox_info = NULL; + +#if defined(OS_WIN) + // Manages the life span of the sandbox information object. + CefScopedSandboxInfo scoped_sandbox; + windows_sandbox_info = scoped_sandbox.sandbox_info(); +#endif + + CefRefPtr app(new client::ClientApp); + + // Execute the secondary process, if any. + int exit_code = CefExecuteProcess(main_args, app, windows_sandbox_info); + if (exit_code >= 0) + return exit_code; + + // Initialize the CommandLine object. + CefTestSuite::InitCommandLine(argc, argv_copy); + + CefSettings settings; + CefTestSuite::GetSettings(settings); + +#if defined(OS_MACOSX) + // Platform-specific initialization. + extern void PlatformInit(); + PlatformInit(); +#endif + +#if defined(OS_LINUX) + // Install xlib error handlers so that the application won't be terminated + // on non-fatal errors. + XSetErrorHandler(XErrorHandlerImpl); + XSetIOErrorHandler(XIOErrorHandlerImpl); +#endif + + // Initialize CEF. + CefInitialize(main_args, settings, app, windows_sandbox_info); + + // Create the test suite object. TestSuite will modify |argv_copy|. + CefTestSuite test_suite(argc, argv_copy); + + int retval; + + if (settings.multi_threaded_message_loop) { + // Run the test suite on the main thread. + retval = test_suite.Run(); + } else { + // Create the test thread. + scoped_ptr thread; + thread.reset(new CefTestThread(&test_suite)); + if (!thread->Start()) + return 1; + + // Start the tests from the UI thread so that any pending UI tasks get a + // chance to execute first. + CefPostTask(TID_UI, base::Bind(&RunTests, thread.get())); + + // Run the CEF message loop. + CefRunMessageLoop(); + + // The test suite has completed. + retval = thread->retval(); + + // Terminate the test thread. + thread.reset(); + } + + // Shut down CEF. + CefShutdown(); + +#if defined(OS_MACOSX) + // Platform-specific cleanup. + extern void PlatformCleanup(); + PlatformCleanup(); +#endif + + return retval; +} diff --git a/tests/unittests/run_all_unittests_mac.mm b/tests/unittests/run_all_unittests_mac.mm new file mode 100644 index 000000000..2b81f5f43 --- /dev/null +++ b/tests/unittests/run_all_unittests_mac.mm @@ -0,0 +1,48 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_app.h" +#import "include/cef_application_mac.h" + +// Memory AutoRelease pool. +static NSAutoreleasePool* g_autopool = nil; + +// Provide the CefAppProtocol implementation required by CEF. +@interface TestApplication : NSApplication { +@private + BOOL handlingSendEvent_; +} +@end + +@implementation TestApplication +- (BOOL)isHandlingSendEvent { + return handlingSendEvent_; +} + +- (void)setHandlingSendEvent:(BOOL)handlingSendEvent { + handlingSendEvent_ = handlingSendEvent; +} + +- (void)sendEvent:(NSEvent*)event { + CefScopedSendingEvent sendingEventScoper; + [super sendEvent:event]; +} +@end + +void PlatformInit() { + // Initialize the AutoRelease pool. + g_autopool = [[NSAutoreleasePool alloc] init]; + + // Initialize the TestApplication instance. + [TestApplication sharedApplication]; +} + +void PlatformCleanup() { + // Release the AutoRelease pool. + [g_autopool release]; +} + diff --git a/tests/unittests/scheme_handler_unittest.cc b/tests/unittests/scheme_handler_unittest.cc new file mode 100644 index 000000000..800708f83 --- /dev/null +++ b/tests/unittests/scheme_handler_unittest.cc @@ -0,0 +1,1576 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +#include + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/base/cef_bind.h" +#include "include/cef_origin_whitelist.h" +#include "include/cef_callback.h" +#include "include/cef_scheme.h" +#include "include/wrapper/cef_closure_task.h" +#include "tests/unittests/test_handler.h" + +namespace { + +class TestResults { + public: + TestResults() + : status_code(0), + sub_status_code(0), + delay(0) { + } + + void reset() { + url.clear(); + html.clear(); + status_code = 0; + redirect_url.clear(); + sub_url.clear(); + sub_html.clear(); + sub_status_code = 0; + sub_allow_origin.clear(); + exit_url.clear(); + delay = 0; + got_request.reset(); + got_read.reset(); + got_output.reset(); + got_redirect.reset(); + got_error.reset(); + got_sub_request.reset(); + got_sub_read.reset(); + got_sub_success.reset(); + } + + std::string url; + std::string html; + int status_code; + + // Used for testing redirects + std::string redirect_url; + + // Used for testing XHR requests + std::string sub_url; + std::string sub_html; + int sub_status_code; + std::string sub_allow_origin; + std::string sub_redirect_url; + std::string exit_url; + + // Delay for returning scheme handler results. + int delay; + + TrackCallback + got_request, + got_read, + got_output, + got_redirect, + got_error, + got_sub_redirect, + got_sub_request, + got_sub_read, + got_sub_success; +}; + +// Current scheme handler object. Used when destroying the test from +// ClientSchemeHandler::ProcessRequest(). +class TestSchemeHandler; +TestSchemeHandler* g_current_handler = NULL; + +class TestSchemeHandler : public TestHandler { + public: + explicit TestSchemeHandler(TestResults* tr) + : test_results_(tr) { + g_current_handler = this; + } + + void RunTest() override { + CreateBrowser(test_results_->url); + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + // Necessary to make the method public in order to destroy the test from + // ClientSchemeHandler::ProcessRequest(). + void DestroyTest() { + TestHandler::DestroyTest(); + } + + bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request) override { + std::string newUrl = request->GetURL(); + if (!test_results_->exit_url.empty() && + newUrl.find(test_results_->exit_url) != std::string::npos) { + // XHR tests use an exit URL to destroy the test. + if (newUrl.find("SUCCESS") != std::string::npos) + test_results_->got_sub_success.yes(); + DestroyTest(); + return true; + } + + if (!test_results_->sub_redirect_url.empty() && + newUrl == test_results_->sub_redirect_url) { + test_results_->got_sub_redirect.yes(); + // Redirect to the sub URL. + request->SetURL(test_results_->sub_url); + } else if (newUrl == test_results_->redirect_url) { + test_results_->got_redirect.yes(); + + // No read should have occurred for the redirect. + EXPECT_TRUE(test_results_->got_request); + EXPECT_FALSE(test_results_->got_read); + + // Now loading the redirect URL. + test_results_->url = test_results_->redirect_url; + test_results_->redirect_url.clear(); + } + + return false; + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + std::string url = frame->GetURL(); + if (url == test_results_->url || test_results_->status_code != 200) { + test_results_->got_output.yes(); + + // Test that the status code is correct. + EXPECT_EQ(httpStatusCode, test_results_->status_code); + + if (test_results_->sub_url.empty()) + DestroyTest(); + } + } + + void OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& errorText, + const CefString& failedUrl) override { + test_results_->got_error.yes(); + DestroyTest(); + } + + protected: + TestResults* test_results_; +}; + +class ClientSchemeHandler : public CefResourceHandler { + public: + explicit ClientSchemeHandler(TestResults* tr) + : test_results_(tr), + offset_(0), + is_sub_(false), + has_delayed_(false) { + } + + bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + bool handled = false; + + std::string url = request->GetURL(); + is_sub_ = (!test_results_->sub_url.empty() && + test_results_->sub_url == url); + + if (is_sub_) { + test_results_->got_sub_request.yes(); + + if (!test_results_->sub_html.empty()) + handled = true; + } else { + EXPECT_EQ(url, test_results_->url); + + test_results_->got_request.yes(); + + if (!test_results_->html.empty()) + handled = true; + } + + if (handled) { + if (test_results_->delay > 0) { + // Continue after the delay. + CefPostDelayedTask(TID_IO, + base::Bind(&CefCallback::Continue, callback.get()), + test_results_->delay); + } else { + // Continue immediately. + callback->Continue(); + } + return true; + } + + // Response was canceled. + if (g_current_handler) + g_current_handler->DestroyTest(); + return false; + } + + void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) override { + if (is_sub_) { + response->SetStatus(test_results_->sub_status_code); + + if (!test_results_->sub_allow_origin.empty()) { + // Set the Access-Control-Allow-Origin header to allow cross-domain + // scripting. + CefResponse::HeaderMap headers; + headers.insert(std::make_pair("Access-Control-Allow-Origin", + test_results_->sub_allow_origin)); + response->SetHeaderMap(headers); + } + + if (!test_results_->sub_html.empty()) { + response->SetMimeType("text/html"); + response_length = test_results_->sub_html.size(); + } + } else if (!test_results_->redirect_url.empty()) { + redirectUrl = test_results_->redirect_url; + } else { + response->SetStatus(test_results_->status_code); + + if (!test_results_->html.empty()) { + response->SetMimeType("text/html"); + response_length = test_results_->html.size(); + } + } + } + + void Cancel() override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + } + + bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + + if (test_results_->delay > 0) { + if (!has_delayed_) { + // Continue after a delay. + CefPostDelayedTask(TID_IO, + base::Bind(&ClientSchemeHandler::ContinueAfterDelay, + this, callback), + test_results_->delay); + bytes_read = 0; + return true; + } + + has_delayed_ = false; + } + + std::string* data; + + if (is_sub_) { + test_results_->got_sub_read.yes(); + data = &test_results_->sub_html; + } else { + test_results_->got_read.yes(); + data = &test_results_->html; + } + + bool has_data = false; + bytes_read = 0; + + size_t size = data->size(); + if (offset_ < size) { + int transfer_size = + std::min(bytes_to_read, static_cast(size - offset_)); + memcpy(data_out, data->c_str() + offset_, transfer_size); + offset_ += transfer_size; + + bytes_read = transfer_size; + has_data = true; + } + + return has_data; + } + + private: + void ContinueAfterDelay(CefRefPtr callback) { + has_delayed_ = true; + callback->Continue(); + } + + TestResults* test_results_; + size_t offset_; + bool is_sub_; + bool has_delayed_; + + IMPLEMENT_REFCOUNTING(ClientSchemeHandler); +}; + +class ClientSchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + explicit ClientSchemeHandlerFactory(TestResults* tr) + : test_results_(tr) { + } + + CefRefPtr Create( + CefRefPtr browser, + CefRefPtr frame, + const CefString& scheme_name, + CefRefPtr request) override { + EXPECT_TRUE(CefCurrentlyOn(TID_IO)); + return new ClientSchemeHandler(test_results_); + } + + TestResults* test_results_; + + IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory); +}; + +// Global test results object. +TestResults g_TestResults; + +// If |domain| is empty the scheme will be registered as non-standard. +void RegisterTestScheme(const std::string& scheme, const std::string& domain) { + g_TestResults.reset(); + + EXPECT_TRUE(CefRegisterSchemeHandlerFactory(scheme, domain, + new ClientSchemeHandlerFactory(&g_TestResults))); + WaitForIOThread(); +} + +void ClearTestSchemes() { + EXPECT_TRUE(CefClearSchemeHandlerFactories()); + WaitForIOThread(); +} + +struct XHRTestSettings { + XHRTestSettings() + : synchronous(true) {} + + std::string url; + std::string sub_url; + std::string sub_allow_origin; + std::string sub_redirect_url; + bool synchronous; +}; + +void SetUpXHR(const XHRTestSettings& settings) { + g_TestResults.sub_url = settings.sub_url; + g_TestResults.sub_html = "SUCCESS"; + g_TestResults.sub_status_code = 200; + g_TestResults.sub_allow_origin = settings.sub_allow_origin; + g_TestResults.sub_redirect_url = settings.sub_redirect_url; + + std::string request_url; + if (!settings.sub_redirect_url.empty()) + request_url = settings.sub_redirect_url; + else + request_url = settings.sub_url; + + g_TestResults.url = settings.url; + std::stringstream ss; + ss << "" + "" + "" + "Running execXMLHttpRequest..." + ""; + g_TestResults.html = ss.str(); + g_TestResults.status_code = 200; + + g_TestResults.exit_url = "http://tests/exit"; +} + +void SetUpXSS(const std::string& url, const std::string& sub_url, + const std::string& domain = std::string()) { + // 1. Load |url| which contains an iframe. + // 2. The iframe loads |xss_url|. + // 3. |xss_url| tries to call a JS function in |url|. + // 4. |url| tries to call a JS function in |xss_url|. + + std::stringstream ss; + std::string domain_line; + if (!domain.empty()) + domain_line = "document.domain = '" + domain + "';"; + + g_TestResults.sub_url = sub_url; + ss << "" + "" + "" + "Running execXSSRequest..." + ""; + g_TestResults.sub_html = ss.str(); + g_TestResults.sub_status_code = 200; + + g_TestResults.url = url; + ss.str(""); + ss << "" + "" + "" + "" + "", "text/html"); + AddResource(kV8ContextChildTestUrl, "" + "CHILD", + "text/html"); + CreateBrowser(kV8ContextParentTestUrl); + } else if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION || + test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) { + AddResource(kV8OnUncaughtExceptionTestUrl, "" + "

OnUncaughtException

" + "\n" + "\n", + "text/html"); + CreateBrowser(kV8OnUncaughtExceptionTestUrl); + } else { + EXPECT_TRUE(test_url_ != NULL); + AddResource(test_url_, "" + "TEST", "text/html"); + CreateBrowser(test_url_); + } + + // Time out the test after a reasonable period of time. + SetTestTimeout(); + } + + void OnBeforeClose(CefRefPtr browser) override { + if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS && + browser->IsPopup()) { + // Generate the uncaught exception in the main browser. + GetBrowser()->GetMainFrame()->ExecuteJavaScript( + "window.setTimeout(test, 0);", + GetBrowser()->GetMainFrame()->GetURL(), 0); + } + + TestHandler::OnBeforeClose(browser); + } + + void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) override { + if (test_mode_ == V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS) { + if (!browser->IsPopup()) { + // Create the DevTools window. + CefWindowInfo windowInfo; + CefBrowserSettings settings; + +#if defined(OS_WIN) + windowInfo.SetAsPopup(browser->GetHost()->GetWindowHandle(), "DevTools"); +#endif + + browser->GetHost()->ShowDevTools(windowInfo, this, settings, + CefPoint()); + } + return; + } + + const std::string& url = frame->GetURL(); + if (url != kV8NavTestUrl && url != kV8ContextParentTestUrl && + url.find("http://tests/") != std::string::npos) { + // Run the test. + CefRefPtr return_msg = + CefProcessMessage::Create(kV8RunTestMsg); + EXPECT_TRUE(browser->SendProcessMessage(PID_RENDERER, return_msg)); + } + } + + bool OnProcessMessageReceived( + CefRefPtr browser, + CefProcessId source_process, + CefRefPtr message) override { + EXPECT_TRUE(browser.get()); + EXPECT_EQ(PID_RENDERER, source_process); + EXPECT_TRUE(message.get()); + EXPECT_TRUE(message->IsReadOnly()); + + const std::string& message_name = message->GetName(); + EXPECT_STREQ(kV8TestMsg, message_name.c_str()); + + got_message_.yes(); + + if (message->GetArgumentList()->GetBool(0)) + got_success_.yes(); + + // Test is complete. + DestroyTest(); + + return true; + } + + V8TestMode test_mode_; + const char* test_url_; + TrackCallback got_message_; + TrackCallback got_success_; +}; + +} // namespace + + +// Entry point for creating V8 browser test objects. +// Called from client_app_delegates.cc. +void CreateV8BrowserTests(ClientApp::BrowserDelegateSet& delegates) { + delegates.insert(new V8BrowserTest); +} + +// Entry point for creating V8 renderer test objects. +// Called from client_app_delegates.cc. +void CreateV8RendererTests(ClientApp::RenderDelegateSet& delegates) { + delegates.insert(new V8RendererTest); +} + + +// Helpers for defining V8 tests. +#define V8_TEST_EX(name, test_mode, test_url) \ + TEST(V8Test, name) { \ + g_current_test_mode = test_mode; \ + CefRefPtr handler = \ + new V8TestHandler(test_mode, test_url); \ + handler->ExecuteTest(); \ + EXPECT_TRUE(handler->got_message_); \ + EXPECT_TRUE(handler->got_success_); \ + g_current_test_mode = V8TEST_NONE; \ + ReleaseAndWaitForDestructor(handler); \ + } + +#define V8_TEST(name, test_mode) \ + V8_TEST_EX(name, test_mode, kV8TestUrl) + + +// Define the tests. +V8_TEST(NullCreate, V8TEST_NULL_CREATE); +V8_TEST(BoolCreate, V8TEST_BOOL_CREATE); +V8_TEST(IntCreate, V8TEST_INT_CREATE); +V8_TEST(UIntCreate, V8TEST_UINT_CREATE); +V8_TEST(DoubleCreate, V8TEST_DOUBLE_CREATE); +V8_TEST(DateCreate, V8TEST_DATE_CREATE); +V8_TEST(StringCreate, V8TEST_STRING_CREATE); +V8_TEST(EmptyStringCreate, V8TEST_EMPTY_STRING_CREATE); +V8_TEST(ArrayCreate, V8TEST_ARRAY_CREATE); +V8_TEST(ArrayValue, V8TEST_ARRAY_VALUE); +V8_TEST(ObjectCreate, V8TEST_OBJECT_CREATE); +V8_TEST(ObjectUserData, V8TEST_OBJECT_USERDATA); +V8_TEST(ObjectAccessor, V8TEST_OBJECT_ACCESSOR); +V8_TEST(ObjectAccessorException, V8TEST_OBJECT_ACCESSOR_EXCEPTION); +V8_TEST(ObjectAccessorFail, V8TEST_OBJECT_ACCESSOR_FAIL); +V8_TEST(ObjectAccessorReadOnly, V8TEST_OBJECT_ACCESSOR_READONLY); +V8_TEST(ObjectValue, V8TEST_OBJECT_VALUE); +V8_TEST(ObjectValueReadOnly, V8TEST_OBJECT_VALUE_READONLY); +V8_TEST(ObjectValueEnum, V8TEST_OBJECT_VALUE_ENUM); +V8_TEST(ObjectValueDontEnum, V8TEST_OBJECT_VALUE_DONTENUM); +V8_TEST(ObjectValueDelete, V8TEST_OBJECT_VALUE_DELETE); +V8_TEST(ObjectValueDontDelete, V8TEST_OBJECT_VALUE_DONTDELETE); +V8_TEST(ObjectValueEmptyKey, V8TEST_OBJECT_VALUE_EMPTYKEY); +V8_TEST(FunctionCreate, V8TEST_FUNCTION_CREATE); +V8_TEST(FunctionHandler, V8TEST_FUNCTION_HANDLER); +V8_TEST(FunctionHandlerException, V8TEST_FUNCTION_HANDLER_EXCEPTION); +V8_TEST(FunctionHandlerFail, V8TEST_FUNCTION_HANDLER_FAIL); +V8_TEST(FunctionHandlerNoObject, V8TEST_FUNCTION_HANDLER_NO_OBJECT); +V8_TEST(FunctionHandlerWithContext, V8TEST_FUNCTION_HANDLER_WITH_CONTEXT); +V8_TEST(FunctionHandlerEmptyString, V8TEST_FUNCTION_HANDLER_EMPTY_STRING); +V8_TEST(ContextEval, V8TEST_CONTEXT_EVAL); +V8_TEST(ContextEvalException, V8TEST_CONTEXT_EVAL_EXCEPTION); +V8_TEST_EX(ContextEntered, V8TEST_CONTEXT_ENTERED, NULL); +V8_TEST(ContextInvalid, V8TEST_CONTEXT_INVALID); +V8_TEST_EX(Binding, V8TEST_BINDING, kV8BindingTestUrl); +V8_TEST(StackTrace, V8TEST_STACK_TRACE); +V8_TEST(OnUncaughtException, V8TEST_ON_UNCAUGHT_EXCEPTION); +V8_TEST(OnUncaughtExceptionDevTools, V8TEST_ON_UNCAUGHT_EXCEPTION_DEV_TOOLS); +V8_TEST(Extension, V8TEST_EXTENSION); diff --git a/tests/unittests/values_unittest.cc b/tests/unittests/values_unittest.cc new file mode 100644 index 000000000..c295182f3 --- /dev/null +++ b/tests/unittests/values_unittest.cc @@ -0,0 +1,736 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_task.h" +#include "include/cef_values.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_util.h" + +namespace { + +// Dictionary test keys. +const char* kNullKey = "null_key"; +const char* kBoolKey = "bool_key"; +const char* kIntKey = "int_key"; +const char* kDoubleKey = "double_key"; +const char* kStringKey = "string_key"; +const char* kBinaryKey = "binary_key"; +const char* kDictionaryKey = "dict_key"; +const char* kListKey = "list_key"; + +// List test indexes. +enum { + kNullIndex = 0, + kBoolIndex, + kIntIndex, + kDoubleIndex, + kStringIndex, + kBinaryIndex, + kDictionaryIndex, + kListIndex, +}; + +// Dictionary/list test values. +const bool kBoolValue = true; +const int kIntValue = 12; +const double kDoubleValue = 4.5432; +const char* kStringValue = "My string value"; + + +// BINARY TEST HELPERS + +// Test a binary value. +void TestBinary(CefRefPtr value, char* data, size_t data_size) { + // Testing requires strings longer than 15 characters. + EXPECT_GT(data_size, (size_t)15); + + EXPECT_EQ(data_size, value->GetSize()); + + char* buff = new char[data_size+1]; + char old_char; + + // Test full read. + memset(buff, 0, data_size+1); + EXPECT_EQ(data_size, value->GetData(buff, data_size, 0)); + EXPECT_TRUE(!strcmp(buff, data)); + + // Test partial read with offset. + memset(buff, 0, data_size+1); + old_char = data[15]; + data[15] = 0; + EXPECT_EQ((size_t)10, value->GetData(buff, 10, 5)); + EXPECT_TRUE(!strcmp(buff, data+5)); + data[15] = old_char; + + // Test that changes to the original data have no effect. + memset(buff, 0, data_size+1); + old_char = data[0]; + data[0] = '.'; + EXPECT_EQ((size_t)1, value->GetData(buff, 1, 0)); + EXPECT_EQ(old_char, buff[0]); + data[0] = old_char; + + // Test copy. + CefRefPtr copy = value->Copy(); + TestBinaryEqual(copy, value); + + delete [] buff; +} + +// Used to test access of binary data on a different thread. +class BinaryTask : public CefTask { + public: + BinaryTask(CefRefPtr value, char* data, size_t data_size) + : value_(value), + data_(data), + data_size_(data_size) {} + + void Execute() override { + TestBinary(value_, data_, data_size_); + } + + private: + CefRefPtr value_; + char* data_; + size_t data_size_; + + IMPLEMENT_REFCOUNTING(BinaryTask); +}; + + +// DICTIONARY TEST HELPERS + +// Test dictionary null value. +void TestDictionaryNull(CefRefPtr value) { + EXPECT_FALSE(value->HasKey(kNullKey)); + EXPECT_TRUE(value->SetNull(kNullKey)); + EXPECT_TRUE(value->HasKey(kNullKey)); + EXPECT_EQ(VTYPE_NULL, value->GetType(kNullKey)); +} + +// Test dictionary bool value. +void TestDictionaryBool(CefRefPtr value) { + EXPECT_FALSE(value->HasKey(kBoolKey)); + EXPECT_TRUE(value->SetBool(kBoolKey, kBoolValue)); + EXPECT_TRUE(value->HasKey(kBoolKey)); + EXPECT_EQ(VTYPE_BOOL, value->GetType(kBoolKey)); + EXPECT_EQ(kBoolValue, value->GetBool(kBoolKey)); +} + +// Test dictionary int value. +void TestDictionaryInt(CefRefPtr value) { + EXPECT_FALSE(value->HasKey(kIntKey)); + EXPECT_TRUE(value->SetInt(kIntKey, kIntValue)); + EXPECT_TRUE(value->HasKey(kIntKey)); + EXPECT_EQ(VTYPE_INT, value->GetType(kIntKey)); + EXPECT_EQ(kIntValue, value->GetInt(kIntKey)); +} + +// Test dictionary double value. +void TestDictionaryDouble(CefRefPtr value) { + EXPECT_FALSE(value->HasKey(kDoubleKey)); + EXPECT_TRUE(value->SetDouble(kDoubleKey, kDoubleValue)); + EXPECT_TRUE(value->HasKey(kDoubleKey)); + EXPECT_EQ(VTYPE_DOUBLE, value->GetType(kDoubleKey)); + EXPECT_EQ(kDoubleValue, value->GetDouble(kDoubleKey)); +} + +// Test dictionary string value. +void TestDictionaryString(CefRefPtr value) { + EXPECT_FALSE(value->HasKey(kStringKey)); + EXPECT_TRUE(value->SetString(kStringKey, kStringValue)); + EXPECT_TRUE(value->HasKey(kStringKey)); + EXPECT_EQ(VTYPE_STRING, value->GetType(kStringKey)); + EXPECT_EQ(kStringValue, value->GetString(kStringKey).ToString()); +} + +// Test dictionary binary value. +void TestDictionaryBinary(CefRefPtr value, + char* binary_data, size_t binary_data_size, + CefRefPtr& binary_value) { + binary_value = CefBinaryValue::Create(binary_data, binary_data_size); + EXPECT_TRUE(binary_value.get()); + EXPECT_TRUE(binary_value->IsValid()); + EXPECT_FALSE(binary_value->IsOwned()); + EXPECT_FALSE(value->HasKey(kBinaryKey)); + EXPECT_TRUE(value->SetBinary(kBinaryKey, binary_value)); + EXPECT_FALSE(binary_value->IsValid()); // Value should be detached + EXPECT_TRUE(value->HasKey(kBinaryKey)); + EXPECT_EQ(VTYPE_BINARY, value->GetType(kBinaryKey)); + binary_value = value->GetBinary(kBinaryKey); + EXPECT_TRUE(binary_value.get()); + EXPECT_TRUE(binary_value->IsValid()); + EXPECT_TRUE(binary_value->IsOwned()); + TestBinary(binary_value, binary_data, binary_data_size); +} + +// Test dictionary dictionary value. +void TestDictionaryDictionary(CefRefPtr value, + CefRefPtr& dictionary_value) { + dictionary_value = CefDictionaryValue::Create(); + EXPECT_TRUE(dictionary_value.get()); + EXPECT_TRUE(dictionary_value->IsValid()); + EXPECT_FALSE(dictionary_value->IsOwned()); + EXPECT_FALSE(dictionary_value->IsReadOnly()); + EXPECT_TRUE(dictionary_value->SetInt(kIntKey, kIntValue)); + EXPECT_EQ((size_t)1, dictionary_value->GetSize()); + EXPECT_FALSE(value->HasKey(kDictionaryKey)); + EXPECT_TRUE(value->SetDictionary(kDictionaryKey, dictionary_value)); + EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached + EXPECT_TRUE(value->HasKey(kDictionaryKey)); + EXPECT_EQ(VTYPE_DICTIONARY, value->GetType(kDictionaryKey)); + dictionary_value = value->GetDictionary(kDictionaryKey); + EXPECT_TRUE(dictionary_value.get()); + EXPECT_TRUE(dictionary_value->IsValid()); + EXPECT_TRUE(dictionary_value->IsOwned()); + EXPECT_FALSE(dictionary_value->IsReadOnly()); + EXPECT_EQ((size_t)1, dictionary_value->GetSize()); + EXPECT_EQ(kIntValue, dictionary_value->GetInt(kIntKey)); +} + +// Test dictionary list value. +void TestDictionaryList(CefRefPtr value, + CefRefPtr& list_value) { + list_value = CefListValue::Create(); + EXPECT_TRUE(list_value.get()); + EXPECT_TRUE(list_value->IsValid()); + EXPECT_FALSE(list_value->IsOwned()); + EXPECT_FALSE(list_value->IsReadOnly()); + EXPECT_TRUE(list_value->SetInt(0, kIntValue)); + EXPECT_EQ((size_t)1, list_value->GetSize()); + EXPECT_FALSE(value->HasKey(kListKey)); + EXPECT_TRUE(value->SetList(kListKey, list_value)); + EXPECT_FALSE(list_value->IsValid()); // Value should be detached + EXPECT_TRUE(value->HasKey(kListKey)); + EXPECT_EQ(VTYPE_LIST, value->GetType(kListKey)); + list_value = value->GetList(kListKey); + EXPECT_TRUE(list_value.get()); + EXPECT_TRUE(list_value->IsValid()); + EXPECT_TRUE(list_value->IsOwned()); + EXPECT_FALSE(list_value->IsReadOnly()); + EXPECT_EQ((size_t)1, list_value->GetSize()); + EXPECT_EQ(kIntValue, list_value->GetInt(0)); +} + +// Test dictionary value. +void TestDictionary(CefRefPtr value, + char* binary_data, size_t binary_data_size) { + CefRefPtr binary_value; + CefRefPtr dictionary_value; + CefRefPtr list_value; + + // Test the size. + EXPECT_EQ((size_t)0, value->GetSize()); + + TestDictionaryNull(value); + TestDictionaryBool(value); + TestDictionaryInt(value); + TestDictionaryDouble(value); + TestDictionaryString(value); + TestDictionaryBinary(value, binary_data, binary_data_size, binary_value); + TestDictionaryDictionary(value, dictionary_value); + TestDictionaryList(value, list_value); + + // Test the size. + EXPECT_EQ((size_t)8, value->GetSize()); + + // Test copy. + CefRefPtr copy = value->Copy(false); + TestDictionaryEqual(value, copy); + + // Test removal. + EXPECT_TRUE(value->Remove(kNullKey)); + EXPECT_FALSE(value->HasKey(kNullKey)); + + EXPECT_TRUE(value->Remove(kBoolKey)); + EXPECT_FALSE(value->HasKey(kBoolKey)); + + EXPECT_TRUE(value->Remove(kIntKey)); + EXPECT_FALSE(value->HasKey(kIntKey)); + + EXPECT_TRUE(value->Remove(kDoubleKey)); + EXPECT_FALSE(value->HasKey(kDoubleKey)); + + EXPECT_TRUE(value->Remove(kStringKey)); + EXPECT_FALSE(value->HasKey(kStringKey)); + + EXPECT_TRUE(value->Remove(kBinaryKey)); + EXPECT_FALSE(value->HasKey(kBinaryKey)); + EXPECT_FALSE(binary_value->IsValid()); // Value should be detached + + EXPECT_TRUE(value->Remove(kDictionaryKey)); + EXPECT_FALSE(value->HasKey(kDictionaryKey)); + EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached + + EXPECT_TRUE(value->Remove(kListKey)); + EXPECT_FALSE(value->HasKey(kListKey)); + EXPECT_FALSE(list_value->IsValid()); // Value should be detached + + // Test the size. + EXPECT_EQ((size_t)0, value->GetSize()); + + // Re-add some values. + TestDictionaryNull(value); + TestDictionaryBool(value); + TestDictionaryDictionary(value, dictionary_value); + + // Test the size. + EXPECT_EQ((size_t)3, value->GetSize()); + + // Clear the values. + EXPECT_TRUE(value->Clear()); + EXPECT_EQ((size_t)0, value->GetSize()); + EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached +} + +// Used to test access of dictionary data on a different thread. +class DictionaryTask : public CefTask { + public: + DictionaryTask(CefRefPtr value, char* binary_data, + size_t binary_data_size) + : value_(value), + binary_data_(binary_data), + binary_data_size_(binary_data_size) {} + + void Execute() override { + TestDictionary(value_, binary_data_, binary_data_size_); + } + + private: + CefRefPtr value_; + char* binary_data_; + size_t binary_data_size_; + + IMPLEMENT_REFCOUNTING(DictionaryTask); +}; + + +// LIST TEST HELPERS + +// Test list null value. +void TestListNull(CefRefPtr value, int index) { + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetNull(index)); + EXPECT_EQ(VTYPE_NULL, value->GetType(index)); +} + +// Test list bool value. +void TestListBool(CefRefPtr value, int index) { + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetBool(index, kBoolValue)); + EXPECT_EQ(VTYPE_BOOL, value->GetType(index)); + EXPECT_EQ(kBoolValue, value->GetBool(index)); +} + +// Test list int value. +void TestListInt(CefRefPtr value, int index) { + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetInt(index, kIntValue)); + EXPECT_EQ(VTYPE_INT, value->GetType(index)); + EXPECT_EQ(kIntValue, value->GetInt(index)); +} + +// Test list double value. +void TestListDouble(CefRefPtr value, int index) { + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetDouble(index, kDoubleValue)); + EXPECT_EQ(VTYPE_DOUBLE, value->GetType(index)); + EXPECT_EQ(kDoubleValue, value->GetDouble(index)); +} + +// Test list string value. +void TestListString(CefRefPtr value, int index) { + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetString(index, kStringValue)); + EXPECT_EQ(VTYPE_STRING, value->GetType(index)); + EXPECT_EQ(kStringValue, value->GetString(index).ToString()); +} + +// Test list binary value. +void TestListBinary(CefRefPtr value, int index, + char* binary_data, size_t binary_data_size, + CefRefPtr& binary_value) { + binary_value = CefBinaryValue::Create(binary_data, binary_data_size); + EXPECT_TRUE(binary_value.get()); + EXPECT_TRUE(binary_value->IsValid()); + EXPECT_FALSE(binary_value->IsOwned()); + + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetBinary(index, binary_value)); + EXPECT_FALSE(binary_value->IsValid()); // Value should be detached + EXPECT_EQ(VTYPE_BINARY, value->GetType(index)); + binary_value = value->GetBinary(index); + EXPECT_TRUE(binary_value.get()); + EXPECT_TRUE(binary_value->IsValid()); + EXPECT_TRUE(binary_value->IsOwned()); + TestBinary(binary_value, binary_data, binary_data_size); +} + +// Test list dictionary value. +void TestListDictionary(CefRefPtr value, int index, + CefRefPtr& dictionary_value) { + dictionary_value = CefDictionaryValue::Create(); + EXPECT_TRUE(dictionary_value.get()); + EXPECT_TRUE(dictionary_value->IsValid()); + EXPECT_FALSE(dictionary_value->IsOwned()); + EXPECT_FALSE(dictionary_value->IsReadOnly()); + EXPECT_TRUE(dictionary_value->SetInt(kIntKey, kIntValue)); + EXPECT_EQ((size_t)1, dictionary_value->GetSize()); + + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetDictionary(index, dictionary_value)); + EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached + EXPECT_EQ(VTYPE_DICTIONARY, value->GetType(index)); + dictionary_value = value->GetDictionary(index); + EXPECT_TRUE(dictionary_value.get()); + EXPECT_TRUE(dictionary_value->IsValid()); + EXPECT_TRUE(dictionary_value->IsOwned()); + EXPECT_FALSE(dictionary_value->IsReadOnly()); + EXPECT_EQ((size_t)1, dictionary_value->GetSize()); + EXPECT_EQ(kIntValue, dictionary_value->GetInt(kIntKey)); +} + +// Test list list value. +void TestListList(CefRefPtr value, int index, + CefRefPtr& list_value) { + list_value = CefListValue::Create(); + EXPECT_TRUE(list_value.get()); + EXPECT_TRUE(list_value->IsValid()); + EXPECT_FALSE(list_value->IsOwned()); + EXPECT_FALSE(list_value->IsReadOnly()); + EXPECT_TRUE(list_value->SetInt(0, kIntValue)); + EXPECT_EQ((size_t)1, list_value->GetSize()); + + CefValueType type = value->GetType(index); + EXPECT_TRUE(type == VTYPE_INVALID || type == VTYPE_NULL); + + EXPECT_TRUE(value->SetList(index, list_value)); + EXPECT_FALSE(list_value->IsValid()); // Value should be detached + EXPECT_EQ(VTYPE_LIST, value->GetType(index)); + list_value = value->GetList(index); + EXPECT_TRUE(list_value.get()); + EXPECT_TRUE(list_value->IsValid()); + EXPECT_TRUE(list_value->IsOwned()); + EXPECT_FALSE(list_value->IsReadOnly()); + EXPECT_EQ((size_t)1, list_value->GetSize()); + EXPECT_EQ(kIntValue, list_value->GetInt(0)); +} + +// Test list value. +void TestList(CefRefPtr value, + char* binary_data, size_t binary_data_size) { + CefRefPtr binary_value; + CefRefPtr dictionary_value; + CefRefPtr list_value; + + // Test the size. + EXPECT_EQ((size_t)0, value->GetSize()); + + // Set the size. + EXPECT_TRUE(value->SetSize(8)); + EXPECT_EQ((size_t)8, value->GetSize()); + + EXPECT_EQ(VTYPE_NULL, value->GetType(kNullIndex)); + TestListNull(value, kNullIndex); + EXPECT_EQ(VTYPE_NULL, value->GetType(kBoolIndex)); + TestListBool(value, kBoolIndex); + EXPECT_EQ(VTYPE_NULL, value->GetType(kIntIndex)); + TestListInt(value, kIntIndex); + EXPECT_EQ(VTYPE_NULL, value->GetType(kDoubleIndex)); + TestListDouble(value, kDoubleIndex); + EXPECT_EQ(VTYPE_NULL, value->GetType(kStringIndex)); + TestListString(value, kStringIndex); + EXPECT_EQ(VTYPE_NULL, value->GetType(kBinaryIndex)); + TestListBinary(value, kBinaryIndex, binary_data, binary_data_size, + binary_value); + EXPECT_EQ(VTYPE_NULL, value->GetType(kDictionaryIndex)); + TestListDictionary(value, kDictionaryIndex, dictionary_value); + EXPECT_EQ(VTYPE_NULL, value->GetType(kListIndex)); + TestListList(value, kListIndex, list_value); + + // Test the size. + EXPECT_EQ((size_t)8, value->GetSize()); + + // Test copy. + CefRefPtr copy = value->Copy(); + TestListEqual(value, copy); + + // Test removal (in reverse order so indexes stay valid). + EXPECT_TRUE(value->Remove(kListIndex)); + EXPECT_EQ((size_t)7, value->GetSize()); + EXPECT_FALSE(list_value->IsValid()); // Value should be detached + + EXPECT_TRUE(value->Remove(kDictionaryIndex)); + EXPECT_EQ((size_t)6, value->GetSize()); + EXPECT_FALSE(dictionary_value->IsValid()); // Value should be detached + + EXPECT_TRUE(value->Remove(kBinaryIndex)); + EXPECT_EQ((size_t)5, value->GetSize()); + EXPECT_FALSE(binary_value->IsValid()); // Value should be detached + + EXPECT_TRUE(value->Remove(kStringIndex)); + EXPECT_EQ((size_t)4, value->GetSize()); + + EXPECT_TRUE(value->Remove(kDoubleIndex)); + EXPECT_EQ((size_t)3, value->GetSize()); + + EXPECT_TRUE(value->Remove(kIntIndex)); + EXPECT_EQ((size_t)2, value->GetSize()); + + EXPECT_TRUE(value->Remove(kBoolIndex)); + EXPECT_EQ((size_t)1, value->GetSize()); + + EXPECT_TRUE(value->Remove(kNullIndex)); + EXPECT_EQ((size_t)0, value->GetSize()); + + // Re-add some values. + EXPECT_EQ(VTYPE_INVALID, value->GetType(0)); + TestListNull(value, 0); + EXPECT_EQ(VTYPE_INVALID, value->GetType(1)); + TestListBool(value, 1); + EXPECT_EQ(VTYPE_INVALID, value->GetType(2)); + TestListList(value, 2, list_value); + + // Test the size. + EXPECT_EQ((size_t)3, value->GetSize()); + + // Clear the values. + EXPECT_TRUE(value->Clear()); + EXPECT_EQ((size_t)0, value->GetSize()); + EXPECT_FALSE(list_value->IsValid()); // Value should be detached + + // Add some values in random order. + EXPECT_EQ(VTYPE_INVALID, value->GetType(2)); + TestListInt(value, 2); + EXPECT_EQ(VTYPE_NULL, value->GetType(0)); + TestListBool(value, 0); + EXPECT_EQ(VTYPE_NULL, value->GetType(1)); + TestListList(value, 1, list_value); + + EXPECT_EQ(VTYPE_BOOL, value->GetType(0)); + EXPECT_EQ(VTYPE_LIST, value->GetType(1)); + EXPECT_EQ(VTYPE_INT, value->GetType(2)); + + // Test the size. + EXPECT_EQ((size_t)3, value->GetSize()); + + // Clear some values. + EXPECT_TRUE(value->SetSize(1)); + EXPECT_EQ((size_t)1, value->GetSize()); + EXPECT_FALSE(list_value->IsValid()); // Value should be detached + + EXPECT_EQ(VTYPE_BOOL, value->GetType(0)); + EXPECT_EQ(VTYPE_INVALID, value->GetType(1)); + EXPECT_EQ(VTYPE_INVALID, value->GetType(2)); + + // Clear all values. + EXPECT_TRUE(value->Clear()); + EXPECT_EQ((size_t)0, value->GetSize()); +} + +// Used to test access of list data on a different thread. +class ListTask : public CefTask { + public: + ListTask(CefRefPtr value, char* binary_data, + size_t binary_data_size) + : value_(value), + binary_data_(binary_data), + binary_data_size_(binary_data_size) {} + + void Execute() override { + TestList(value_, binary_data_, binary_data_size_); + } + + private: + CefRefPtr value_; + char* binary_data_; + size_t binary_data_size_; + + IMPLEMENT_REFCOUNTING(ListTask); +}; + +} // namespace + + +// Test binary value access. +TEST(ValuesTest, BinaryAccess) { + char data[] = "This is my test data"; + + CefRefPtr value = + CefBinaryValue::Create(data, sizeof(data)-1); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + + // Test on this thread. + TestBinary(value, data, sizeof(data)-1); +} + +// Test binary value access on a different thread. +TEST(ValuesTest, BinaryAccessOtherThread) { + char data[] = "This is my test data"; + + CefRefPtr value = + CefBinaryValue::Create(data, sizeof(data)-1); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + + // Test on a different thread. + CefPostTask(TID_UI, new BinaryTask(value, data, sizeof(data)-1)); + WaitForUIThread(); +} + +// Test dictionary value access. +TEST(ValuesTest, DictionaryAccess) { + CefRefPtr value = CefDictionaryValue::Create(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + EXPECT_FALSE(value->IsReadOnly()); + + char binary_data[] = "This is my test data"; + + // Test on this thread. + TestDictionary(value, binary_data, sizeof(binary_data)-1); +} + +// Test dictionary value access on a different thread. +TEST(ValuesTest, DictionaryAccessOtherThread) { + CefRefPtr value = CefDictionaryValue::Create(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + EXPECT_FALSE(value->IsReadOnly()); + + char binary_data[] = "This is my test data"; + + // Test on a different thread. + CefPostTask(TID_UI, + new DictionaryTask(value, binary_data, sizeof(binary_data)-1)); + WaitForUIThread(); +} + +// Test dictionary value nested detachment +TEST(ValuesTest, DictionaryDetachment) { + CefRefPtr value = CefDictionaryValue::Create(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + EXPECT_FALSE(value->IsReadOnly()); + + CefRefPtr dictionary_value = CefDictionaryValue::Create(); + CefRefPtr dictionary_value2 = + CefDictionaryValue::Create(); + CefRefPtr dictionary_value3 = + CefDictionaryValue::Create(); + + dictionary_value2->SetDictionary(kDictionaryKey, dictionary_value3); + EXPECT_FALSE(dictionary_value3->IsValid()); + dictionary_value->SetDictionary(kDictionaryKey, dictionary_value2); + EXPECT_FALSE(dictionary_value2->IsValid()); + value->SetDictionary(kDictionaryKey, dictionary_value); + EXPECT_FALSE(dictionary_value->IsValid()); + + dictionary_value = value->GetDictionary(kDictionaryKey); + EXPECT_TRUE(dictionary_value.get()); + EXPECT_TRUE(dictionary_value->IsValid()); + + dictionary_value2 = dictionary_value->GetDictionary(kDictionaryKey); + EXPECT_TRUE(dictionary_value2.get()); + EXPECT_TRUE(dictionary_value2->IsValid()); + + dictionary_value3 = dictionary_value2->GetDictionary(kDictionaryKey); + EXPECT_TRUE(dictionary_value3.get()); + EXPECT_TRUE(dictionary_value3->IsValid()); + + EXPECT_TRUE(value->Remove(kDictionaryKey)); + EXPECT_FALSE(dictionary_value->IsValid()); + EXPECT_FALSE(dictionary_value2->IsValid()); + EXPECT_FALSE(dictionary_value3->IsValid()); +} + +// Test list value access. +TEST(ValuesTest, ListAccess) { + CefRefPtr value = CefListValue::Create(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + EXPECT_FALSE(value->IsReadOnly()); + + char binary_data[] = "This is my test data"; + + // Test on this thread. + TestList(value, binary_data, sizeof(binary_data)-1); +} + +// Test list value access on a different thread. +TEST(ValuesTest, ListAccessOtherThread) { + CefRefPtr value = CefListValue::Create(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + EXPECT_FALSE(value->IsReadOnly()); + + char binary_data[] = "This is my test data"; + + // Test on a different thread. + CefPostTask(TID_UI, new ListTask(value, binary_data, sizeof(binary_data)-1)); + WaitForUIThread(); +} + +// Test list value nested detachment +TEST(ValuesTest, ListDetachment) { + CefRefPtr value = CefListValue::Create(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsValid()); + EXPECT_FALSE(value->IsOwned()); + EXPECT_FALSE(value->IsReadOnly()); + + CefRefPtr list_value = CefListValue::Create(); + CefRefPtr list_value2 = CefListValue::Create(); + CefRefPtr list_value3 = CefListValue::Create(); + + list_value2->SetList(0, list_value3); + EXPECT_FALSE(list_value3->IsValid()); + list_value->SetList(0, list_value2); + EXPECT_FALSE(list_value2->IsValid()); + value->SetList(0, list_value); + EXPECT_FALSE(list_value->IsValid()); + + list_value = value->GetList(0); + EXPECT_TRUE(list_value.get()); + EXPECT_TRUE(list_value->IsValid()); + + list_value2 = list_value->GetList(0); + EXPECT_TRUE(list_value2.get()); + EXPECT_TRUE(list_value2->IsValid()); + + list_value3 = list_value2->GetList(0); + EXPECT_TRUE(list_value3.get()); + EXPECT_TRUE(list_value3->IsValid()); + + EXPECT_TRUE(value->Remove(0)); + EXPECT_FALSE(list_value->IsValid()); + EXPECT_FALSE(list_value2->IsValid()); + EXPECT_FALSE(list_value3->IsValid()); +} diff --git a/tests/unittests/version_unittest.cc b/tests/unittests/version_unittest.cc new file mode 100644 index 000000000..b4d5f3016 --- /dev/null +++ b/tests/unittests/version_unittest.cc @@ -0,0 +1,27 @@ +// Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_version.h" +#include "testing/gtest/include/gtest/gtest.h" + +TEST(VersionTest, BuildRevision) { + EXPECT_EQ(CEF_REVISION, cef_build_revision()); +} + +TEST(VersionTest, VersionInfo) { + EXPECT_EQ(CEF_VERSION_MAJOR, cef_version_info(0)); + EXPECT_EQ(CEF_REVISION, cef_version_info(1)); + EXPECT_EQ(CHROME_VERSION_MAJOR, cef_version_info(2)); + EXPECT_EQ(CHROME_VERSION_MINOR, cef_version_info(3)); + EXPECT_EQ(CHROME_VERSION_BUILD, cef_version_info(4)); + EXPECT_EQ(CHROME_VERSION_PATCH, cef_version_info(5)); +} + +TEST(VersionTest, ApiHash) { + EXPECT_STREQ(CEF_API_HASH_PLATFORM, cef_api_hash(0)); + EXPECT_STREQ(CEF_API_HASH_UNIVERSAL, cef_api_hash(1)); +} diff --git a/tests/unittests/xml_reader_unittest.cc b/tests/unittests/xml_reader_unittest.cc new file mode 100644 index 000000000..aa7f8b730 --- /dev/null +++ b/tests/unittests/xml_reader_unittest.cc @@ -0,0 +1,645 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_stream.h" +#include "include/cef_xml_reader.h" +#include "include/wrapper/cef_xml_object.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +char g_test_xml[] = + "\n" + "\n" + "\n" + " \n" + "]>\n" + "\n" + " value A\n" + " \n" + " \n" + " value B1\n" + " data]]>\n" + " &EB;\n" + " this is mixed content &EA;\n" + " \n" + " " + "\n" + "\n"; + +} // namespace + +// Test XML reading +TEST(XmlReaderTest, Read) { + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(g_test_xml, sizeof(g_test_xml) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + // Create the XML reader. + CefRefPtr reader( + CefXmlReader::Create(stream, XML_ENCODING_NONE, + "http://www.example.org/example.xml")); + ASSERT_TRUE(reader.get() != NULL); + + // Move to the processing instruction node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 0); + ASSERT_EQ(reader->GetType(), XML_NODE_PROCESSING_INSTRUCTION); + ASSERT_EQ(reader->GetLocalName(), "my_instruction"); + ASSERT_EQ(reader->GetQualifiedName(), "my_instruction"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "my_value"); + + // Move to the DOCTYPE node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 0); + ASSERT_EQ(reader->GetType(), XML_NODE_DOCUMENT_TYPE); + ASSERT_EQ(reader->GetLocalName(), "my_document"); + ASSERT_EQ(reader->GetQualifiedName(), "my_document"); + ASSERT_FALSE(reader->HasValue()); + + // Move to ns:obj element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 0); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "obj"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:obj"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->HasAttributes()); + ASSERT_EQ(reader->GetAttributeCount(), (size_t)1); + ASSERT_EQ(reader->GetAttribute(0), "http://www.example.org/ns"); + ASSERT_EQ(reader->GetAttribute("xmlns:ns"), "http://www.example.org/ns"); + ASSERT_EQ(reader->GetAttribute("ns", "http://www.w3.org/2000/xmlns/"), + "http://www.example.org/ns"); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objA element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objA"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objA"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the ns:objA value node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_TEXT); + ASSERT_EQ(reader->GetLocalName(), "#text"); + ASSERT_EQ(reader->GetQualifiedName(), "#text"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "value A"); + + // Move to the ns:objA element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objA"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objA"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the comment node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_COMMENT); + ASSERT_EQ(reader->GetLocalName(), "#comment"); + ASSERT_EQ(reader->GetQualifiedName(), "#comment"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), " my comment "); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objB element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objB"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objB_1 element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objB_1"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_1"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the ns:objB_1 value node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_TEXT); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "value B1"); + + // Move to the ns:objB_1 element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objB_1"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_1"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objB_2 element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objB_2"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_2"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the ns:objB_2 value node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_CDATA); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "some
data"); + + // Move to the ns:objB_2 element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objB_2"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_2"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objB_3 element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objB_3"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_3"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the EB entity reference node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_ENTITY_REFERENCE); + ASSERT_EQ(reader->GetLocalName(), "EB"); + ASSERT_EQ(reader->GetQualifiedName(), "EB"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "EB Value"); + + // Move to the ns:objB_3 element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objB_3"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_3"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objB_4 element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objB_4"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_4"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + ASSERT_EQ(reader->GetInnerXml(), "this is mixed content &EA;"); + ASSERT_EQ(reader->GetOuterXml(), + "" + "this is mixed content &EA;"); + + // Move to the element node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "b"); + ASSERT_EQ(reader->GetQualifiedName(), "b"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the text node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 4); + ASSERT_EQ(reader->GetType(), XML_NODE_TEXT); + ASSERT_EQ(reader->GetLocalName(), "#text"); + ASSERT_EQ(reader->GetQualifiedName(), "#text"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "this is"); + + // Move to the element node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "b"); + ASSERT_EQ(reader->GetQualifiedName(), "b"); + + // Move to the text node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_TEXT); + ASSERT_EQ(reader->GetLocalName(), "#text"); + ASSERT_EQ(reader->GetQualifiedName(), "#text"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), " mixed content "); + + // Move to the EA entity reference node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 3); + ASSERT_EQ(reader->GetType(), XML_NODE_ENTITY_REFERENCE); + ASSERT_EQ(reader->GetLocalName(), "EA"); + ASSERT_EQ(reader->GetQualifiedName(), "EA"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_EQ(reader->GetValue(), "EA Value"); + + // Move to the ns:objB_4 element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objB_4"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB_4"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objB element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objB"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objB"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to the ns:objC element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objC"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objC"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->IsEmptyElement()); + ASSERT_TRUE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + ASSERT_EQ(reader->GetAttributeCount(), (size_t)2); + ASSERT_EQ(reader->GetAttribute(0), "value C1"); + ASSERT_EQ(reader->GetAttribute("ns:attr1"), "value C1"); + ASSERT_EQ(reader->GetAttribute("attr1", "http://www.example.org/ns"), + "value C1"); + ASSERT_EQ(reader->GetAttribute(1), "value C2"); + ASSERT_EQ(reader->GetAttribute("ns:attr2"), "value C2"); + ASSERT_EQ(reader->GetAttribute("attr2", "http://www.example.org/ns"), + "value C2"); + + // Move to the ns:attr1 attribute. + ASSERT_TRUE(reader->MoveToFirstAttribute()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE); + ASSERT_EQ(reader->GetLocalName(), "attr1"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_EQ(reader->GetValue(), "value C1"); + + // Move to the ns:attr2 attribute. + ASSERT_TRUE(reader->MoveToNextAttribute()); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE); + ASSERT_EQ(reader->GetLocalName(), "attr2"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:attr2"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_EQ(reader->GetValue(), "value C2"); + + // No more attributes. + ASSERT_FALSE(reader->MoveToNextAttribute()); + + // Return to the ns:objC element start node. + ASSERT_TRUE(reader->MoveToCarryingElement()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objC"); + + // Move to the ns:attr1 attribute. + ASSERT_TRUE(reader->MoveToAttribute(0)); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE); + ASSERT_EQ(reader->GetLocalName(), "attr1"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_EQ(reader->GetValue(), "value C1"); + + // Return to the ns:objC element start node. + ASSERT_TRUE(reader->MoveToCarryingElement()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objC"); + + // Move to the ns:attr2 attribute. + ASSERT_TRUE(reader->MoveToAttribute("ns:attr2")); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE); + ASSERT_EQ(reader->GetLocalName(), "attr2"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:attr2"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_EQ(reader->GetValue(), "value C2"); + + // Move to the ns:attr1 attribute without returning to the ns:objC element. + ASSERT_TRUE(reader->MoveToAttribute("attr1", "http://www.example.org/ns")); + ASSERT_EQ(reader->GetDepth(), 2); + ASSERT_EQ(reader->GetType(), XML_NODE_ATTRIBUTE); + ASSERT_EQ(reader->GetLocalName(), "attr1"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:attr1"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_TRUE(reader->HasValue()); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_EQ(reader->GetValue(), "value C1"); + + // Move to the ns:objD element start node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_START); + ASSERT_EQ(reader->GetLocalName(), "objD"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objD"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the ns:objD element end node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 1); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "objD"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:objD"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_FALSE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + + // Move to the whitespace node without returning to the ns:objC element. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetType(), XML_NODE_WHITESPACE); + + // Move to ns:obj element ending node. + ASSERT_TRUE(reader->MoveToNextNode()); + ASSERT_EQ(reader->GetDepth(), 0); + ASSERT_EQ(reader->GetType(), XML_NODE_ELEMENT_END); + ASSERT_EQ(reader->GetLocalName(), "obj"); + ASSERT_EQ(reader->GetPrefix(), "ns"); + ASSERT_EQ(reader->GetQualifiedName(), "ns:obj"); + ASSERT_EQ(reader->GetNamespaceURI(), "http://www.example.org/ns"); + ASSERT_FALSE(reader->IsEmptyElement()); + ASSERT_TRUE(reader->HasAttributes()); + ASSERT_FALSE(reader->HasValue()); + // Strangely, the end node will report if the starting node has attributes + // but will not provide access to them. + ASSERT_TRUE(reader->HasAttributes()); + ASSERT_EQ(reader->GetAttributeCount(), (size_t)0); + + // And we're done. + ASSERT_FALSE(reader->MoveToNextNode()); + + ASSERT_TRUE(reader->Close()); +} + +// Test XML read error handling. +TEST(XmlReaderTest, ReadError) { + char test_str[] = + "\n" + "\n"; + + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(test_str, sizeof(test_str) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + // Create the XML reader. + CefRefPtr reader( + CefXmlReader::Create(stream, XML_ENCODING_NONE, + "http://www.example.org/example.xml")); + ASSERT_TRUE(reader.get() != NULL); + + // Move to the processing instruction node and generate parser error. + ASSERT_FALSE(reader->MoveToNextNode()); + ASSERT_TRUE(reader->HasError()); +} + +// Test XmlObject load behavior. +TEST(XmlReaderTest, ObjectLoad) { + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(g_test_xml, sizeof(g_test_xml) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + // Create the XML reader. + CefRefPtr object(new CefXmlObject("object")); + ASSERT_TRUE(object->Load(stream, XML_ENCODING_NONE, + "http://www.example.org/example.xml", NULL)); + + ASSERT_FALSE(object->HasAttributes()); + ASSERT_TRUE(object->HasChildren()); + ASSERT_EQ(object->GetChildCount(), (size_t)1); + + CefRefPtr obj(object->FindChild("ns:obj")); + ASSERT_TRUE(obj.get()); + ASSERT_TRUE(obj->HasChildren()); + ASSERT_EQ(obj->GetChildCount(), (size_t)4); + + CefRefPtr obj_child(obj->FindChild("ns:objC")); + ASSERT_TRUE(obj_child.get()); + ASSERT_EQ(obj_child->GetName(), "ns:objC"); + ASSERT_FALSE(obj_child->HasChildren()); + ASSERT_FALSE(obj_child->HasValue()); + ASSERT_TRUE(obj_child->HasAttributes()); + + CefXmlObject::ObjectVector obj_children; + ASSERT_EQ(obj->GetChildren(obj_children), (size_t)4); + ASSERT_EQ(obj_children.size(), (size_t)4); + + CefXmlObject::ObjectVector::const_iterator it = obj_children.begin(); + for (int ct = 0; it != obj_children.end(); ++it, ++ct) { + obj_child = *it; + ASSERT_TRUE(obj_child.get()); + if (ct == 0) { + // ns:objA + ASSERT_EQ(obj_child->GetName(), "ns:objA"); + ASSERT_FALSE(obj_child->HasChildren()); + ASSERT_TRUE(obj_child->HasValue()); + ASSERT_FALSE(obj_child->HasAttributes()); + ASSERT_EQ(obj_child->GetValue(), "value A"); + } else if (ct == 1) { + // ns:objB + ASSERT_EQ(obj_child->GetName(), "ns:objB"); + ASSERT_TRUE(obj_child->HasChildren()); + ASSERT_FALSE(obj_child->HasValue()); + ASSERT_FALSE(obj_child->HasAttributes()); + ASSERT_EQ(obj_child->GetChildCount(), (size_t)4); + obj_child = obj_child->FindChild("ns:objB_4"); + ASSERT_TRUE(obj_child.get()); + ASSERT_TRUE(obj_child->HasValue()); + ASSERT_EQ(obj_child->GetValue(), + "this is mixed content EA Value"); + } else if (ct == 2) { + // ns:objC + ASSERT_EQ(obj_child->GetName(), "ns:objC"); + ASSERT_FALSE(obj_child->HasChildren()); + ASSERT_FALSE(obj_child->HasValue()); + ASSERT_TRUE(obj_child->HasAttributes()); + + CefXmlObject::AttributeMap attribs; + ASSERT_EQ(obj_child->GetAttributes(attribs), (size_t)2); + ASSERT_EQ(attribs.size(), (size_t)2); + ASSERT_EQ(attribs["ns:attr1"], "value C1"); + ASSERT_EQ(attribs["ns:attr2"], "value C2"); + + ASSERT_EQ(obj_child->GetAttributeCount(), (size_t)2); + ASSERT_TRUE(obj_child->HasAttribute("ns:attr1")); + ASSERT_EQ(obj_child->GetAttributeValue("ns:attr1"), "value C1"); + ASSERT_TRUE(obj_child->HasAttribute("ns:attr2")); + ASSERT_EQ(obj_child->GetAttributeValue("ns:attr2"), "value C2"); + } else if (ct == 3) { + // ns:objD + ASSERT_EQ(obj_child->GetName(), "ns:objD"); + ASSERT_FALSE(obj_child->HasChildren()); + ASSERT_FALSE(obj_child->HasValue()); + ASSERT_FALSE(obj_child->HasAttributes()); + } + } +} + +// Test XmlObject load error handling behavior. +TEST(XmlReaderTest, ObjectLoadError) { + // Test start/end tag mismatch error. + { + char error_xml[] = "\n\n\n
"; + + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(error_xml, sizeof(error_xml) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + CefString error_str; + + // Create the XML reader. + CefRefPtr object(new CefXmlObject("object")); + ASSERT_FALSE(object->Load(stream, XML_ENCODING_NONE, + "http://www.example.org/example.xml", &error_str)); + ASSERT_EQ(error_str, + "Opening and ending tag mismatch: foo line 2 and obj, line 3"); + } + + // Test value following child error. + { + char error_xml[] = "\n\ndisallowed value\n"; + + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(error_xml, sizeof(error_xml) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + CefString error_str; + + // Create the XML reader. + CefRefPtr object(new CefXmlObject("object")); + ASSERT_FALSE(object->Load(stream, XML_ENCODING_NONE, + "http://www.example.org/example.xml", &error_str)); + ASSERT_EQ(error_str, + "Value following child element, line 4"); + } +} diff --git a/tests/unittests/zip_reader_unittest.cc b/tests/unittests/zip_reader_unittest.cc new file mode 100644 index 000000000..4ae10b8cc --- /dev/null +++ b/tests/unittests/zip_reader_unittest.cc @@ -0,0 +1,256 @@ +// Copyright (c) 2010 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. + +// Include this first to avoid type conflicts with CEF headers. +#include "tests/unittests/chromium_includes.h" + +#include "include/cef_stream.h" +#include "include/cef_zip_reader.h" +#include "include/wrapper/cef_zip_archive.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + + unsigned char g_test_zip[] = { + 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67, 0x7f, + 0x57, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, + 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x50, 0x4b, 0x03, 0x04, 0x0a, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x7f, 0x57, 0x3d, 0xf8, 0x47, 0x0c, + 0xc6, 0x13, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, + 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, + 0x65, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x2e, 0x74, 0x78, 0x74, + 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66, 0x20, + 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x2e, 0x50, 0x4b, 0x03, 0x04, 0x0a, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x7f, 0x57, 0x3d, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, + 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, + 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x2f, 0x50, + 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x7f, 0x57, + 0x3d, 0x43, 0xe3, 0x11, 0x5f, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, + 0x00, 0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, + 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, + 0x20, 0x31, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x61, 0x2e, 0x74, + 0x78, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, + 0x66, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x41, 0x2e, 0x50, 0x4b, + 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x7f, 0x57, 0x3d, + 0x80, 0xb0, 0x3c, 0x74, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, + 0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, + 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, + 0x31, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x62, 0x2e, 0x74, 0x78, + 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66, + 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x42, 0x2e, 0x50, 0x4b, 0x03, + 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x7f, 0x57, 0x3d, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, + 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, + 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, + 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x61, 0x2f, 0x50, + 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x7f, 0x57, + 0x3d, 0x15, 0xed, 0x04, 0x2c, 0x15, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, + 0x00, 0x2c, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, + 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, + 0x20, 0x31, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x61, + 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x61, 0x31, 0x2e, 0x74, 0x78, + 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x6f, 0x66, + 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x41, 0x31, 0x2e, 0x50, 0x4b, + 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x7f, 0x57, 0x3d, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x16, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, + 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, + 0x32, 0x2f, 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x02, 0x80, 0x57, 0x3d, 0x1a, 0x5d, 0x57, 0x5d, 0x14, 0x00, 0x00, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, + 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, + 0x64, 0x65, 0x72, 0x20, 0x32, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x32, + 0x61, 0x2e, 0x74, 0x78, 0x74, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, + 0x73, 0x20, 0x6f, 0x66, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x32, 0x41, + 0x2e, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x67, 0x7f, 0x57, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, + 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, + 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x70, 0x7f, 0x57, 0x3d, 0xf8, 0x47, 0x0c, 0xc6, 0x13, 0x00, 0x00, 0x00, + 0x13, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x74, 0x65, + 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, + 0x69, 0x6c, 0x65, 0x20, 0x31, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, 0x01, + 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x7f, 0x57, + 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, + 0x00, 0x00, 0x00, 0x73, 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, + 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, + 0x65, 0x72, 0x20, 0x31, 0x2f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x7f, 0x57, 0x3d, 0x43, 0xe3, 0x11, + 0x5f, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xa7, + 0x00, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, + 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, + 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x31, 0x61, 0x2e, 0x74, 0x78, 0x74, + 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x78, 0x7f, 0x57, 0x3d, 0x80, 0xb0, 0x3c, 0x74, 0x14, 0x00, 0x00, 0x00, + 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0x74, 0x65, + 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, + 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x2f, 0x66, 0x69, 0x6c, 0x65, + 0x20, 0x31, 0x62, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, 0x01, 0x02, 0x14, + 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x7f, 0x57, 0x3d, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, + 0x00, 0x4d, 0x01, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, + 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, + 0x20, 0x31, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x61, + 0x2f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x7c, 0x7f, 0x57, 0x3d, 0x15, 0xed, 0x04, 0x2c, 0x15, 0x00, 0x00, + 0x00, 0x15, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x8b, 0x01, 0x00, 0x00, 0x74, + 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, + 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x31, 0x2f, 0x66, 0x6f, 0x6c, + 0x64, 0x65, 0x72, 0x20, 0x31, 0x61, 0x2f, 0x66, 0x69, 0x6c, 0x65, 0x20, + 0x31, 0x61, 0x31, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, 0x01, 0x02, 0x14, + 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x7f, 0x57, 0x3d, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, + 0x00, 0xea, 0x01, 0x00, 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, + 0x63, 0x68, 0x69, 0x76, 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, + 0x20, 0x32, 0x2f, 0x50, 0x4b, 0x01, 0x02, 0x14, 0x00, 0x0a, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x02, 0x80, 0x57, 0x3d, 0x1a, 0x5d, 0x57, 0x5d, 0x14, + 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x1e, 0x02, 0x00, + 0x00, 0x74, 0x65, 0x73, 0x74, 0x5f, 0x61, 0x72, 0x63, 0x68, 0x69, 0x76, + 0x65, 0x2f, 0x66, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x32, 0x2f, 0x66, + 0x69, 0x6c, 0x65, 0x20, 0x32, 0x61, 0x2e, 0x74, 0x78, 0x74, 0x50, 0x4b, + 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x09, 0x00, 0x9d, 0x02, + 0x00, 0x00, 0x71, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + +} // namespace + +// Test Zip reading. +TEST(ZipReaderTest, Read) { + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(g_test_zip, sizeof(g_test_zip) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + // Create the Zip reader. + CefRefPtr reader(CefZipReader::Create(stream)); + ASSERT_TRUE(reader.get() != NULL); + + char buff[25]; + + // Walk through the archive contents. + ASSERT_TRUE(reader->MoveToFirstFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/"); + ASSERT_EQ(reader->GetFileSize(), 0); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/file 1.txt"); + ASSERT_EQ(reader->GetFileSize(), 19); + ASSERT_TRUE(reader->OpenFile("")); + ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 19); + ASSERT_TRUE(!strncmp(buff, "Contents of file 1.", 19)); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/"); + ASSERT_EQ(reader->GetFileSize(), 0); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/file 1a.txt"); + ASSERT_EQ(reader->GetFileSize(), 20); + ASSERT_TRUE(reader->OpenFile("")); + ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20); + ASSERT_TRUE(reader->CloseFile()); + ASSERT_TRUE(!strncmp(buff, "Contents of file 1A.", 20)); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/file 1b.txt"); + ASSERT_EQ(reader->GetFileSize(), 20); + ASSERT_TRUE(reader->OpenFile("")); + ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20); + ASSERT_TRUE(reader->CloseFile()); + ASSERT_TRUE(!strncmp(buff, "Contents of file 1B.", 20)); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/folder 1a/"); + ASSERT_EQ(reader->GetFileSize(), 0); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), + "test_archive/folder 1/folder 1a/file 1a1.txt"); + ASSERT_EQ(reader->GetFileSize(), 21); + ASSERT_TRUE(reader->OpenFile("")); + ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 21); + ASSERT_TRUE(reader->CloseFile()); + ASSERT_TRUE(!strncmp(buff, "Contents of file 1A1.", 21)); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 2/"); + ASSERT_EQ(reader->GetFileSize(), 0); + + ASSERT_TRUE(reader->MoveToNextFile()); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 2/file 2a.txt"); + ASSERT_EQ(reader->GetFileSize(), 20); + ASSERT_TRUE(reader->OpenFile("")); + ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20); + ASSERT_TRUE(reader->CloseFile()); + ASSERT_TRUE(!strncmp(buff, "Contents of file 2A.", 20)); + + ASSERT_FALSE(reader->MoveToNextFile()); + + // Try seeking a particular file + ASSERT_TRUE(reader->MoveToFile("TEST_ARCHIVE/FOLDER 1/FILE 1B.TXT", false)); + ASSERT_EQ(reader->GetFileName(), "test_archive/folder 1/file 1b.txt"); + ASSERT_EQ(reader->GetFileSize(), 20); + ASSERT_TRUE(reader->OpenFile("")); + ASSERT_EQ(reader->ReadFile(buff, sizeof(buff)), 20); + ASSERT_TRUE(reader->CloseFile()); + ASSERT_TRUE(!strncmp(buff, "Contents of file 1B.", 20)); + + ASSERT_TRUE(reader->MoveToFile("test_archive/folder 1/file 1b.txt", true)); + ASSERT_FALSE(reader->MoveToFile("test_archive/folder 1/FILE 1B.txt", true)); + + ASSERT_TRUE(reader->Close()); +} + +// Test CefZipArchive object. +TEST(ZipReaderTest, ReadArchive) { + // Create the stream reader. + CefRefPtr stream( + CefStreamReader::CreateForData(g_test_zip, sizeof(g_test_zip) - 1)); + ASSERT_TRUE(stream.get() != NULL); + + // Create the Zip archive object. + CefRefPtr archive(new CefZipArchive()); + + ASSERT_EQ(archive->Load(stream, CefString(), false), (size_t)5); + + ASSERT_TRUE(archive->HasFile("test_archive/file 1.txt")); + ASSERT_TRUE(archive->HasFile("test_archive/folder 1/file 1a.txt")); + ASSERT_TRUE(archive->HasFile("test_archive/FOLDER 1/file 1b.txt")); + ASSERT_TRUE(archive->HasFile("test_archive/folder 1/folder 1a/file 1a1.txt")); + ASSERT_TRUE(archive->HasFile("test_archive/folder 2/file 2a.txt")); + + // Test content retrieval. + CefRefPtr file; + file = archive->GetFile("test_archive/folder 2/file 2a.txt"); + ASSERT_TRUE(file.get()); + + ASSERT_EQ(file->GetDataSize(), (size_t)20); + ASSERT_TRUE(!strncmp(reinterpret_cast(file->GetData()), + "Contents of file 2A.", 20)); + + // Test stream reading. + CefRefPtr reader(file->GetStreamReader()); + ASSERT_TRUE(reader.get()); + + char buff[8]; + ASSERT_EQ(reader->Read(buff, 1, 8), (size_t)8); + ASSERT_TRUE(!strncmp(buff, "Contents", 8)); + ASSERT_EQ(reader->Read(buff, 1, 8), (size_t)8); + ASSERT_TRUE(!strncmp(buff, " of file", 8)); + ASSERT_EQ(reader->Read(buff, 1, 8), (size_t)4); + ASSERT_TRUE(!strncmp(buff, " 2A.", 4)); + ASSERT_TRUE(reader->Eof()); +} diff --git a/tools/automate/automate-git.py b/tools/automate/automate-git.py new file mode 100644 index 000000000..f583dcd0c --- /dev/null +++ b/tools/automate/automate-git.py @@ -0,0 +1,960 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from optparse import OptionParser +import os +import shlex +import shutil +import subprocess +import sys +import tempfile +import urllib +import xml.etree.ElementTree as ET +import zipfile + +## +# Default URLs. +## + +depot_tools_url = 'https://chromium.googlesource.com/chromium/tools/depot_tools.git' +depot_tools_archive_url = 'https://src.chromium.org/svn/trunk/tools/depot_tools.zip' + +cef_git_trunk_url = 'https://chromiumembedded@bitbucket.org/chromiumembedded/trunk-cef3.git' +cef_git_branch_url = 'https://chromiumembedded@bitbucket.org/chromiumembedded/branches-%1-cef3.git' +cef_svn_trunk_url = 'https://chromiumembedded.googlecode.com/svn/trunk/cef3' +cef_svn_branch_url = 'https://chromiumembedded.googlecode.com/svn/branches/%1/cef3' + + +## +# Global system variables. +## + +# Operating system. +platform = ''; +if sys.platform == 'win32': + platform = 'windows' +elif sys.platform == 'darwin': + platform = 'macosx' +elif sys.platform.startswith('linux'): + platform = 'linux' + +# Script directory. +script_dir = os.path.dirname(__file__) + +# Script extension. +if platform == 'windows': + script_ext = '.bat' +else: + script_ext = '.sh' + + +## +# Helper functions. +## + +def msg(message): + """ Output a message. """ + sys.stdout.write('--> ' + message + "\n") + +def run(command_line, working_dir, depot_tools_dir=None, output_file=None): + """ Runs the specified command. """ + # add depot_tools to the path + env = os.environ + if not depot_tools_dir is None: + env['PATH'] = depot_tools_dir+os.pathsep+env['PATH'] + + sys.stdout.write('-------- Running "'+command_line+'" in "'+\ + working_dir+'"...'+"\n") + if not options.dryrun: + args = shlex.split(command_line.replace('\\', '\\\\')) + + if not output_file: + return subprocess.check_call(args, cwd=working_dir, env=env, + shell=(sys.platform == 'win32')) + with open(output_file, "w") as f: + return subprocess.check_call(args, cwd=working_dir, env=env, + shell=(sys.platform == 'win32'), + stderr=subprocess.STDOUT, stdout=f) + +def create_directory(path): + """ Creates a directory if it doesn't already exist. """ + if not os.path.exists(path): + msg("Creating directory %s" % (path)); + if not options.dryrun: + os.makedirs(path) + +def delete_directory(path): + """ Removes an existing directory. """ + if os.path.exists(path): + msg("Removing directory %s" % (path)); + if not options.dryrun: + shutil.rmtree(path, onerror=onerror) + +def copy_directory(source, target, allow_overwrite=False): + """ Copies a directory from source to target. """ + if not options.dryrun and os.path.exists(target): + if not allow_overwrite: + raise Exception("Directory %s already exists" % (target)) + remove_directory(target) + if os.path.exists(source): + msg("Copying directory %s to %s" % (source, target)); + if not options.dryrun: + shutil.copytree(source, target) + +def move_directory(source, target, allow_overwrite=False): + """ Copies a directory from source to target. """ + if not options.dryrun and os.path.exists(target): + if not allow_overwrite: + raise Exception("Directory %s already exists" % (target)) + remove_directory(target) + if os.path.exists(source): + msg("Moving directory %s to %s" % (source, target)); + if not options.dryrun: + shutil.move(source, target) + +def is_git_checkout(path): + """ Returns true if the path represents a git checkout. """ + return os.path.exists(os.path.join(path, '.git')) + +def is_svn_checkout(path): + """ Returns true if the path represents an svn checkout. """ + return os.path.exists(os.path.join(path, '.svn')) + +def exec_cmd(cmd, path): + """ Execute the specified command and return the result. """ + out = '' + err = '' + sys.stdout.write("-------- Running \"%s\" in \"%s\"...\n" % (cmd, path)) + parts = cmd.split() + try: + process = subprocess.Popen(parts, cwd=path, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=(sys.platform == 'win32')) + out, err = process.communicate() + except IOError, (errno, strerror): + raise + except: + raise + return {'out': out, 'err': err} + +def get_git_hash(path, branch): + """ Returns the git hash for the specified branch/tag/hash. """ + cmd = "%s rev-parse %s" % (git_exe, branch) + result = exec_cmd(cmd, path) + if result['out'] != '': + return result['out'].strip() + return 'Unknown' + +def get_git_url(path): + """ Returns the origin url for the specified path. """ + cmd = "%s config --get remote.origin.url" % (git_exe) + result = exec_cmd(cmd, path) + if result['out'] != '': + return result['out'].strip() + return 'Unknown' + +def get_git_svn_revision(path, branch): + """ Returns the SVN revision associated with the specified path and git + branch/tag/hash. """ + svn_rev = "None" + cmd = "%s log --grep=^git-svn-id: -n 1 %s" % (git_exe, branch) + result = exec_cmd(cmd, path) + if result['err'] == '': + for line in result['out'].split('\n'): + if line.find("git-svn-id") > 0: + svn_rev = line.split("@")[1].split()[0] + break + return svn_rev + +def get_svn_info(path): + """ Retrieves the URL and revision from svn info. """ + url = 'None' + rev = 'None' + cmd = "%s info --xml %s" % (svn_exe, path) + is_http = path[0:4] == 'http' + if is_http or os.path.exists(path): + result = exec_cmd(cmd, path if not is_http else '.') + if result['err'] == '': + tree = ET.ElementTree(ET.fromstring(result['out'])) + entry = tree.getroot().find('entry') + url = entry.find('url').text + rev = entry.attrib['revision'] + else: + raise Exception("Failed to execute svn info: %s" % (result['err'])) + return {'url': url, 'revision': rev} + +def download_and_extract(src, target, contents_prefix): + """ Extracts the contents of src, which may be a URL or local file, to the + target directory. """ + temporary = False + + if src[:4] == 'http': + # Attempt to download a URL. + opener = urllib.FancyURLopener({}) + response = opener.open(src) + + temporary = True + handle, archive_path = tempfile.mkstemp(suffix = '.zip') + os.write(handle, response.read()) + os.close(handle) + elif os.path.exists(src): + # Use a local file. + archive_path = src + else: + raise Exception('Path type is unsupported or does not exist: ' + src) + + if not zipfile.is_zipfile(archive_path): + raise Exception('Not a valid zip archive: ' + src) + + def remove_prefix(zip, prefix): + offset = len(prefix) + for zipinfo in zip.infolist(): + name = zipinfo.filename + if len(name) > offset and name[:offset] == prefix: + zipinfo.filename = name[offset:] + yield zipinfo + + # Attempt to extract the archive file. + try: + os.makedirs(target) + zf = zipfile.ZipFile(archive_path, 'r') + zf.extractall(target, remove_prefix(zf, contents_prefix)) + except: + shutil.rmtree(target, onerror=onerror) + raise + zf.close() + + # Delete the archive file if temporary. + if temporary and os.path.exists(archive_path): + os.remove(archive_path) + +def read_config_file(path): + """ Read a configuration file. """ + if os.path.exists(path): + fp = open(path, 'r') + data = fp.read() + fp.close() + else: + raise Exception("Path does not exist: %s" % (path)) + + # Parse the contents. + return eval(data, {'__builtins__': None}, None) + +def write_config_file(path, contents): + """ Write a configuration file. """ + msg('Writing file: %s' % path) + if not options.dryrun: + fp = open(path, 'w') + fp.write("{\n") + for key in sorted(contents.keys()): + fp.write(" '%s': '%s',\n" % (key, contents[key])) + fp.write("}\n") + fp.close() + +def read_branch_config_file(path): + """ Read the CEF branch from the specified path. """ + config_file = os.path.join(path, 'cef.branch') + if os.path.isfile(config_file): + contents = read_config_file(config_file) + if 'branch' in contents: + return contents['branch'] + return '' + +def write_branch_config_file(path, branch): + """ Write the CEF branch to the specified path. """ + config_file = os.path.join(path, 'cef.branch') + if not os.path.isfile(config_file): + write_config_file(config_file, {'branch': branch}) + +def remove_deps_entry(path, entry): + """ Remove an entry from the DEPS file at the specified path. """ + msg('Updating DEPS file: %s' % path) + if not options.dryrun: + if not os.path.isfile(path): + raise Exception('Path does not exist: %s' % path) + + # Read the DEPS file. + fp = open(path, 'r') + lines = fp.readlines() + fp.close() + + # Write the DEPS file. + # Each entry takes 2 lines. Skip both lines if found. + fp = open(path, 'w') + skip_next = False + for line in lines: + if skip_next: + skip_next = False + continue + elif line.find(entry) >= 0: + skip_next = True + continue + fp.write(line) + fp.close() + +def onerror(func, path, exc_info): + """ + Error handler for ``shutil.rmtree``. + + If the error is due to an access error (read only file) + it attempts to add write permission and then retries. + + If the error is for another reason it re-raises the error. + + Usage : ``shutil.rmtree(path, onerror=onerror)`` + """ + import stat + if not os.access(path, os.W_OK): + # Is the error an access error ? + os.chmod(path, stat.S_IWUSR) + func(path) + else: + raise + + +## +# Program entry point. +## + +# Cannot be loaded as a module. +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + +# Parse command-line options. +disc = """ +This utility implements automation for the download, update, build and +distribution of CEF. +""" + +parser = OptionParser(description=disc) + +# Setup options. +parser.add_option('--download-dir', dest='downloaddir', metavar='DIR', + help='Download directory with no spaces [required].') +parser.add_option('--depot-tools-dir', dest='depottoolsdir', metavar='DIR', + help='Download directory for depot_tools.', default='') +parser.add_option('--depot-tools-archive', dest='depottoolsarchive', + help='Zip archive file that contains a single top-level '+\ + 'depot_tools directory.', default='') +parser.add_option('--branch', dest='branch', + help='Branch of CEF to build (trunk, 1916, ...). This '+\ + 'will be used to name the CEF download directory and '+\ + 'to identify the correct URL if --url is not '+\ + 'specified. The default value is trunk.', + default='trunk') +parser.add_option('--url', dest='url', + help='CEF download URL. If not specified the default URL '+\ + 'will be used for the chosen branch.', + default='') +parser.add_option('--checkout', dest='checkout', + help='Version of CEF to checkout. If not specified the '+\ + 'most recent version of the branch will be used. '+\ + 'If --use-git is specified this should be a Git '+\ + 'branch/hash/tag instead of an SVN revision number.', + default='') +parser.add_option('--use-svn', + action='store_true', dest='usesvn', default=False, + help="Download CEF source code using SVN instead of Git.") +parser.add_option('--chromium-checkout', dest='chromiumcheckout', + help='Version of Chromium to checkout (Git '+\ + 'branch/hash/tag). This overrides the value specified '+\ + 'by CEF in CHROMIUM_BUILD_COMPATIBILITY.txt.', + default='') + +# Miscellaneous options. +parser.add_option('--force-config', + action='store_true', dest='forceconfig', default=False, + help='Force creation of a new gclient config file.') +parser.add_option('--force-clean', + action='store_true', dest='forceclean', default=False, + help='Force a clean checkout of Chromium and CEF. This will'+\ + ' trigger a new update, build and distribution.') +parser.add_option('--force-clean-deps', + action='store_true', dest='forcecleandeps', default=False, + help='Force a clean checkout of Chromium dependencies. Used'+\ + ' in combination with --force-clean.') +parser.add_option('--dry-run', + action='store_true', dest='dryrun', default=False, + help="Output commands without executing them.") + +# Update-related options. +parser.add_option('--force-update', + action='store_true', dest='forceupdate', default=False, + help='Force a Chromium and CEF update. This will trigger a '+\ + 'new build and distribution.') +parser.add_option('--no-update', + action='store_true', dest='noupdate', default=False, + help='Do not update Chromium or CEF. Pass --force-build or '+\ + '--force-distrib if you desire a new build or '+\ + 'distribution.') + +# Build-related options. +parser.add_option('--force-build', + action='store_true', dest='forcebuild', default=False, + help='Force CEF debug and release builds. This builds '+\ + 'cefclient on all platforms and chrome_sandbox on '+\ + 'Linux.') +parser.add_option('--no-build', + action='store_true', dest='nobuild', default=False, + help='Do not build CEF.') +parser.add_option('--build-tests', + action='store_true', dest='buildtests', default=False, + help='Also build the cef_unittests target.') +parser.add_option('--no-debug-build', + action='store_true', dest='nodebugbuild', default=False, + help="Don't perform the CEF debug build.") +parser.add_option('--no-release-build', + action='store_true', dest='noreleasebuild', default=False, + help="Don't perform the CEF release build.") +parser.add_option('--verbose-build', + action='store_true', dest='verbosebuild', default=False, + help='Show all command lines while building.') +parser.add_option('--build-log-file', + action='store_true', dest='buildlogfile', default=False, + help='Write build logs to file. The file will be named '+\ + '"build-[branch]-[debug|release].log" in the download '+\ + 'directory.') +parser.add_option('--x64-build', + action='store_true', dest='x64build', default=False, + help='Build for 64-bit systems (Windows and Mac OS X only).') + +# Distribution-related options. +parser.add_option('--force-distrib', + action='store_true', dest='forcedistrib', default=False, + help='Force creation of a CEF binary distribution.') +parser.add_option('--no-distrib', + action='store_true', dest='nodistrib', default=False, + help="Don't create a CEF binary distribution.") +parser.add_option('--minimal-distrib', + action='store_true', dest='minimaldistrib', default=False, + help='Create a minimal CEF binary distribution.') +parser.add_option('--minimal-distrib-only', + action='store_true', dest='minimaldistribonly', default=False, + help='Create a minimal CEF binary distribution only.') +parser.add_option('--client-distrib', + action='store_true', dest='clientdistrib', default=False, + help='Create a client CEF binary distribution.') +parser.add_option('--client-distrib-only', + action='store_true', dest='clientdistribonly', default=False, + help='Create a client CEF binary distribution only.') +parser.add_option('--no-distrib-docs', + action='store_true', dest='nodistribdocs', default=False, + help="Don't create CEF documentation.") +parser.add_option('--no-distrib-archive', + action='store_true', dest='nodistribarchive', default=False, + help="Don't create archives for output directories.") +parser.add_option('--clean-artifacts', + action='store_true', dest='cleanartifacts', default=False, + help='Clean the artifacts output directory.') + +(options, args) = parser.parse_args() + +if options.downloaddir is None: + print "The --download-dir option is required." + parser.print_help(sys.stderr) + sys.exit() + +if options.noupdate and options.forceupdate or \ + options.nobuild and options.forcebuild or \ + options.nodistrib and options.forcedistrib: + print "Invalid combination of options." + parser.print_help(sys.stderr) + sys.exit() + +if (options.noreleasebuild and \ + (options.minimaldistrib or options.minimaldistribonly or \ + options.clientdistrib or options.clientdistribonly)) or \ + (options.minimaldistribonly and options.clientdistribonly): + print 'Invalid combination of options.' + parser.print_help(sys.stderr) + sys.exit() + +if options.x64build and platform != 'windows' and platform != 'macosx': + print 'The x64 build option is only used on Windows and Mac OS X.' + sys.exit() + +if platform == 'windows' and not 'GYP_MSVS_VERSION' in os.environ.keys(): + print 'You must set the GYP_MSVS_VERSION environment variable on Windows.' + sys.exit() + +# Options that force the sources to change. +force_change = options.forceclean or options.forceupdate + + +## +# Manage the download directory. +## + +# Create the download directory if necessary. +download_dir = os.path.abspath(options.downloaddir) +create_directory(download_dir) + +msg("Download Directory: %s" % (download_dir)) + + +## +# Manage the depot_tools directory. +## + +# Check if the depot_tools directory exists. +if options.depottoolsdir != '': + depot_tools_dir = os.path.abspath(options.depottoolsdir) +else: + depot_tools_dir = os.path.join(download_dir, 'depot_tools') + +msg("Depot Tools Directory: %s" % (depot_tools_dir)) + +if not os.path.exists(depot_tools_dir): + if platform == 'windows' and options.depottoolsarchive == '': + # On Windows download depot_tools as an archive file since we can't assume + # that git is already installed. + options.depottoolsarchive = depot_tools_archive_url + + if options.depottoolsarchive != '': + # Extract depot_tools from an archive file. + msg('Extracting %s to %s.' % \ + (options.depottoolsarchive, depot_tools_dir)) + if not options.dryrun: + download_and_extract(options.depottoolsarchive, depot_tools_dir, \ + 'depot_tools/') + else: + # On Linux and OS X check out depot_tools using Git. + run('git clone '+depot_tools_url+' '+depot_tools_dir, download_dir) + +if not options.noupdate: + # Update depot_tools. + # On Windows this will download required python and git binaries. + if platform == 'windows': + run('update_depot_tools.bat', depot_tools_dir, depot_tools_dir); + else: + run('update_depot_tools', depot_tools_dir, depot_tools_dir); + +# Determine the svn/git executables to use. +if platform == 'windows': + # Force use of the version bundled with depot_tools. + svn_exe = os.path.join(depot_tools_dir, 'svn.bat') + git_exe = os.path.join(depot_tools_dir, 'git.bat') + if options.dryrun and (not os.path.exists(svn_exe) or \ + not os.path.exists(git_exe)): + sys.stdout.write("WARNING: --dry-run assumes that depot_tools" \ + " is already in your PATH. If it isn't\nplease" \ + " specify a --depot-tools-dir value.\n") + svn_exe = 'svn.bat' + git_exe = 'git.bat' +else: + svn_exe = 'svn' + git_exe = 'git' + + +## +# Manage the cef directory. +## + +# Validate the branch value. +if options.branch != 'trunk' and not options.branch.isdigit(): + raise Exception("Invalid branch value: %s" % (options.branch)) +cef_branch = options.branch + +cef_dir = os.path.join(download_dir, 'cef_' + cef_branch) + +# Delete the existing CEF directory if requested. +if options.forceclean and os.path.exists(cef_dir): + delete_directory(cef_dir) + +# Determine the type of CEF checkout to use. +if os.path.exists(cef_dir): + if is_git_checkout(cef_dir): + cef_use_git = True + elif is_svn_checkout(cef_dir): + cef_use_git = False + else: + raise Exception("Not a valid CEF checkout: %s" % (cef_dir)) + + if cef_use_git == options.usesvn: + raise Exception( + "The existing and requested CEF checkout types do not match") +else: + cef_use_git = not options.usesvn + +# Determine the CEF download URL to use. +if options.url == '': + if cef_branch == 'trunk': + if cef_use_git: + cef_url = cef_git_trunk_url + else: + cef_url = cef_svn_trunk_url + else: + if cef_use_git: + cef_url = cef_git_branch_url + else: + cef_url = cef_svn_branch_url + cef_url = cef_url.replace('%1', cef_branch) +else: + cef_url = options.url + +# Verify that the requested CEF URL matches the existing checkout. +if os.path.exists(cef_dir): + if cef_use_git: + cef_existing_url = get_git_url(cef_dir) + else: + cef_existing_url = get_svn_info(cef_dir)['url'] + if cef_url != cef_existing_url: + raise Exception('Requested CEF checkout URL %s does not match existing '+\ + 'URL %s' % (cef_url, cef_existing_url)) + +msg("CEF Branch: %s" % (cef_branch)) +msg("CEF URL: %s" % (cef_url)) +msg("CEF Source Directory: %s" % (cef_dir)) + +# Determine the CEF SVN revision or Git checkout to use. +if options.checkout == '': + # Use the CEF head revision. + if cef_use_git: + cef_checkout = 'origin/master' + else: + cef_checkout = get_svn_info(cef_url)['revision'] +else: + cef_checkout = options.checkout + if not cef_use_git and not cef_checkout.isdigit(): + raise Exception("Invalid SVN revision number: %s" % (cef_checkout)) + +# Create the CEF checkout if necessary. +if not options.noupdate and not os.path.exists(cef_dir): + cef_checkout_new = True + if cef_use_git: + run('%s clone %s %s' % (git_exe, cef_url, cef_dir), download_dir, \ + depot_tools_dir) + else: + run('%s checkout %s -r %s %s' % (svn_exe, cef_url, cef_checkout, cef_dir), \ + download_dir, depot_tools_dir) +else: + cef_checkout_new = False + +# Verify the CEF checkout. +if not options.dryrun: + if cef_use_git and not is_git_checkout(cef_dir): + raise Exception('Not a valid git checkout: %s' % (cef_dir)) + if not cef_use_git and not is_svn_checkout(cef_dir): + raise Exception('Not a valid svn checkout: %s' % (cef_dir)) + +# Update the CEF checkout if necessary. +if not options.noupdate and os.path.exists(cef_dir): + if cef_use_git: + cef_current_hash = get_git_hash(cef_dir, 'HEAD') + + if not cef_checkout_new: + # Fetch new sources. + run('%s fetch' % (git_exe), cef_dir, depot_tools_dir) + + cef_desired_hash = get_git_hash(cef_dir, cef_checkout) + cef_checkout_changed = cef_checkout_new or force_change or \ + cef_current_hash != cef_desired_hash + + msg("CEF Current Checkout: %s" % (cef_current_hash)) + msg("CEF Current Revision: %s" % \ + (get_git_svn_revision(cef_dir, cef_current_hash))) + msg("CEF Desired Checkout: %s (%s)" % (cef_desired_hash, cef_checkout)) + msg("CEF Desired Revision: %s" % \ + (get_git_svn_revision(cef_dir, cef_desired_hash))) + + if cef_checkout_changed: + # Checkout the requested branch. + run('%s checkout %s%s' % + (git_exe, ('--force ' if options.forceclean else ''), cef_checkout), \ + cef_dir, depot_tools_dir) + else: + cef_current_info = get_svn_info(cef_dir) + if cef_current_info['url'] != cef_url: + raise Exception("CEF URL does not match; found %s, expected %s" % + (cef_current_info['url'], cef_url)) + + cef_checkout_changed = cef_checkout_new or force_change or \ + cef_current_info['revision'] != cef_checkout + + msg("CEF Current Revision: %s" % (cef_current_info['revision'])) + msg("CEF Desired Revision: %s" % (cef_checkout)) + + if cef_checkout_changed and not cef_checkout_new: + # Update to the requested revision. + run('%s update -r %s' % (svn_exe, cef_checkout), cef_dir, depot_tools_dir) +else: + cef_checkout_changed = False + + +## +# Manage the out directory. +## + +out_dir = os.path.join(download_dir, 'out_' + cef_branch) + +# Delete the existing out directory if requested. +if options.forceclean and os.path.exists(out_dir): + delete_directory(out_dir) + +msg("CEF Output Directory: %s" % (out_dir)) + + +## +# Manage the chromium directory. +## + +# Create the chromium directory if necessary. +chromium_dir = os.path.join(download_dir, 'chromium') +create_directory(chromium_dir) + +chromium_src_dir = os.path.join(chromium_dir, 'src') +cef_src_dir = os.path.join(chromium_src_dir, 'cef') +out_src_dir = os.path.join(chromium_src_dir, 'out') + +# Create gclient configuration file. +gclient_file = os.path.join(chromium_dir, '.gclient') +if not os.path.exists(gclient_file) or options.forceconfig: + # Exclude unnecessary directories. Intentionally written without newlines. + gclient_spec = \ + "solutions = [{"+\ + "u'managed': False,"+\ + "u'name': u'src', "+\ + "u'url': u'https://chromium.googlesource.com/chromium/src.git', "+\ + "u'custom_deps': {"+\ + "u'build': None, "+\ + "u'build/scripts/command_wrapper/bin': None, "+\ + "u'build/scripts/gsd_generate_index': None, "+\ + "u'build/scripts/private/data/reliability': None, "+\ + "u'build/third_party/lighttpd': None, "+\ + "u'commit-queue': None, "+\ + "u'depot_tools': None, "+\ + "u'src/chrome_frame/tools/test/reference_build/chrome': None, "+\ + "u'src/chrome/tools/test/reference_build/chrome_linux': None, "+\ + "u'src/chrome/tools/test/reference_build/chrome_mac': None, "+\ + "u'src/chrome/tools/test/reference_build/chrome_win': None, "+\ + "}, "+\ + "u'deps_file': u'.DEPS.git', "+\ + "u'safesync_url': u''"+\ + "}]" + + msg('Writing file: %s' % gclient_file) + if not options.dryrun: + fp = open(gclient_file, 'w') + fp.write(gclient_spec) + fp.close() + +# Initial Chromium checkout. +if not options.noupdate and not os.path.exists(chromium_src_dir): + chromium_checkout_new = True + run("gclient sync --nohooks --with_branch_heads --jobs 16", chromium_dir, \ + depot_tools_dir) +else: + chromium_checkout_new = False + +# Verify the Chromium checkout. +if not options.dryrun and not is_git_checkout(chromium_src_dir): + raise Exception('Not a valid git checkout: %s' % (chromium_src_dir)) + +if os.path.exists(chromium_src_dir): + msg("Chromium URL: %s" % (get_git_url(chromium_src_dir))) + +# Determine the Chromium checkout options required by CEF. +chromium_nohooks = False +if options.chromiumcheckout == '': + # Read the build compatibility file to identify the checkout name. + compat_path = os.path.join(cef_dir, 'CHROMIUM_BUILD_COMPATIBILITY.txt') + config = read_config_file(compat_path) + + if 'chromium_checkout' in config: + chromium_checkout = config['chromium_checkout'] + else: + raise Exception("Missing chromium_checkout value in %s" % (compat_path)) + + # Some branches run hooks using CEF instead of Chromium. + if 'chromium_nohooks' in config: + chromium_nohooks = config['chromium_nohooks'] +else: + chromium_checkout = options.chromiumcheckout + +# Determine if the Chromium checkout needs to change. +if not options.noupdate and os.path.exists(chromium_src_dir): + chromium_current_hash = get_git_hash(chromium_src_dir, 'HEAD') + chromium_desired_hash = get_git_hash(chromium_src_dir, chromium_checkout) + chromium_checkout_changed = chromium_checkout_new or force_change or \ + chromium_current_hash != chromium_desired_hash + + msg("Chromium Current Checkout: %s" % (chromium_current_hash)) + msg("Chromium Current Revision: %s" % \ + (get_git_svn_revision(chromium_src_dir, chromium_current_hash))) + msg("Chromium Desired Checkout: %s (%s)" % \ + (chromium_desired_hash, chromium_checkout)) + msg("Chromium Desired Revision: %s" % \ + (get_git_svn_revision(chromium_src_dir, chromium_desired_hash))) +else: + chromium_checkout_changed = options.dryrun + +# Delete the existing src/cef directory. It will be re-copied from the download +# directory later. +if cef_checkout_changed and os.path.exists(cef_src_dir): + delete_directory(cef_src_dir) + +# Delete the existing src/out directory if requested. +if options.forceclean and os.path.exists(out_src_dir): + delete_directory(out_src_dir) + +# Move the existing src/out directory to the correct location in the download +# directory. It will be moved back from the download directory later. +if os.path.exists(out_src_dir): + old_branch = read_branch_config_file(out_src_dir) + if chromium_checkout_changed or old_branch != cef_branch: + old_out_dir = os.path.join(download_dir, 'out_' + old_branch) + move_directory(out_src_dir, old_out_dir) + +# Update the Chromium checkout. +if chromium_checkout_changed: + if not chromium_checkout_new: + if options.forceclean and options.forcecleandeps: + # Remove all local changes including third-party git checkouts managed by + # gclient. + run("%s clean -dffx" % (git_exe), chromium_src_dir, depot_tools_dir) + else: + # Revert all changes in the Chromium checkout. + run("gclient revert --nohooks", chromium_dir, depot_tools_dir) + + # Fetch new sources. + run("%s fetch" % (git_exe), chromium_src_dir, depot_tools_dir) + # Also fetch tags, which are required for release branch builds. + run("%s fetch --tags" % (git_exe), chromium_src_dir, depot_tools_dir) + + # Checkout the requested branch. + run("%s checkout %s%s" % \ + (git_exe, ('--force ' if options.forceclean else ''), chromium_checkout), \ + chromium_src_dir, depot_tools_dir) + + if cef_branch != 'trunk': + # Remove the 'src' entry from .DEPS.git for release branches. + # Otherwise, `gclient sync` will fail. + deps_path = os.path.join(chromium_src_dir, '.DEPS.git') + remove_deps_entry(deps_path, "'src'") + + # Update third-party dependencies including branch/tag information. + run("gclient sync %s%s--with_branch_heads --jobs 16" % \ + (('--reset ' if options.forceclean else ''), \ + ('--nohooks ' if chromium_nohooks else '')), \ + chromium_dir, depot_tools_dir) + + # Delete the src/out directory created by `gclient sync`. + delete_directory(out_src_dir) + +# Restore the src/cef directory. +if os.path.exists(cef_dir) and not os.path.exists(cef_src_dir): + copy_directory(cef_dir, cef_src_dir) + +# Restore the src/out directory. +if os.path.exists(out_dir) and not os.path.exists(out_src_dir): + move_directory(out_dir, out_src_dir) + + +## +# Build CEF. +## + +if not options.nobuild and (chromium_checkout_changed or \ + cef_checkout_changed or options.forcebuild or \ + not os.path.exists(out_src_dir)): + # Building should also force a distribution. + options.forcedistrib = True + + # Run the cef_create_projects script to generate Ninja project files. + os.environ['GYP_GENERATORS'] = 'ninja' + if options.x64build: + if 'GYP_DEFINES' in os.environ.keys(): + os.environ['GYP_DEFINES'] = os.environ['GYP_DEFINES'] + ' ' + \ + 'target_arch=x64' + else: + os.environ['GYP_DEFINES'] = 'target_arch=x64' + path = os.path.join(cef_src_dir, 'cef_create_projects'+script_ext) + run(path, cef_src_dir, depot_tools_dir) + + # Write the config file for identifying the branch. + write_branch_config_file(out_src_dir, cef_branch) + + # Build using Ninja. + command = 'ninja -C ' + if options.verbosebuild: + command = 'ninja -v -C' + target = ' cefclient' + if options.buildtests: + target = target + ' cef_unittests' + if platform == 'linux': + target = target + ' chrome_sandbox' + build_dir_suffix = '' + if platform == 'windows' and options.x64build: + build_dir_suffix = '_x64' + + if not options.nodebugbuild: + # Make a CEF Debug build. + run(command + os.path.join('out', 'Debug' + build_dir_suffix) + target, \ + chromium_src_dir, depot_tools_dir, + os.path.join(download_dir, 'build-%s-debug.log' % (cef_branch)) \ + if options.buildlogfile else None) + + if not options.noreleasebuild: + # Make a CEF Release build. + run(command + os.path.join('out', 'Release' + build_dir_suffix) + target, \ + chromium_src_dir, depot_tools_dir, + os.path.join(download_dir, 'build-%s-release.log' % (cef_branch)) \ + if options.buildlogfile else None) + + +## +# Create the CEF binary distribution. +## + +if not options.nodistrib and (chromium_checkout_changed or \ + cef_checkout_changed or options.forcedistrib): + if not options.forceclean and options.cleanartifacts: + # Clean the artifacts output directory. + artifacts_path = os.path.join(cef_src_dir, 'binary_distrib') + delete_directory(artifacts_path) + + # Determine the requested distribution types. + distrib_types = [] + if options.minimaldistribonly: + distrib_types.append('minimal') + elif options.clientdistribonly: + distrib_types.append('client') + else: + distrib_types.append('standard') + if options.minimaldistrib: + distrib_types.append('minimal') + if options.clientdistrib: + distrib_types.append('client') + + cef_tools_dir = os.path.join(cef_src_dir, 'tools') + + # Create the requested distribution types. + first_type = True + for type in distrib_types: + path = os.path.join(cef_tools_dir, 'make_distrib'+script_ext) + if options.nodebugbuild or options.noreleasebuild or type != 'standard': + path = path + ' --allow-partial' + path = path + ' --ninja-build' + if options.x64build: + path = path + ' --x64-build' + + if type == 'minimal': + path = path + ' --minimal' + elif type == 'client': + path = path + ' --client' + + if first_type: + if options.nodistribdocs: + path = path + ' --no-docs' + if options.nodistribarchive: + path = path + ' --no-archive' + first_type = False + else: + # Don't create the symbol archives or documentation more than once. + path = path + ' --no-symbols --no-docs' + + # Create the distribution. + run(path, cef_tools_dir, depot_tools_dir) diff --git a/tools/automate/gitsvnmirror.py b/tools/automate/gitsvnmirror.py new file mode 100644 index 000000000..32334a407 --- /dev/null +++ b/tools/automate/gitsvnmirror.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python +# Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +import httplib +from optparse import OptionParser +import os +import re +import shlex +import subprocess +import sys +import urllib +import urlparse + +# Cannot be loaded as a module. +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + +def run(command_line, working_dir): + """ Run the specified command line. """ + if not options.quiet: + print '-------- Running "%s" in "%s"...' % (command_line, working_dir) + if not options.dryrun: + args = shlex.split(command_line.replace('\\', '\\\\')) + return subprocess.check_call(args, cwd=working_dir, env=os.environ, + shell=(sys.platform == 'win32')) + +def fail(message): + """ Exit the script due to an execution failure. """ + print message + sys.exit(1) + +def url_request(url, method, headers, body, expected_response): + """ Execute an arbitrary request. """ + parsed_url = urlparse.urlparse(url) + if parsed_url.scheme == "http": + connection = httplib.HTTPConnection(parsed_url.netloc) + elif parsed_url.scheme == "https": + connection = httplib.HTTPSConnection(parsed_url.netloc) + else: + print 'Unsupported URL format for %s' % url + return None + + connection.putrequest(method, url) + + if not headers is None: + for key, val in headers.iteritems(): + connection.putheader(key, val) + if not body is None: + connection.putheader('Content-Length', len(body)) + connection.endheaders() + + if not body is None: + connection.send(body) + + response = connection.getresponse() + if response.status == expected_response: + return response.read() + else: + print 'URL %s returned unexpected response code %d' % \ + (url, response.status) + return None + +def url_propfind(url, depth, body): + """ Execute a PROPFIND request. """ + return url_request(url, 'PROPFIND', + {'Depth': depth, 'Content-Type': 'text/xml'}, body, 207) + +def url_get(url): + """ Execute a GET request. """ + return url_request(url, 'GET', None, None, 200) + +def extract_string(str, start, end): + """ Returns the string between start and end. """ + s = str.find(start) + if s < 0: + return None + slen = len(start) + e = str.find(end, s + slen) + if e < 0: + return None + return str[s + slen:e] + +def extract_int(str, start, end): + """ Returns the integer between start and end. """ + val = extract_string(str, start, end) + if not val is None and re.match('^[0-9]{1,}$', val): + return int(val) + return None + +def read_file(name, normalize = True): + """ Read a file. """ + try: + f = open(name, 'r') + # read the data + data = f.read() + if normalize: + # normalize line endings + data = data.replace("\r\n", "\n") + return data + except IOError, (errno, strerror): + print 'Failed to read file %s: %s' % (name, strerror) + else: + f.close() + return None + +def write_file(name, data): + """ Write a file. """ + try: + f = open(name, 'w') + f.write(data) + return True + except IOError, (errno, strerror): + print 'Failed to write file %s: %s' % (name, strerror) + else: + f.close() + return True + +def read_cache_file(name, args): + """ Read and parse a cache file (key=value pairs, one per line). """ + content = read_file(name) + if content is None: + return False + lines = content.split("\n") + for line in lines: + parts = line.split('=', 1) + if len(parts) == 2: + args[parts[0]] = parts[1] + return True + +def write_cache_file(name, args): + """ Write a cache file (key=value pairs, one per line). """ + data = '' + for key, val in args.iteritems(): + data = data + key + '=' + str(val) + "\n" + return write_file(name, data) + + +# Parse command-line options. +disc = """This utility creates and synchronizes git-svn clones of CEF SVN +repositories.""" + +parser = OptionParser(description=disc) +parser.add_option('--storage-dir', dest='storagedir', metavar='DIR', + help='local directory where data will be stored') +parser.add_option('--branch', dest='branch', + help='CEF branch to clone ' + + '(trunk/cef3, branches/1453/cef3, etc)') +parser.add_option('--git-repo', dest='gitrepo', + help='remote repo where the git data will be pushed ' + + '(user@domain:path/to/repo.git)') +parser.add_option('--force', + action='store_true', dest='force', default=False, + help="force the run even if the revision hasn't changed") +parser.add_option('--dry-run', + action='store_true', dest='dryrun', default=False, + help="output commands without executing them") +parser.add_option('-q', '--quiet', + action='store_true', dest='quiet', default=False, + help='do not output detailed status information') +(options, args) = parser.parse_args() + +# Required options. +if options.storagedir is None or options.branch is None or \ + options.gitrepo is None: + parser.print_help(sys.stderr) + sys.exit(1) + +# Validate the git repo format. Should be user@domain:path/to/repo.git +if not re.match( + '^[a-zA-Z0-9_\-]{1,}@[a-zA-Z0-9\-\.]{1,}:[a-zA-Z0-9\-_/]{1,}\.git$', + options.gitrepo): + fail('Invalid git repo format: %s' % options.gitrepo) + +svn_url = 'https://chromiumembedded.googlecode.com/svn/' + options.branch + +# Verify that the requested branch is valid CEF root directory. +value = url_get(svn_url + '/CHROMIUM_BUILD_COMPATIBILITY.txt') +if value is None: + fail('Invalid branch "%s"' % options.branch) + +# Retrieve the most recent revision for the branch. +revision = None +request = '' + \ + '' +value = url_propfind(svn_url, 0, request) +if not value is None: + revision = extract_int(value, '', '') +if revision is None: + fail('Failed to discover revision for branch "%s"' % options.branch) + +branch_path_comp = options.branch.replace('/', '-') + +# Create the branch storage directory if it doesn't already exist. +branch_dir = os.path.join(options.storagedir, branch_path_comp) +if not os.path.exists(branch_dir): + os.makedirs(branch_dir) + +# Default cache configuration. +cache_config = { + 'last_revision': 0, +} + +# Create the authors.txt file if it doesn't already exist +authors_file_path = os.path.join(options.storagedir, 'authors.txt') +if not os.path.exists(authors_file_path): + content = 'magreenblatt@gmail.com = ' + \ + 'Marshall Greenblatt ' + if not write_file(authors_file_path, content): + fail('Failed to create authors.txt file: %s' % authors_file_path) + +# Read the cache file if it exists. +cache_file_path = os.path.join(branch_dir, 'cache.txt') +if os.path.exists(cache_file_path): + if not read_cache_file(cache_file_path, cache_config): + print 'Failed to read cache.txt file %s' % cache_file_path + +# Check if the revision has changed. +if not options.force and int(cache_config['last_revision']) == revision: + if not options.quiet: + print 'Already at revision %d' % revision + sys.exit() + +repo_dir = os.path.join(branch_dir, branch_path_comp) +if not os.path.exists(repo_dir): + # Create the git repository. + run('git svn clone -A %s %s %s' % (authors_file_path, svn_url, repo_dir), + branch_dir) + run('git remote add origin %s' % options.gitrepo, repo_dir) +else: + # Rebase the git repository. + run('git svn rebase --fetch-all -A %s' % authors_file_path, repo_dir) + +run('git push origin --all', repo_dir) + +# Write the cache file. +cache_config['last_revision'] = revision +if not write_cache_file(cache_file_path, cache_config): + print 'Failed to write cache file %s' % cache_file_path diff --git a/tools/cef_api_hash.py b/tools/cef_api_hash.py new file mode 100644 index 000000000..df5c13505 --- /dev/null +++ b/tools/cef_api_hash.py @@ -0,0 +1,245 @@ +# Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from file_util import * +import os +import re +import shutil +import string +import sys +import textwrap +import time +import itertools +import hashlib + + +class cef_api_hash: + """ CEF API hash calculator """ + + def __init__(self, headerdir, debugdir = None, verbose = False): + if headerdir is None or len(headerdir) == 0: + raise AssertionError("headerdir is not specified") + + self.__headerdir = headerdir; + self.__debugdir = debugdir; + self.__verbose = verbose; + self.__debug_enabled = not (self.__debugdir is None) and len(self.__debugdir) > 0; + + self.platforms = [ "windows", "macosx", "linux" ]; + + self.platform_files = { + "windows": [ + "internal/cef_types_win.h", + ], + "macosx": [ + "internal/cef_types_mac.h", + ], + "linux": [ + "internal/cef_types_linux.h", + ] + }; + + self.included_files = [ + ]; + + self.excluded_files = [ + "cef_version.h", + "internal/cef_tuple.h", + "internal/cef_types_wrappers.h", + "internal/cef_string_wrappers.h", + "internal/cef_win.h", + "internal/cef_mac.h", + "internal/cef_linux.h", + ]; + + def calculate(self): + filenames = [filename for filename in self.__get_filenames() if not filename in self.excluded_files] + + objects = [] + for filename in filenames: + if self.__verbose: + print "Processing " + filename + "..." + content = read_file(os.path.join(self.__headerdir, filename), True) + platforms = list([p for p in self.platforms if self.__is_platform_filename(filename, p)]) + + # Parse cef_string.h happens in special case: grab only defined CEF_STRING_TYPE_xxx declaration + content_objects = None + if filename == "internal/cef_string.h": + content_objects = self.__parse_string_type(content) + else: + content_objects = self.__parse_objects(content) + + for o in content_objects: + o["text"] = self.__prepare_text(o["text"]) + o["platforms"] = platforms + o["filename"] = filename + objects.append(o) + + # objects will be sorted including filename, to make stable universal hashes + objects = sorted(objects, key = lambda o: o["name"] + "@" + o["filename"]) + + if self.__debug_enabled: + namelen = max([len(o["name"]) for o in objects]) + filenamelen = max([len(o["filename"]) for o in objects]) + dumpsig = []; + for o in objects: + dumpsig.append(format(o["name"], str(namelen) + "s") + "|" + format(o["filename"], "" + str(filenamelen) + "s") + "|" + o["text"]); + self.__write_debug_file("objects.txt", dumpsig) + + revisions = { }; + + for platform in itertools.chain(["universal"], self.platforms): + sig = self.__get_final_sig(objects, platform) + if self.__debug_enabled: + self.__write_debug_file(platform + ".sig", sig) + rev = hashlib.sha1(sig).digest(); + revstr = ''.join(format(ord(i),'0>2x') for i in rev) + revisions[platform] = revstr + + return revisions + + def __parse_objects(self, content): + """ Returns array of objects in content file. """ + objects = [] + content = re.sub("//.*\n", "", content) + + # function declarations + for m in re.finditer("\nCEF_EXPORT\s+?.*?\s+?(\w+)\s*?\(.*?\)\s*?;", content, flags = re.DOTALL): + object = { + "name": m.group(1), + "text": m.group(0).strip() + } + objects.append(object) + + # structs + for m in re.finditer("\ntypedef\s+?struct\s+?(\w+)\s+?\{.*?\}\s+?(\w+)\s*?;", content, flags = re.DOTALL): + object = { + "name": m.group(2), + "text": m.group(0).strip() + } + objects.append(object) + + # enums + for m in re.finditer("\nenum\s+?(\w+)\s+?\{.*?\}\s*?;", content, flags = re.DOTALL): + object = { + "name": m.group(1), + "text": m.group(0).strip() + } + objects.append(object) + + # typedefs + for m in re.finditer("\ntypedef\s+?.*?\s+(\w+);", content, flags = 0): + object = { + "name": m.group(1), + "text": m.group(0).strip() + } + objects.append(object) + + return objects + + def __parse_string_type(self, content): + """ Grab defined CEF_STRING_TYPE_xxx """ + objects = [] + for m in re.finditer("\n\s*?#\s*?define\s+?(CEF_STRING_TYPE_\w+)\s+?.*?\n", content, flags = 0): + object = { + "name": m.group(1), + "text": m.group(0), + } + objects.append(object) + return objects + + def __prepare_text(self, text): + text = text.strip() + text = re.sub("\s+", " ", text); + text = re.sub("\(\s+", "(", text); + return text + + def __get_final_sig(self, objects, platform): + sig = [] + + for o in objects: + if platform == "universal" or platform in o["platforms"]: + sig.append(o["text"]) + + return "\n".join(sig) + + def __get_filenames(self): + """ Returns file names to be processed, relative to headerdir """ + headers = [os.path.join(self.__headerdir, filename) for filename in self.included_files]; + headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "capi", "*.h"))) + headers = itertools.chain(headers, get_files(os.path.join(self.__headerdir, "internal", "*.h"))) + + for v in self.platform_files.values(): + headers = itertools.chain(headers, [os.path.join(self.__headerdir, f) for f in v]) + + normalized = [os.path.relpath(filename, self.__headerdir) for filename in headers]; + normalized = [f.replace('\\', '/').lower() for f in normalized]; + + return list(set(normalized)); + + def __is_platform_filename(self, filename, platform): + if platform == "universal": + return True + if not platform in self.platform_files: + return False + listed = False + for p in self.platforms: + if filename in self.platform_files[p]: + if p == platform: + return True + else: + listed = True + return not listed + + def __write_debug_file(self, filename, content): + make_dir(self.__debugdir); + outfile = os.path.join(self.__debugdir, filename); + dir = os.path.dirname(outfile); + make_dir(dir); + if not isinstance(content, basestring): + content = "\n".join(content) + write_file(outfile, content) + + +if __name__ == "__main__": + from optparse import OptionParser + import time + + disc = """ + This utility calculates CEF API hash. + """ + + parser = OptionParser(description=disc) + parser.add_option('--cpp-header-dir', dest='cppheaderdir', metavar='DIR', + help='input directory for C++ header files [required]') + parser.add_option('--debug-dir', dest='debugdir', metavar='DIR', + help='intermediate directory for easy debugging') + parser.add_option('-v', '--verbose', + action='store_true', dest='verbose', default=False, + help='output detailed status information') + (options, args) = parser.parse_args() + + # the cppheader option is required + if options.cppheaderdir is None: + parser.print_help(sys.stdout) + sys.exit() + + # calculate + c_start_time = time.time() + + calc = cef_api_hash(options.cppheaderdir, options.debugdir, options.verbose); + revisions = calc.calculate(); + + c_completed_in = time.time() - c_start_time + + print "{" + for k in sorted(revisions.keys()): + print format("\"" + k + "\"", ">12s") + ": \"" + revisions[k] + "\"" + print "}" + # print + # print 'Completed in: ' + str(c_completed_in) + # print + + # print "Press any key to continue..."; + # sys.stdin.readline(); diff --git a/tools/cef_parser.py b/tools/cef_parser.py new file mode 100644 index 000000000..80c83fcc9 --- /dev/null +++ b/tools/cef_parser.py @@ -0,0 +1,1870 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from date_util import * +from file_util import * +import os +import re +import shutil +import string +import sys +import textwrap +import time + + +def notify(msg): + """ Display a message. """ + sys.stdout.write(' NOTE: '+msg+'\n') + +def wrap_text(text, indent = '', maxchars = 80): + """ Wrap the text to the specified number of characters. If + necessary a line will be broken and wrapped after a word. + """ + result = '' + lines = textwrap.wrap(text, maxchars - len(indent)) + for line in lines: + result += indent+line+'\n' + return result + +def wrap_code(code, indent = ' ', maxchars = 80, splitchars = '(=,'): + """ Wrap the code lines to the specified number of characters. If + necessary a line will be broken and wrapped after one of the split + characters. + """ + output = '' + + # normalize line endings + code = code.replace("\r\n", "\n") + + # break the code chunk into lines + lines = string.split(code, '\n') + for line in lines: + if len(line) <= maxchars: + # line is short enough that it doesn't need to be wrapped + output += line + '\n' + continue + + # retrieve the whitespace at the beginning of the line for later use + # as padding + ws = '' + for char in line: + if char.isspace(): + ws += char + else: + break + + # iterate over all characters in the string keeping track of where the + # last valid break character was found and wrapping the line + # accordingly + lastsplit = 0 + nextsplit = -1 + splitct = 0 + pos = 0 + for char in line: + if splitchars.find(char) >= 0: + # a new split position has been found + nextsplit = pos + size = pos - lastsplit + 1 + if splitct > 0: + size += len(ws) + len(indent) + if size >= maxchars: + # the line is too long + section = line[lastsplit:nextsplit+1] + if len(section) > 0: + # output the line portion between the last split and the + # next split + if splitct > 0: + # start a new line and trim the line section + output += '\n'+ws+indent + section = string.strip(section) + output += section + lastsplit = nextsplit + 1 + splitct += 1 + pos += 1 + if len(line) - lastsplit > 0: + # output the remainder of the line + section = line[lastsplit:] + if splitct > 0: + # start a new line and trim the line section + output += '\n'+ws+indent + section = string.strip(section) + output += section + output += '\n' + + return output + +def get_capi_file_name(cppname): + """ Convert a C++ header file name to a C API header file name. """ + return cppname[:-2]+'_capi.h' + +def get_capi_name(cppname, isclassname, prefix = None): + """ Convert a C++ CamelCaps name to a C API underscore name. """ + result = '' + lastchr = '' + for chr in cppname: + # add an underscore if the current character is an upper case letter + # and the last character was a lower case letter + if len(result) > 0 and not chr.isdigit() \ + and string.upper(chr) == chr \ + and not string.upper(lastchr) == lastchr: + result += '_' + result += string.lower(chr) + lastchr = chr + + if isclassname: + result += '_t' + + if not prefix is None: + if prefix[0:3] == 'cef': + # if the prefix name is duplicated in the function name + # remove that portion of the function name + subprefix = prefix[3:] + pos = result.find(subprefix) + if pos >= 0: + result = result[0:pos]+ result[pos+len(subprefix):] + result = prefix+'_'+result + + return result + +def get_prev_line(body, pos): + """ Retrieve the start and end positions and value for the line immediately + before the line containing the specified position. + """ + end = string.rfind(body, '\n', 0, pos) + start = body.rfind('\n', 0, end)+1 + line = body[start:end] + return { 'start' : start, 'end' : end, 'line' : line } + +def get_comment(body, name): + """ Retrieve the comment for a class or function. """ + result = [] + + pos = body.find(name) + while pos > 0: + data = get_prev_line(body, pos) + line = string.strip(data['line']) + pos = data['start'] + if len(line) == 0: + # check if the next previous line is a comment + prevdata = get_prev_line(body, pos) + if string.strip(prevdata['line'])[0:2] == '//': + result.append(None) + else: + break + elif line[0:2] == '/*' or line[-2:] == '*/': + continue + elif line[0:2] == '//': + # keep the comment line including any leading spaces + result.append(line[2:]) + else: + break + + result.reverse() + return result + +def format_comment(comment, indent, translate_map = None, maxchars = 80): + """ Return the comments array as a formatted string. """ + result = '' + wrapme = '' + hasemptyline = False + for line in comment: + # if the line starts with a leading space, remove that space + if not line is None and len(line) > 0 and line[0:1] == ' ': + line = line[1:] + didremovespace = True + else: + didremovespace = False + + if line is None or len(line) == 0 or line[0:1] == ' ' \ + or line[0:1] == '/': + # the previous paragraph, if any, has ended + if len(wrapme) > 0: + if not translate_map is None: + # apply the translation + for key in translate_map.keys(): + wrapme = wrapme.replace(key, translate_map[key]) + # output the previous paragraph + result += wrap_text(wrapme, indent+'// ', maxchars) + wrapme = '' + + if not line is None: + if len(line) == 0 or line[0:1] == ' ' or line[0:1] == '/': + # blank lines or anything that's further indented should be + # output as-is + result += indent+'//' + if len(line) > 0: + if didremovespace: + result += ' '+line + else: + result += line + result += '\n' + else: + # add to the current paragraph + wrapme += line+' ' + else: + # output an empty line + hasemptyline = True + result += '\n' + + if len(wrapme) > 0: + if not translate_map is None: + # apply the translation + for key in translate_map.keys(): + wrapme = wrapme.replace(key, translate_map[key]) + # output the previous paragraph + result += wrap_text(wrapme, indent+'// ', maxchars) + + if hasemptyline: + # an empty line means a break between comments, so the comment is + # probably a section heading and should have an extra line before it + result = '\n' + result + return result + +def format_translation_changes(old, new): + """ Return a comment stating what is different between the old and new + function prototype parts. + """ + changed = False + result = '' + + # normalize C API attributes + oldargs = [x.replace('struct _', '') for x in old['args']] + oldretval = old['retval'].replace('struct _', '') + newargs = [x.replace('struct _', '') for x in new['args']] + newretval = new['retval'].replace('struct _', '') + + # check if the prototype has changed + oldset = set(oldargs) + newset = set(newargs) + if len(oldset.symmetric_difference(newset)) > 0: + changed = True + result += '\n // WARNING - CHANGED ATTRIBUTES' + + # in the implementation set only + oldonly = oldset.difference(newset) + for arg in oldonly: + result += '\n // REMOVED: '+arg + + # in the current set only + newonly = newset.difference(oldset) + for arg in newonly: + result += '\n // ADDED: '+arg + + # check if the return value has changed + if oldretval != newretval: + changed = True + result += '\n // WARNING - CHANGED RETURN VALUE'+ \ + '\n // WAS: '+old['retval']+ \ + '\n // NOW: '+new['retval'] + + if changed: + result += '\n #pragma message("Warning: "__FILE__": '+new['name']+ \ + ' prototype has changed")\n' + + return result + +def format_translation_includes(body): + """ Return the necessary list of includes based on the contents of the + body. + """ + result = '' + + # required for VS2013. + if body.find('std::min') > 0 or body.find('std::max') > 0: + result += '#include \n' + + if body.find('cef_api_hash(') > 0: + result += '#include "include/cef_version.h"\n' + + # identify what CppToC classes are being used + p = re.compile('([A-Za-z0-9_]{1,})CppToC') + list = sorted(set(p.findall(body))) + for item in list: + result += '#include "libcef_dll/cpptoc/'+ \ + get_capi_name(item[3:], False)+'_cpptoc.h"\n' + + # identify what CToCpp classes are being used + p = re.compile('([A-Za-z0-9_]{1,})CToCpp') + list = sorted(set(p.findall(body))) + for item in list: + result += '#include "libcef_dll/ctocpp/'+ \ + get_capi_name(item[3:], False)+'_ctocpp.h"\n' + + if body.find('transfer_') > 0: + result += '#include "libcef_dll/transfer_util.h"\n' + + return result + +def str_to_dict(str): + """ Convert a string to a dictionary. If the same key has multiple values + the values will be stored in a list. """ + dict = {} + parts = string.split(str, ',') + for part in parts: + part = string.strip(part) + if len(part) == 0: + continue + sparts = string.split(part, '=') + if len(sparts) > 2: + raise Exception('Invalid dictionary pair format: '+part) + name = string.strip(sparts[0]) + if len(sparts) == 2: + val = string.strip(sparts[1]) + else: + val = True + if name in dict: + # a value with this name already exists + curval = dict[name] + if not isinstance(curval, list): + # convert the string value to a list + dict[name] = [curval] + dict[name].append(val) + else: + dict[name] = val + return dict + +def dict_to_str(dict): + """ Convert a dictionary to a string. """ + str = [] + for name in dict.keys(): + if not isinstance(dict[name], list): + if dict[name] is True: + # currently a bool value + str.append(name) + else: + # currently a string value + str.append(name+'='+dict[name]) + else: + # currently a list value + for val in dict[name]: + str.append(name+'='+val) + return string.join(str, ',') + + +# regex for matching comment-formatted attributes +_cre_attrib = '/\*--cef\(([A-Za-z0-9_ ,=:\n]{0,})\)--\*/' +# regex for matching class and function names +_cre_cfname = '([A-Za-z0-9_]{1,})' +# regex for matching function return values +_cre_retval = '([A-Za-z0-9_<>:,\*\&]{1,})' +# regex for matching typedef value and name combination +_cre_typedef = '([A-Za-z0-9_<>:,\*\& ]{1,})' +# regex for matching function return value and name combination +_cre_func = '([A-Za-z][A-Za-z0-9_<>:,\*\& ]{1,})' +# regex for matching virtual function modifiers +_cre_vfmod = '([A-Za-z0-9_]{0,})' +# regex for matching arbitrary whitespace +_cre_space = '[\s]{1,}' + +# Simple translation types. Format is: +# 'cpp_type' : ['capi_type', 'capi_default_value'] +_simpletypes = { + 'void' : ['void', ''], + 'void*' : ['void*', 'NULL'], + 'int' : ['int', '0'], + 'int32' : ['int32', '0'], + 'uint32' : ['uint32', '0'], + 'int64' : ['int64', '0'], + 'uint64' : ['uint64', '0'], + 'double' : ['double', '0'], + 'float' : ['float', '0'], + 'long' : ['long', '0'], + 'unsigned long' : ['unsigned long', '0'], + 'long long' : ['long long', '0'], + 'size_t' : ['size_t', '0'], + 'time_t' : ['time_t', '0'], + 'bool' : ['int', '0'], + 'char': ['char', '0'], + 'char* const': ['char* const', 'NULL'], + 'CefCursorHandle' : ['cef_cursor_handle_t', 'kNullCursorHandle'], + 'CefEventHandle' : ['cef_event_handle_t', 'kNullEventHandle'], + 'CefWindowHandle' : ['cef_window_handle_t', 'kNullWindowHandle'], + 'CefTextInputContext' : ['cef_text_input_context_t' ,'NULL'], + 'CefPoint' : ['cef_point_t', 'CefPoint()'], + 'CefRect' : ['cef_rect_t', 'CefRect()'], + 'CefSize' : ['cef_size_t', 'CefSize()'], + 'CefPageRange' : ['cef_page_range_t', 'CefPageRange()'], + 'CefThreadId' : ['cef_thread_id_t', 'TID_UI'], + 'CefTime' : ['cef_time_t', 'CefTime()'], +} + +def get_function_impls(content, ident): + """ Retrieve the function parts from the specified contents as a set of + return value, name, arguments and body. Ident must occur somewhere in + the value. + """ + # extract the functions + p = re.compile('\n'+_cre_func+'\((.*?)\)([A-Za-z0-9_\s]{0,})'+ + '\{(.*?)\n\}', + re.MULTILINE | re.DOTALL) + list = p.findall(content) + + # build the function map with the function name as the key + result = [] + for retval, argval, vfmod, body in list: + if retval.find(ident) < 0: + # the identifier was not found + continue + + # remove the identifier + retval = string.replace(retval, ident, '') + retval = string.strip(retval) + + # retrieve the function name + parts = string.split(retval, ' ') + name = parts[-1] + del parts[-1] + retval = string.join(parts, ' ') + + # parse the arguments + args = [] + for v in string.split(argval, ','): + v = string.strip(v) + if len(v) > 0: + args.append(v) + + result.append({ + 'retval' : string.strip(retval), + 'name' : name, + 'args' : args, + 'vfmod' : string.strip(vfmod), + 'body' : body + }) + + return result + +def get_next_function_impl(existing, name): + result = None + for item in existing: + if item['name'] == name: + result = item + existing.remove(item) + break + return result + +def get_copyright(): + result = \ +"""// Copyright (c) $YEAR$ The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +""" + # add the copyright year + return result.replace('$YEAR$', get_year()) + + +class obj_header: + """ Class representing a C++ header file. """ + + def __init__(self): + self.filenames = [] + self.typedefs = [] + self.funcs = [] + self.classes = [] + + def add_directory(self, directory, excluded_files = []): + """ Add all header files from the specified directory. """ + files = get_files(os.path.join(directory, '*.h')) + for file in files: + if len(excluded_files) == 0 or \ + not os.path.split(file)[1] in excluded_files: + self.add_file(file) + + def add_file(self, filepath): + """ Add a header file. """ + + filename = os.path.split(filepath)[1] + added = False + + # read the input file into memory + data = read_file(filepath) + + # remove space from between template definition end brackets + data = data.replace("> >", ">>") + + # extract global typedefs + p = re.compile('\ntypedef'+_cre_space+_cre_typedef+';', + re.MULTILINE | re.DOTALL) + list = p.findall(data) + if len(list) > 0: + # build the global typedef objects + for value in list: + pos = value.rfind(' ') + if pos < 0: + raise Exception('Invalid typedef: '+value) + alias = value[pos+1:] + value = value[:pos] + self.typedefs.append(obj_typedef(self, filename, value, alias)) + + # extract global functions + p = re.compile('\n'+_cre_attrib+'\n'+_cre_func+'\((.*?)\)', + re.MULTILINE | re.DOTALL) + list = p.findall(data) + if len(list) > 0: + added = True + + # build the global function objects + for attrib, retval, argval in list: + comment = get_comment(data, retval+'('+argval+');') + self.funcs.append(obj_function(self, filename, attrib, retval, + argval, comment)) + + # extract includes + p = re.compile('\n#include \"include/'+_cre_cfname+'.h') + includes = p.findall(data) + + # extract forward declarations + p = re.compile('\nclass'+_cre_space+_cre_cfname+';') + forward_declares = p.findall(data) + + # extract classes + p = re.compile('\n'+_cre_attrib+ + '\nclass'+_cre_space+_cre_cfname+_cre_space+ + ':'+_cre_space+'public'+_cre_space+'virtual'+ + _cre_space+'CefBase'+_cre_space+ + '{(.*?)};', re.MULTILINE | re.DOTALL) + list = p.findall(data) + if len(list) > 0: + added = True + + # build the class objects + for attrib, name, body in list: + comment = get_comment(data, name+' : public virtual CefBase') + self.classes.append( + obj_class(self, filename, attrib, name, body, comment, + includes, forward_declares)) + + if added: + # a global function or class was read from the header file + self.filenames.append(filename) + + def __repr__(self): + result = '' + + if len(self.typedefs) > 0: + strlist = [] + for cls in self.typedefs: + strlist.append(str(cls)) + result += string.join(strlist, "\n") + "\n\n" + + if len(self.funcs) > 0: + strlist = [] + for cls in self.funcs: + strlist.append(str(cls)) + result += string.join(strlist, "\n") + "\n\n" + + if len(self.classes) > 0: + strlist = [] + for cls in self.classes: + strlist.append(str(cls)) + result += string.join(strlist, "\n") + + return result + + def get_file_names(self): + """ Return the array of header file names. """ + return self.filenames + + def get_typedefs(self): + """ Return the array of typedef objects. """ + return self.typedefs + + def get_funcs(self, filename = None): + """ Return the array of function objects. """ + if filename is None: + return self.funcs + else: + # only return the functions in the specified file + res = [] + for func in self.funcs: + if func.get_file_name() == filename: + res.append(func) + return res + + def get_classes(self, filename = None): + """ Return the array of class objects. """ + if filename is None: + return self.classes + else: + # only return the classes in the specified file + res = [] + for cls in self.classes: + if cls.get_file_name() == filename: + res.append(cls) + return res + + def get_class(self, classname, defined_structs = None): + """ Return the specified class or None if not found. """ + for cls in self.classes: + if cls.get_name() == classname: + return cls + elif not defined_structs is None: + defined_structs.append(cls.get_capi_name()) + return None + + def get_class_names(self): + """ Returns the names of all classes in this object. """ + result = [] + for cls in self.classes: + result.append(cls.get_name()) + return result + + def get_types(self, list): + """ Return a dictionary mapping data types to analyzed values. """ + for cls in self.typedefs: + cls.get_types(list) + + for cls in self.classes: + cls.get_types(list) + + def get_alias_translation(self, alias): + """ Return a translation of alias to value based on typedef + statements. """ + for cls in self.typedefs: + if cls.alias == alias: + return cls.value + return None + + def get_analysis(self, value, named = True): + """ Return an analysis of the value based the header file context. """ + return obj_analysis([self], value, named) + + def get_defined_structs(self): + """ Return a list of names already defined structure names. """ + return ['cef_print_info_t', 'cef_window_info_t', 'cef_base_t'] + + def get_capi_translations(self): + """ Return a dictionary that maps C++ terminology to C API terminology. + """ + # strings that will be changed in C++ comments + map = { + 'class' : 'structure', + 'Class' : 'Structure', + 'interface' : 'structure', + 'Interface' : 'Structure', + 'true' : 'true (1)', + 'false' : 'false (0)', + 'empty' : 'NULL', + 'method' : 'function' + } + + # add mappings for all classes and functions + funcs = self.get_funcs() + for func in funcs: + map[func.get_name()+'()'] = func.get_capi_name()+'()' + + classes = self.get_classes() + for cls in classes: + map[cls.get_name()] = cls.get_capi_name() + + funcs = cls.get_virtual_funcs() + for func in funcs: + map[func.get_name()+'()'] = func.get_capi_name()+'()' + + funcs = cls.get_static_funcs() + for func in funcs: + map[func.get_name()+'()'] = func.get_capi_name()+'()' + + return map + + +class obj_class: + """ Class representing a C++ class. """ + + def __init__(self, parent, filename, attrib, name, body, comment, + includes, forward_declares): + if not isinstance(parent, obj_header): + raise Exception('Invalid parent object type') + + self.parent = parent + self.filename = filename + self.attribs = str_to_dict(attrib) + self.name = name + self.comment = comment + self.includes = includes + self.forward_declares = forward_declares + + # extract typedefs + p = re.compile('\n'+_cre_space+'typedef'+_cre_space+_cre_typedef+';', + re.MULTILINE | re.DOTALL) + list = p.findall(body) + + # build the typedef objects + self.typedefs = [] + for value in list: + pos = value.rfind(' ') + if pos < 0: + raise Exception('Invalid typedef: '+value) + alias = value[pos+1:] + value = value[:pos] + self.typedefs.append(obj_typedef(self, filename, value, alias)) + + # extract static functions + p = re.compile('\n'+_cre_space+_cre_attrib+'\n'+_cre_space+'static'+ + _cre_space+_cre_func+'\((.*?)\)', + re.MULTILINE | re.DOTALL) + list = p.findall(body) + + # build the static function objects + self.staticfuncs = [] + for attrib, retval, argval in list: + comment = get_comment(body, retval+'('+argval+')') + self.staticfuncs.append( + obj_function_static(self, attrib, retval, argval, comment)) + + # extract virtual functions + p = re.compile('\n'+_cre_space+_cre_attrib+'\n'+_cre_space+'virtual'+ + _cre_space+_cre_func+'\((.*?)\)'+_cre_space+_cre_vfmod, + re.MULTILINE | re.DOTALL) + list = p.findall(body) + + # build the virtual function objects + self.virtualfuncs = [] + for attrib, retval, argval, vfmod in list: + comment = get_comment(body, retval+'('+argval+')') + self.virtualfuncs.append( + obj_function_virtual(self, attrib, retval, argval, comment, + vfmod)) + + def __repr__(self): + result = '/* '+dict_to_str(self.attribs)+' */ class '+self.name+"\n{" + + if len(self.typedefs) > 0: + result += "\n\t" + strlist = [] + for cls in self.typedefs: + strlist.append(str(cls)) + result += string.join(strlist, "\n\t") + + if len(self.staticfuncs) > 0: + result += "\n\t" + strlist = [] + for cls in self.staticfuncs: + strlist.append(str(cls)) + result += string.join(strlist, "\n\t") + + if len(self.virtualfuncs) > 0: + result += "\n\t" + strlist = [] + for cls in self.virtualfuncs: + strlist.append(str(cls)) + result += string.join(strlist, "\n\t") + + result += "\n};\n" + return result + + def get_file_name(self): + """ Return the C++ header file name. """ + return self.filename + + def get_capi_file_name(self): + """ Return the CAPI header file name. """ + return get_capi_file_name(self.filename) + + def get_name(self): + """ Return the class name. """ + return self.name + + def get_capi_name(self): + """ Return the CAPI structure name for this class. """ + return get_capi_name(self.name, True) + + def get_comment(self): + """ Return the class comment as an array of lines. """ + return self.comment + + def get_includes(self): + """ Return the list of classes that are included from this class' + header file. """ + return self.includes + + def get_forward_declares(self): + """ Return the list of classes that are forward declared for this + class. """ + return self.forward_declares + + def get_attribs(self): + """ Return all attributes as a dictionary. """ + return self.attribs + + def has_attrib(self, name): + """ Return true if the specified attribute exists. """ + return name in self.attribs + + def get_attrib(self, name): + """ Return the first or only value for specified attribute. """ + if name in self.attribs: + if isinstance(self.attribs[name], list): + # the value is a list + return self.attribs[name][0] + else: + # the value is a string + return self.attribs[name] + return None + + def get_attrib_list(self, name): + """ Return all values for specified attribute as a list. """ + if name in self.attribs: + if isinstance(self.attribs[name], list): + # the value is already a list + return self.attribs[name] + else: + # convert the value to a list + return [self.attribs[name]] + return None + + def get_typedefs(self): + """ Return the array of typedef objects. """ + return self.typedefs + + def has_typedef_alias(self, alias): + """ Returns true if the specified typedef alias is defined in the scope + of this class declaration. """ + for typedef in self.typedefs: + if typedef.get_alias() == alias: + return True + return False + + def get_static_funcs(self): + """ Return the array of static function objects. """ + return self.staticfuncs + + def get_virtual_funcs(self): + """ Return the array of virtual function objects. """ + return self.virtualfuncs + + def get_types(self, list): + """ Return a dictionary mapping data types to analyzed values. """ + for cls in self.typedefs: + cls.get_types(list) + + for cls in self.staticfuncs: + cls.get_types(list) + + for cls in self.virtualfuncs: + cls.get_types(list) + + def get_alias_translation(self, alias): + for cls in self.typedefs: + if cls.alias == alias: + return cls.value + return None + + def get_analysis(self, value, named = True): + """ Return an analysis of the value based on the class definition + context. + """ + return obj_analysis([self, self.parent], value, named) + + def is_library_side(self): + """ Returns true if the class is implemented by the library. """ + return self.attribs['source'] == 'library' + + def is_client_side(self): + """ Returns true if the class is implemented by the client. """ + return self.attribs['source'] == 'client' + + +class obj_typedef: + """ Class representing a typedef statement. """ + + def __init__(self, parent, filename, value, alias): + if not isinstance(parent, obj_header) \ + and not isinstance(parent, obj_class): + raise Exception('Invalid parent object type') + + self.parent = parent + self.filename = filename + self.alias = alias + self.value = self.parent.get_analysis(value, False) + + def __repr__(self): + return 'typedef '+self.value.get_type()+' '+self.alias+';' + + def get_file_name(self): + """ Return the C++ header file name. """ + return self.filename + + def get_capi_file_name(self): + """ Return the CAPI header file name. """ + return get_capi_file_name(self.filename) + + def get_alias(self): + """ Return the alias. """ + return self.alias + + def get_value(self): + """ Return an analysis of the value based on the class or header file + definition context. + """ + return self.value + + def get_types(self, list): + """ Return a dictionary mapping data types to analyzed values. """ + name = self.value.get_type() + if not name in list: + list[name] = self.value + + +class obj_function: + """ Class representing a function. """ + + def __init__(self, parent, filename, attrib, retval, argval, comment): + self.parent = parent + self.filename = filename + self.attribs = str_to_dict(attrib) + self.retval = obj_argument(self, retval) + self.name = self.retval.remove_name() + self.comment = comment + + # build the argument objects + self.arguments = [] + arglist = string.split(argval, ',') + for arg in arglist: + arg = string.strip(arg) + if len(arg) > 0: + argument = obj_argument(self, arg) + if argument.needs_attrib_count_func() and \ + argument.get_attrib_count_func() is None: + raise Exception("A 'count_func' attribute is required "+ \ + "for the '"+argument.get_name()+ \ + "' parameter to "+self.get_qualified_name()) + self.arguments.append(argument) + + if self.retval.needs_attrib_default_retval() and \ + self.retval.get_attrib_default_retval() is None: + raise Exception("A 'default_retval' attribute is required for "+ \ + self.get_qualified_name()) + + def __repr__(self): + return '/* '+dict_to_str(self.attribs)+' */ '+self.get_cpp_proto() + + def get_file_name(self): + """ Return the C++ header file name. """ + return self.filename + + def get_capi_file_name(self): + """ Return the CAPI header file name. """ + return get_capi_file_name(self.filename) + + def get_name(self): + """ Return the function name. """ + return self.name + + def get_qualified_name(self): + """ Return the fully qualified function name. """ + if isinstance(self.parent, obj_header): + # global function + return self.name + else: + # member function + return self.parent.get_name()+'::'+self.name + + def get_capi_name(self, prefix = None): + """ Return the CAPI function name. """ + if 'capi_name' in self.attribs: + return self.attribs['capi_name'] + return get_capi_name(self.name, False, prefix) + + def get_comment(self): + """ Return the function comment as an array of lines. """ + return self.comment + + def get_attribs(self): + """ Return all attributes as a dictionary. """ + return self.attribs + + def has_attrib(self, name): + """ Return true if the specified attribute exists. """ + return name in self.attribs + + def get_attrib(self, name): + """ Return the first or only value for specified attribute. """ + if name in self.attribs: + if isinstance(self.attribs[name], list): + # the value is a list + return self.attribs[name][0] + else: + # the value is a string + return self.attribs[name] + return None + + def get_attrib_list(self, name): + """ Return all values for specified attribute as a list. """ + if name in self.attribs: + if isinstance(self.attribs[name], list): + # the value is already a list + return self.attribs[name] + else: + # convert the value to a list + return [self.attribs[name]] + return None + + def get_retval(self): + """ Return the return value object. """ + return self.retval + + def get_arguments(self): + """ Return the argument array. """ + return self.arguments + + def get_types(self, list): + """ Return a dictionary mapping data types to analyzed values. """ + for cls in self.arguments: + cls.get_types(list) + + def get_capi_parts(self, defined_structs = [], prefix = None): + """ Return the parts of the C API function definition. """ + retval = '' + dict = self.retval.get_type().get_capi(defined_structs) + if dict['format'] == 'single': + retval = dict['value'] + + name = self.get_capi_name(prefix) + args = [] + + if isinstance(self, obj_function_virtual): + # virtual functions get themselves as the first argument + str = 'struct _'+self.parent.get_capi_name()+'* self' + if isinstance(self, obj_function_virtual) and self.is_const(): + # const virtual functions get const self pointers + str = 'const '+str + args.append(str) + + if len(self.arguments) > 0: + for cls in self.arguments: + type = cls.get_type() + dict = type.get_capi(defined_structs) + if dict['format'] == 'single': + args.append(dict['value']) + elif dict['format'] == 'multi-arg': + # add an additional argument for the size of the array + type_name = type.get_name() + if type.is_const(): + # for const arrays pass the size argument by value + args.append('size_t '+type_name+'Count') + else: + # for non-const arrays pass the size argument by address + args.append('size_t* '+type_name+'Count') + args.append(dict['value']) + + return { 'retval' : retval, 'name' : name, 'args' : args } + + def get_capi_proto(self, defined_structs = [], prefix = None): + """ Return the prototype of the C API function. """ + parts = self.get_capi_parts(defined_structs, prefix) + result = parts['retval']+' '+parts['name']+ \ + '('+string.join(parts['args'], ', ')+')' + return result + + def get_cpp_parts(self, isimpl = False): + """ Return the parts of the C++ function definition. """ + retval = str(self.retval) + name = self.name + + args = [] + if len(self.arguments) > 0: + for cls in self.arguments: + args.append(str(cls)) + + if isimpl and isinstance(self, obj_function_virtual): + # enumeration return values must be qualified with the class name + # if the type is defined in the class declaration scope. + type = self.get_retval().get_type() + if type.is_result_struct() and type.is_result_struct_enum() and \ + self.parent.has_typedef_alias(retval): + retval = self.parent.get_name()+'::'+retval + + return { 'retval' : retval, 'name' : name, 'args' : args } + + def get_cpp_proto(self, classname = None): + """ Return the prototype of the C++ function. """ + parts = self.get_cpp_parts() + result = parts['retval']+' ' + if not classname is None: + result += classname+'::' + result += parts['name']+'('+string.join(parts['args'], ', ')+')' + if isinstance(self, obj_function_virtual) and self.is_const(): + result += ' const' + return result + + def is_same_side(self, other_class_name): + """ Returns true if this function is on the same side (library or + client) and the specified class. """ + if isinstance(self.parent, obj_class): + # this function is part of a class + this_is_library_side = self.parent.is_library_side() + header = self.parent.parent + else: + # this function is global + this_is_library_side = True + header = self.parent + + if other_class_name == 'CefBase': + other_is_library_side = False + else: + other_class = header.get_class(other_class_name) + if other_class is None: + raise Exception('Unknown class: '+other_class_name) + other_is_library_side = other_class.is_library_side() + + return other_is_library_side == this_is_library_side + + +class obj_function_static(obj_function): + """ Class representing a static function. """ + + def __init__(self, parent, attrib, retval, argval, comment): + if not isinstance(parent, obj_class): + raise Exception('Invalid parent object type') + obj_function.__init__(self, parent, parent.filename, attrib, retval, + argval, comment) + + def __repr__(self): + return 'static '+obj_function.__repr__(self)+';' + + def get_capi_name(self, prefix = None): + """ Return the CAPI function name. """ + if prefix is None: + # by default static functions are prefixed with the class name + prefix = get_capi_name(self.parent.get_name(), False) + return obj_function.get_capi_name(self, prefix) + +class obj_function_virtual(obj_function): + """ Class representing a virtual function. """ + + def __init__(self, parent, attrib, retval, argval, comment, vfmod): + if not isinstance(parent, obj_class): + raise Exception('Invalid parent object type') + obj_function.__init__(self, parent, parent.filename, attrib, retval, + argval, comment) + if vfmod == 'const': + self.isconst = True + else: + self.isconst = False + + def __repr__(self): + return 'virtual '+obj_function.__repr__(self)+';' + + def is_const(self): + """ Returns true if the method declaration is const. """ + return self.isconst + + +class obj_argument: + """ Class representing a function argument. """ + + def __init__(self, parent, argval): + if not isinstance(parent, obj_function): + raise Exception('Invalid parent object type') + + self.parent = parent + self.type = self.parent.parent.get_analysis(argval) + + def __repr__(self): + result = '' + if self.type.is_const(): + result += 'const ' + result += self.type.get_type() + if self.type.is_byref(): + result += '&' + elif self.type.is_byaddr(): + result += '*' + if self.type.has_name(): + result += ' '+self.type.get_name() + return result + + def get_name(self): + """ Return the name for this argument. """ + return self.type.get_name() + + def remove_name(self): + """ Remove and return the name value. """ + name = self.type.get_name() + self.type.name = None + return name + + def get_type(self): + """ Return an analysis of the argument type based on the class + definition context. + """ + return self.type + + def get_types(self, list): + """ Return a dictionary mapping data types to analyzed values. """ + name = self.type.get_type() + if not name in list: + list[name] = self.type + + def needs_attrib_count_func(self): + """ Returns true if this argument requires a 'count_func' attribute. """ + # A 'count_func' attribute is required for non-const non-string vector + # attribute types + return self.type.has_name() and \ + self.type.is_result_vector() and \ + not self.type.is_result_vector_string() and \ + not self.type.is_const() + + def get_attrib_count_func(self): + """ Returns the count function for this argument. """ + # The 'count_func' attribute value format is name:function + if not self.parent.has_attrib('count_func'): + return None + name = self.type.get_name() + vals = self.parent.get_attrib_list('count_func') + for val in vals: + parts = string.split(val, ':') + if len(parts) != 2: + raise Exception("Invalid 'count_func' attribute value for "+ \ + self.parent.get_qualified_name()+': '+val) + if string.strip(parts[0]) == name: + return string.strip(parts[1]) + return None + + def needs_attrib_default_retval(self): + """ Returns true if this argument requires a 'default_retval' attribute. + """ + # A 'default_retval' attribute is required for enumeration return value + # types. + return not self.type.has_name() and \ + self.type.is_result_struct() and \ + self.type.is_result_struct_enum() + + def get_attrib_default_retval(self): + """ Returns the defualt return value for this argument. """ + return self.parent.get_attrib('default_retval') + + def get_arg_type(self): + """ Returns the argument type as defined in translator.README.txt. """ + if not self.type.has_name(): + raise Exception('Cannot be called for retval types') + + # simple or enumeration type + if (self.type.is_result_simple() and \ + self.type.get_type() != 'bool') or \ + (self.type.is_result_struct() and \ + self.type.is_result_struct_enum()): + if self.type.is_byref(): + if self.type.is_const(): + return 'simple_byref_const' + return 'simple_byref' + elif self.type.is_byaddr(): + return 'simple_byaddr' + return 'simple_byval' + + # boolean type + if self.type.get_type() == 'bool': + if self.type.is_byref(): + return 'bool_byref' + elif self.type.is_byaddr(): + return 'bool_byaddr' + return 'bool_byval' + + # structure type + if self.type.is_result_struct() and self.type.is_byref(): + if self.type.is_const(): + return 'struct_byref_const' + return 'struct_byref' + + # string type + if self.type.is_result_string() and self.type.is_byref(): + if self.type.is_const(): + return 'string_byref_const' + return 'string_byref' + + # refptr type + if self.type.is_result_refptr(): + same_side = self.parent.is_same_side(self.type.get_refptr_type()) + if self.type.is_byref(): + if same_side: + return 'refptr_same_byref' + return 'refptr_diff_byref' + if same_side: + return 'refptr_same' + return 'refptr_diff' + + + if self.type.is_result_vector(): + # all vector types must be passed by reference + if not self.type.is_byref(): + return 'invalid' + + if self.type.is_result_vector_string(): + # string vector type + if self.type.is_const(): + return 'string_vec_byref_const' + return 'string_vec_byref' + + if self.type.is_result_vector_simple(): + if self.type.get_vector_type() != 'bool': + # simple/enumeration vector types + if self.type.is_const(): + return 'simple_vec_byref_const' + return 'simple_vec_byref' + + # boolean vector types + if self.type.is_const(): + return 'bool_vec_byref_const' + return 'bool_vec_byref' + + if self.type.is_result_vector_refptr(): + # refptr vector types + same_side = self.parent.is_same_side(self.type.get_refptr_type()) + if self.type.is_const(): + if same_side: + return 'refptr_vec_same_byref_const' + return 'refptr_vec_diff_byref_const' + if same_side: + return 'refptr_vec_same_byref' + return 'refptr_vec_diff_byref' + + + # string single map type + if self.type.is_result_map_single(): + if not self.type.is_byref(): + return 'invalid' + if self.type.is_const(): + return 'string_map_single_byref_const' + return 'string_map_single_byref' + + # string multi map type + if self.type.is_result_map_multi(): + if not self.type.is_byref(): + return 'invalid' + if self.type.is_const(): + return 'string_map_multi_byref_const' + return 'string_map_multi_byref' + + return 'invalid' + + def get_retval_type(self): + """ Returns the retval type as defined in translator.README.txt. """ + if self.type.has_name(): + raise Exception('Cannot be called for argument types') + + # unsupported modifiers + if self.type.is_const() or self.type.is_byref() or \ + self.type.is_byaddr(): + return 'invalid' + + # void types don't have a return value + if self.type.get_type() == 'void': + return 'none' + + if (self.type.is_result_simple() and \ + self.type.get_type() != 'bool') or \ + (self.type.is_result_struct() and self.type.is_result_struct_enum()): + return 'simple' + + if self.type.get_type() == 'bool': + return 'bool' + + if self.type.is_result_string(): + return 'string' + + if self.type.is_result_refptr(): + if self.parent.is_same_side(self.type.get_refptr_type()): + return 'refptr_same' + else: + return 'refptr_diff' + + return 'invalid' + + def get_retval_default(self, for_capi): + """ Returns the default return value based on the retval type. """ + # start with the default retval attribute, if any. + retval = self.get_attrib_default_retval() + if not retval is None: + if for_capi: + # apply any appropriate C API translations. + if retval == 'true': + return '1' + if retval == 'false': + return '0' + return retval + + # next look at the retval type value. + type = self.get_retval_type() + if type == 'simple': + return self.get_type().get_result_simple_default() + elif type == 'bool': + if for_capi: + return '0' + return 'false' + elif type == 'string': + if for_capi: + return 'NULL' + return 'CefString()' + elif type == 'refptr_same' or type == 'refptr_diff': + return 'NULL' + + return '' + +class obj_analysis: + """ Class representing an analysis of a data type value. """ + + def __init__(self, scopelist, value, named): + self.value = value + self.result_type = 'unknown' + self.result_value = None + self.result_default = None + self.refptr_type = None + + # parse the argument string + partlist = string.split(string.strip(value)) + + if named == True: + # extract the name value + self.name = partlist[-1] + del partlist[-1] + else: + self.name = None + + if len(partlist) == 0: + raise Exception('Invalid argument value: '+value) + + # check const status + if partlist[0] == 'const': + self.isconst = True + del partlist[0] + else: + self.isconst = False + + # combine the data type + self.type = string.join(partlist, ' ') + + # extract the last character of the data type + endchar = self.type[-1] + + # check if the value is passed by reference + if endchar == '&': + self.isbyref = True + self.type = self.type[:-1] + else: + self.isbyref = False + + # check if the value is passed by address + if endchar == '*': + self.isbyaddr = True + self.type = self.type[:-1] + else: + self.isbyaddr = False + + # see if the value is directly identifiable + if self._check_advanced(self.type) == True: + return + + # not identifiable, so look it up + translation = None + for scope in scopelist: + if not isinstance(scope, obj_header) \ + and not isinstance(scope, obj_class): + raise Exception('Invalid scope object type') + translation = scope.get_alias_translation(self.type) + if not translation is None: + break + + if translation is None: + raise Exception('Failed to translate type: '+self.type) + + # the translation succeeded so keep the result + self.result_type = translation.result_type + self.result_value = translation.result_value + + def _check_advanced(self, value): + # check for vectors + if value.find('std::vector') == 0: + self.result_type = 'vector' + val = string.strip(value[12:-1]) + self.result_value = [ + self._get_basic(val) + ] + self.result_value[0]['vector_type'] = val + return True + + # check for maps + if value.find('std::map') == 0: + self.result_type = 'map' + vals = string.split(value[9:-1], ',') + if len(vals) == 2: + self.result_value = [ + self._get_basic(string.strip(vals[0])), + self._get_basic(string.strip(vals[1])) + ] + return True + + # check for multimaps + if value.find('std::multimap') == 0: + self.result_type = 'multimap' + vals = string.split(value[14:-1], ',') + if len(vals) == 2: + self.result_value = [ + self._get_basic(string.strip(vals[0])), + self._get_basic(string.strip(vals[1])) + ] + return True + + # check for basic types + basic = self._get_basic(value) + if not basic is None: + self.result_type = basic['result_type'] + self.result_value = basic['result_value'] + if 'refptr_type' in basic: + self.refptr_type = basic['refptr_type'] + if 'result_default' in basic: + self.result_default = basic['result_default'] + return True + + return False + + def _get_basic(self, value): + # check for string values + if value == "CefString": + return { + 'result_type' : 'string', + 'result_value' : None + } + + # check for simple direct translations + if value in _simpletypes.keys(): + return { + 'result_type' : 'simple', + 'result_value' : _simpletypes[value][0], + 'result_default' : _simpletypes[value][1], + } + + # check if already a C API structure + if value[-2:] == '_t': + return { + 'result_type' : 'structure', + 'result_value' : value + } + + # check for CEF reference pointers + p = re.compile('^CefRefPtr<(.*?)>$', re.DOTALL) + list = p.findall(value) + if len(list) == 1: + return { + 'result_type' : 'refptr', + 'result_value' : get_capi_name(list[0], True)+'*', + 'refptr_type' : list[0] + } + + # check for CEF structure types + if value[0:3] == 'Cef' and value[-4:] != 'List': + return { + 'result_type' : 'structure', + 'result_value' : get_capi_name(value, True) + } + + return None + + def __repr__(self): + return '('+self.result_type+') '+str(self.result_value) + + def has_name(self): + """ Returns true if a name value exists. """ + return (not self.name is None) + + def get_name(self): + """ Return the name. """ + return self.name + + def get_value(self): + """ Return the C++ value (type + name). """ + return self.value + + def get_type(self): + """ Return the C++ type. """ + return self.type + + def get_refptr_type(self): + """ Return the C++ class type referenced by a CefRefPtr. """ + if self.is_result_vector() and self.is_result_vector_refptr(): + # return the vector RefPtr type + return self.result_value[0]['refptr_type'] + # return the basic RefPtr type + return self.refptr_type + + def get_vector_type(self): + """ Return the C++ class type referenced by a std::vector. """ + if self.is_result_vector(): + return self.result_value[0]['vector_type'] + return None + + def is_const(self): + """ Returns true if the argument value is constant. """ + return self.isconst + + def is_byref(self): + """ Returns true if the argument is passed by reference. """ + return self.isbyref + + def is_byaddr(self): + """ Returns true if the argument is passed by address. """ + return self.isbyaddr + + def is_result_simple(self): + """ Returns true if this is a simple argument type. """ + return (self.result_type == 'simple') + + def get_result_simple_type_root(self): + """ Return the simple structure or basic type name. """ + return self.result_value + + def get_result_simple_type(self): + """ Return the simple type. """ + result = '' + if self.is_const(): + result += 'const ' + result += self.result_value + if self.is_byaddr() or self.is_byref(): + result += '*' + return result + + def get_result_simple_default(self): + """ Return the default value fo the basic type. """ + return self.result_default + + def is_result_refptr(self): + """ Returns true if this is a reference pointer type. """ + return (self.result_type == 'refptr') + + def get_result_refptr_type_root(self): + """ Return the refptr type structure name. """ + return self.result_value[:-1] + + def get_result_refptr_type(self, defined_structs = []): + """ Return the refptr type. """ + result = '' + if not self.result_value[:-1] in defined_structs: + result += 'struct _' + result += self.result_value + if self.is_byref() or self.is_byaddr(): + result += '*' + return result + + def is_result_struct(self): + """ Returns true if this is a structure type. """ + return (self.result_type == 'structure') + + def is_result_struct_enum(self): + """ Returns true if this struct type is likely an enumeration. """ + # structure values that are passed by reference or address must be + # structures and not enumerations + if not self.is_byref() and not self.is_byaddr(): + return True + return False + + def get_result_struct_type(self, defined_structs = []): + """ Return the structure or enumeration type. """ + result = '' + is_enum = self.is_result_struct_enum() + if not is_enum: + if self.is_const(): + result += 'const ' + if not self.result_value in defined_structs: + result += 'struct _' + result += self.result_value + if not is_enum: + result += '*' + return result + + def is_result_string(self): + """ Returns true if this is a string type. """ + return (self.result_type == 'string') + + def get_result_string_type(self): + """ Return the string type. """ + if not self.has_name(): + # Return values are string structs that the user must free. Use + # the name of the structure as a hint. + return 'cef_string_userfree_t' + elif not self.is_const() and (self.is_byref() or self.is_byaddr()): + # Parameters passed by reference or address. Use the normal + # non-const string struct. + return 'cef_string_t*' + # Const parameters use the const string struct. + return 'const cef_string_t*' + + def is_result_vector(self): + """ Returns true if this is a vector type. """ + return (self.result_type == 'vector') + + def is_result_vector_string(self): + """ Returns true if this is a string vector. """ + return self.result_value[0]['result_type'] == 'string' + + def is_result_vector_simple(self): + """ Returns true if this is a string vector. """ + return self.result_value[0]['result_type'] == 'simple' + + def is_result_vector_refptr(self): + """ Returns true if this is a string vector. """ + return self.result_value[0]['result_type'] == 'refptr' + + def get_result_vector_type_root(self): + """ Return the vector structure or basic type name. """ + return self.result_value[0]['result_value'] + + def get_result_vector_type(self, defined_structs = []): + """ Return the vector type. """ + if not self.has_name(): + raise Exception('Cannot use vector as a return type') + + type = self.result_value[0]['result_type'] + value = self.result_value[0]['result_value'] + + result = {} + if type == 'string': + result['value'] = 'cef_string_list_t' + result['format'] = 'single' + return result + + if type == 'simple': + str = value + if self.is_const(): + str += ' const' + str += '*' + result['value'] = str + elif type == 'refptr': + str = '' + if not value[:-1] in defined_structs: + str += 'struct _' + str += value + if self.is_const(): + str += ' const' + str += '*' + result['value'] = str + else: + raise Exception('Unsupported vector type: '+type) + + # vector values must be passed as a value array parameter + # and a size parameter + result['format'] = 'multi-arg' + return result + + def is_result_map(self): + """ Returns true if this is a map type. """ + return (self.result_type == 'map' or self.result_type == 'multimap') + + def is_result_map_single(self): + """ Returns true if this is a single map type. """ + return (self.result_type == 'map') + + def is_result_map_multi(self): + """ Returns true if this is a multi map type. """ + return (self.result_type == 'multimap') + + def get_result_map_type(self, defined_structs = []): + """ Return the map type. """ + if not self.has_name(): + raise Exception('Cannot use map as a return type') + if self.result_value[0]['result_type'] == 'string' \ + and self.result_value[1]['result_type'] == 'string': + if self.result_type == 'map': + return { + 'value' : 'cef_string_map_t', + 'format' : 'single' + } + elif self.result_type == 'multimap': + return { + 'value' : 'cef_string_multimap_t', + 'format' : 'multi' + } + raise Exception('Only mappings of strings to strings are supported') + + def get_capi(self, defined_structs = []): + """ Format the value for the C API. """ + result = '' + format = 'single' + if self.is_result_simple(): + result += self.get_result_simple_type() + elif self.is_result_refptr(): + result += self.get_result_refptr_type(defined_structs) + elif self.is_result_struct(): + result += self.get_result_struct_type(defined_structs) + elif self.is_result_string(): + result += self.get_result_string_type() + elif self.is_result_map(): + resdict = self.get_result_map_type(defined_structs) + if resdict['format'] == 'single' or resdict['format'] == 'multi': + result += resdict['value'] + else: + raise Exception('Unsupported map type') + elif self.is_result_vector(): + resdict = self.get_result_vector_type(defined_structs) + if resdict['format'] != 'single': + format = resdict['format'] + result += resdict['value'] + + if self.has_name(): + result += ' '+self.get_name() + + return {'format' : format, 'value' : result} + + +# test the module +if __name__ == "__main__": + import pprint + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) != 2: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + pp = pprint.PrettyPrinter(indent=4) + + # create the header object + header = obj_header() + header.add_directory(sys.argv[1]) + + # output the type mapping + types = {} + header.get_types(types) + pp.pprint(types) + sys.stdout.write('\n') + + # output the parsed C++ data + sys.stdout.write(wrap_code(str(header), '\t')) + + # output the C API formatted data + defined_names = header.get_defined_structs() + result = '' + + # global functions + funcs = header.get_funcs() + if len(funcs) > 0: + for func in funcs: + result += func.get_capi_proto(defined_names)+';\n' + result += '\n' + + classes = header.get_classes() + for cls in classes: + # virtual functions are inside a structure + result += 'struct '+cls.get_capi_name()+'\n{\n' + funcs = cls.get_virtual_funcs() + if len(funcs) > 0: + for func in funcs: + result += '\t'+func.get_capi_proto(defined_names)+';\n' + result += '}\n\n' + + defined_names.append(cls.get_capi_name()) + + # static functions become global + funcs = cls.get_static_funcs() + if len(funcs) > 0: + for func in funcs: + result += func.get_capi_proto(defined_names)+';\n' + result += '\n' + sys.stdout.write(wrap_code(result, '\t')) diff --git a/tools/check_style.bat b/tools/check_style.bat new file mode 100644 index 000000000..8bd86b20c --- /dev/null +++ b/tools/check_style.bat @@ -0,0 +1,2 @@ +@echo off +python.bat check_style.py %* diff --git a/tools/check_style.py b/tools/check_style.py new file mode 100644 index 000000000..d734e76fb --- /dev/null +++ b/tools/check_style.py @@ -0,0 +1,129 @@ +# Copyright (c) 2012 The Chromium Embedded Framework Authors. +# Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import os, re, string, sys +from file_util import * +import git_util as git +import svn_util as svn + +# script directory +script_dir = os.path.dirname(__file__) + +# CEF root directory +cef_dir = os.path.abspath(os.path.join(script_dir, os.pardir)) + +# Valid extensions for files we want to lint. +DEFAULT_LINT_WHITELIST_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)" +DEFAULT_LINT_BLACKLIST_REGEX = r"$^" + +try: + # depot_tools may already be in the import path. + import cpplint + import cpplint_chromium +except ImportError, e: + # Search the PATH environment variable to find the depot_tools folder. + depot_tools = None; + paths = os.environ.get('PATH').split(os.pathsep) + for path in paths: + if os.path.exists(os.path.join(path, 'cpplint_chromium.py')): + depot_tools = path + break + + if depot_tools is None: + print >> sys.stderr, 'Error: could not find depot_tools in PATH.' + sys.exit(2) + + # Add depot_tools to import path. + sys.path.append(depot_tools) + import cpplint + import cpplint_chromium + +# The default implementation of FileInfo.RepositoryName looks for the top-most +# directory that contains a .git or .svn folder. This is a problem for CEF +# because the CEF root folder (which may have an arbitrary name) lives inside +# the Chromium src folder. Reimplement in a dumb but sane way. +def patch_RepositoryName(self): + fullname = self.FullName() + project_dir = os.path.dirname(fullname) + if os.path.exists(fullname): + root_dir = project_dir + while os.path.basename(project_dir) != "src": + project_dir = os.path.dirname(project_dir) + prefix = os.path.commonprefix([root_dir, project_dir]) + components = fullname[len(prefix) + 1:].split('/') + return string.join(["cef"] + components[1:], '/') + return fullname + +def check_style(args, white_list = None, black_list = None): + """ Execute cpplint with the specified arguments. """ + + # Apply patches. + cpplint.FileInfo.RepositoryName = patch_RepositoryName + + # Process cpplint arguments. + filenames = cpplint.ParseArguments(args) + + if not white_list: + white_list = DEFAULT_LINT_WHITELIST_REGEX + white_regex = re.compile(white_list) + if not black_list: + black_list = DEFAULT_LINT_BLACKLIST_REGEX + black_regex = re.compile(black_list) + + extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace] + + for filename in filenames: + if white_regex.match(filename): + if black_regex.match(filename): + print "Ignoring file %s" % filename + else: + cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level, + extra_check_functions) + else: + print "Skipping file %s" % filename + + print "Total errors found: %d\n" % cpplint._cpplint_state.error_count + return 1 + +def get_changed_files(): + """ Retrieve the list of changed files. """ + try: + return svn.get_changed_files(cef_dir) + except: + return git.get_changed_files(cef_dir) + +if __name__ == "__main__": + # Start with the default parameters. + args = [ + # * Disable the 'build/class' test because it errors uselessly with C + # structure pointers and template declarations. + # * Disable the 'runtime/references' test because CEF allows non-const + # arguments passed by reference. + # * Disable the 'runtime/sizeof' test because it has a high number of + # false positives and adds marginal value. + '--filter=-build/class,-runtime/references,-runtime/sizeof', + ] + + # Add anything passed on the command-line. + args += sys.argv[1:] + + # Pre-process the arguments before passing to the linter. + new_args = [] + changed = [] + for arg in args: + if arg == '--changed': + # Add any changed files. + changed = get_changed_files() + elif arg[:2] == '--' or not os.path.isdir(arg): + # Pass argument unchanged. + new_args.append(arg) + else: + # Add all files in the directory. + new_args += get_files(os.path.join(arg, '*')) + + if len(changed) > 0: + new_args += changed + + check_style(new_args) diff --git a/tools/check_style.sh b/tools/check_style.sh new file mode 100755 index 000000000..3a38a6ab7 --- /dev/null +++ b/tools/check_style.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python check_style.py $@ diff --git a/tools/combine_libs.py b/tools/combine_libs.py new file mode 100644 index 000000000..8e78efa87 --- /dev/null +++ b/tools/combine_libs.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +# TODO(slightlyoff): move to using shared version of this script. + +'''This script makes it easy to combine libs and object files to a new lib, +optionally removing some of the object files in the input libs by regular +expression matching. +For usage information, run the script with a --help argument. +''' +import optparse +import os +import re +import subprocess +import sys + + +def Shell(*args): + '''Runs the program and args in args, returns the output from the program.''' + process = subprocess.Popen(args, + stdin = None, + stdout = subprocess.PIPE, + stderr = subprocess.STDOUT) + output = process.stdout.readlines() + process.wait() + retcode = process.returncode + if retcode != 0: + raise RuntimeError('%s exited with status %d' % (args[0], retcode)) + return output + + +def CollectRemovals(remove_re, inputs): + '''Returns a list of all object files in inputs that match remove_re.''' + removals = [] + for input in inputs: + output = Shell('lib.exe', '/list', input) + + for line in output: + line = line.rstrip() + if remove_re.search(line): + removals.append(line) + + return removals + + +def CombineLibraries(output, remove_re, inputs): + '''Combines all the libraries and objects in inputs, while removing any + object files that match remove_re. + ''' + removals = [] + if remove_re: + removals = CollectRemovals(remove_re, inputs) + + if len(removals) > 0: + print 'Removals: ', removals + + args = ['lib.exe', '/out:%s' % output] + args += ['/remove:%s' % obj for obj in removals] + args += inputs + Shell(*args) + + +USAGE = '''usage: %prog [options] + + +Combines input libraries or objects into an output library, while removing +any object file (in the input libraries) that matches a given regular +expression. +''' + +def GetOptionParser(): + parser = optparse.OptionParser(USAGE) + parser.add_option('-o', '--output', dest = 'output', + help = 'write to this output library') + parser.add_option('-r', '--remove', dest = 'remove', + help = 'object files matching this regexp will be removed ' + 'from the output library') + return parser + + +def Main(): + '''Main function for this script''' + parser = GetOptionParser() + (opt, args) = parser.parse_args() + output = opt.output + remove = opt.remove + if not output: + parser.error('You must specify an output file') + + if not args: + parser.error('You must specify at least one object or library') + + output = output.strip() + if remove: + remove = remove.strip() + + if remove: + try: + remove_re = re.compile(opt.remove) + except: + parser.error('%s is not a valid regular expression' % opt.remove) + else: + remove_re = None + + if sys.platform != 'win32' and sys.platform != 'cygwin': + parser.error('this script only works on Windows for now') + + # If this is set, we can't capture lib.exe's output. + if 'VS_UNICODE_OUTPUT' in os.environ: + del os.environ['VS_UNICODE_OUTPUT'] + + CombineLibraries(output, remove_re, args) + return 0 + + +if __name__ == '__main__': + sys.exit(Main()) diff --git a/tools/date_util.py b/tools/date_util.py new file mode 100644 index 000000000..ca447f309 --- /dev/null +++ b/tools/date_util.py @@ -0,0 +1,13 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +import datetime + +def get_year(): + """ Returns the current year. """ + return str(datetime.datetime.now().year) + +def get_date(): + """ Returns the current date. """ + return datetime.datetime.now().strftime('%B %d, %Y') diff --git a/tools/distrib/README-TRANSFER.txt b/tools/distrib/README-TRANSFER.txt new file mode 100644 index 000000000..6843cc201 --- /dev/null +++ b/tools/distrib/README-TRANSFER.txt @@ -0,0 +1,5 @@ +Files in this directory have been copied from other locations in the Chromium +source tree. They have been modified only to the extent necessary to work in +the CEF Binary Distribution directory structure. Below is a listing of the +original file locations. + diff --git a/tools/distrib/README.client.txt b/tools/distrib/README.client.txt new file mode 100644 index 000000000..650c078a0 --- /dev/null +++ b/tools/distrib/README.client.txt @@ -0,0 +1,12 @@ +CONTENTS +-------- + +Release Contains a release build of the cefclient sample application. + + +USAGE +----- + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/README.footer.txt b/tools/distrib/README.footer.txt new file mode 100644 index 000000000..e57a66224 --- /dev/null +++ b/tools/distrib/README.footer.txt @@ -0,0 +1,8 @@ +LICENSING +--------- + +The CEF project is BSD licensed. Please read the LICENSE.txt file included with +this binary distribution for licensing terms and conditions. Other software +included in this distribution is provided under other licenses. Please visit +"about:credits" in a CEF-based application for complete Chromium and third-party +licensing information. diff --git a/tools/distrib/README.header.txt b/tools/distrib/README.header.txt new file mode 100644 index 000000000..4bcfc0911 --- /dev/null +++ b/tools/distrib/README.header.txt @@ -0,0 +1,14 @@ +Chromium Embedded Framework (CEF) $DISTRIB_TYPE$ Binary Distribution for $PLATFORM$ +------------------------------------------------------------------------------- + +Date: $DATE$ + +CEF Version: $CEF_VER$ +CEF URL: $CEF_URL$ + @$CEF_REV$ + +Chromium Verison: $CHROMIUM_VER$ +Chromium URL: $CHROMIUM_URL$ + @$CHROMIUM_REV$ + +$DISTRIB_DESC$ diff --git a/tools/distrib/cefclient.gyp b/tools/distrib/cefclient.gyp new file mode 100644 index 000000000..63fd0daac --- /dev/null +++ b/tools/distrib/cefclient.gyp @@ -0,0 +1,705 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +{ + 'variables': { + 'chromium_code': 1, + 'framework_name': 'Chromium Embedded Framework', + 'linux_use_gold_binary': 0, + 'linux_use_gold_flags': 0, + # Don't use clang with CEF binary releases due to Chromium tree structure dependency. + 'clang': 0, + 'conditions': [ + ['sysroot!=""', { + 'pkg-config': './pkg-config-wrapper "<(sysroot)" "<(target_arch)"', + }, { + 'pkg-config': 'pkg-config' + }], + [ 'OS=="win"', { + 'multi_threaded_dll%': 0, + }], + ] + }, + 'includes': [ + # Bring in the source file lists for cefclient. + 'cef_paths2.gypi', + ], + 'targets': [ + { + 'target_name': 'cefclient', + 'type': 'executable', + 'mac_bundle': 1, + 'msvs_guid': '6617FED9-C5D4-4907-BF55-A90062A6683F', + 'dependencies': [ + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'sources': [ + '<@(includes_common)', + '<@(includes_wrapper)', + '<@(cefclient_sources_common)', + ], + 'mac_bundle_resources': [ + '<@(cefclient_bundle_resources_mac)', + ], + 'mac_bundle_resources!': [ + # TODO(mark): Come up with a fancier way to do this (mac_info_plist?) + # that automatically sets the correct INFOPLIST_FILE setting and adds + # the file to a source group. + 'cefclient/mac/Info.plist', + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'cefclient/mac/Info.plist', + # Target build path. + 'SYMROOT': 'xcodebuild', + }, + 'conditions': [ + ['OS=="win"', { + 'variables': { + 'win_exe_compatibility_manifest': 'cefclient/compatibility.manifest', + }, + 'actions': [ + { + 'action_name': 'copy_resources', + 'msvs_cygwin_shell': 0, + 'inputs': [], + 'outputs': [ + '<(PRODUCT_DIR)/copy_resources.stamp', + ], + 'action': [ + 'xcopy /efy', + 'Resources\*', + '$(OutDir)', + ], + }, + { + 'action_name': 'copy_executables', + 'msvs_cygwin_shell': 0, + 'inputs': [], + 'outputs': [ + '<(PRODUCT_DIR)/copy_executables.stamp', + ], + 'action': [ + 'xcopy /efy', + '$(ConfigurationName)\*.exe', + '$(OutDir)', + ], + }, + { + 'action_name': 'copy_libraries', + 'msvs_cygwin_shell': 0, + 'inputs': [], + 'outputs': [ + '<(PRODUCT_DIR)/copy_libraries.stamp', + ], + 'action': [ + 'xcopy /efy', + '$(ConfigurationName)\*.dll', + '$(OutDir)', + ], + }, + ], + 'msvs_settings': { + 'VCLinkerTool': { + # Set /SUBSYSTEM:WINDOWS. + 'SubSystem': '2', + }, + 'VCManifestTool': { + 'AdditionalManifestFiles': [ + 'cefclient/cefclient.exe.manifest', + ], + }, + }, + 'link_settings': { + 'libraries': [ + '-lcomctl32.lib', + '-lshlwapi.lib', + '-lrpcrt4.lib', + '-lopengl32.lib', + '-lglu32.lib', + '-l$(ConfigurationName)/libcef.lib', + ], + }, + 'library_dirs': [ + # Needed to find cef_sandbox.lib using #pragma comment(lib, ...). + '$(ConfigurationName)', + ], + 'sources': [ + '<@(includes_win)', + '<@(cefclient_sources_win)', + ], + }], + [ 'OS=="win" and multi_threaded_dll', { + 'configurations': { + 'Debug': { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 3, + 'WarnAsError': 'false', + }, + }, + }, + 'Release': { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 2, + 'WarnAsError': 'false', + }, + }, + } + } + }], + [ 'OS=="mac"', { + 'product_name': 'cefclient', + 'dependencies': [ + 'cefclient_helper_app', + ], + 'copies': [ + { + # Add libraries and helper app. + 'destination': '<(PRODUCT_DIR)/cefclient.app/Contents/Frameworks', + 'files': [ + '<(PRODUCT_DIR)/cefclient Helper.app', + ], + }, + ], + 'postbuilds': [ + { + 'postbuild_name': 'Add framework', + 'action': [ + 'cp', + '-Rf', + '${CONFIGURATION}/<(framework_name).framework', + '${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks/' + ], + }, + { + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + { + # This postbuid step is responsible for creating the following + # helpers: + # + # cefclient Helper EH.app and cefclient Helper NP.app are created + # from cefclient Helper.app. + # + # The EH helper is marked for an executable heap. The NP helper + # is marked for no PIE (ASLR). + 'postbuild_name': 'Make More Helpers', + 'action': [ + 'tools/make_more_helpers.sh', + 'Frameworks', + 'cefclient', + ], + }, + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework', + '$(CONFIGURATION)/<(framework_name).framework/<(framework_name)', + ], + }, + 'sources': [ + '<@(includes_mac)', + '<@(cefclient_sources_mac)', + ], + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'copies': [ + { + 'destination': '<(PRODUCT_DIR)/files', + 'files': [ + '<@(cefclient_bundle_resources_linux)', + ], + }, + { + 'destination': '<(PRODUCT_DIR)/', + 'files': [ + 'Resources/cef.pak', + 'Resources/cef_100_percent.pak', + 'Resources/cef_200_percent.pak', + 'Resources/devtools_resources.pak', + 'Resources/icudtl.dat', + 'Resources/locales/', + 'Resources/natives_blob.bin', + 'Resources/snapshot_blob.bin', + '$(BUILDTYPE)/chrome-sandbox', + '$(BUILDTYPE)/libcef.so', + '$(BUILDTYPE)/libffmpegsumo.so', + '$(BUILDTYPE)/libpdf.so', + ], + }, + ], + 'dependencies': [ + 'gtk', + 'gtkglext', + ], + 'link_settings': { + 'ldflags': [ + # Look for libcef.so in the current directory. Path can also be + # specified using the LD_LIBRARY_PATH environment variable. + '-Wl,-rpath,.', + ], + 'libraries': [ + "$(BUILDTYPE)/libcef.so", + "-lX11", + ], + }, + 'sources': [ + '<@(includes_linux)', + '<@(cefclient_sources_linux)', + ], + }], + ], + }, + { + 'target_name': 'cefsimple', + 'type': 'executable', + 'mac_bundle': 1, + 'msvs_guid': '5390D142-473F-49A0-BC5E-5F6C609EEDB6', + 'dependencies': [ + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'sources': [ + '<@(includes_common)', + '<@(includes_wrapper)', + '<@(cefsimple_sources_common)', + ], + 'mac_bundle_resources': [ + '<@(cefsimple_bundle_resources_mac)', + ], + 'mac_bundle_resources!': [ + # TODO(mark): Come up with a fancier way to do this (mac_info_plist?) + # that automatically sets the correct INFOPLIST_FILE setting and adds + # the file to a source group. + 'cefsimple/mac/Info.plist', + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'cefsimple/mac/Info.plist', + # Target build path. + 'SYMROOT': 'xcodebuild', + }, + 'conditions': [ + ['OS=="win"', { + 'variables': { + 'win_exe_compatibility_manifest': 'cefsimple/compatibility.manifest', + }, + 'actions': [ + { + 'action_name': 'copy_resources', + 'msvs_cygwin_shell': 0, + 'inputs': [], + 'outputs': [ + '<(PRODUCT_DIR)/copy_resources.stamp', + ], + 'action': [ + 'xcopy /efy', + 'Resources\*', + '$(OutDir)', + ], + }, + { + 'action_name': 'copy_executables', + 'msvs_cygwin_shell': 0, + 'inputs': [], + 'outputs': [ + '<(PRODUCT_DIR)/copy_executables.stamp', + ], + 'action': [ + 'xcopy /efy', + '$(ConfigurationName)\*.exe', + '$(OutDir)', + ], + }, + { + 'action_name': 'copy_libraries', + 'msvs_cygwin_shell': 0, + 'inputs': [], + 'outputs': [ + '<(PRODUCT_DIR)/copy_libraries.stamp', + ], + 'action': [ + 'xcopy /efy', + '$(ConfigurationName)\*.dll', + '$(OutDir)', + ], + }, + ], + 'msvs_settings': { + 'VCLinkerTool': { + # Set /SUBSYSTEM:WINDOWS. + 'SubSystem': '2', + }, + 'VCManifestTool': { + 'AdditionalManifestFiles': [ + 'cefsimple/cefsimple.exe.manifest', + ], + }, + }, + 'link_settings': { + 'libraries': [ + '-lcomctl32.lib', + '-lshlwapi.lib', + '-lrpcrt4.lib', + '-l$(ConfigurationName)/libcef.lib', + ], + }, + 'library_dirs': [ + # Needed to find cef_sandbox.lib using #pragma comment(lib, ...). + '$(ConfigurationName)', + ], + 'sources': [ + '<@(includes_win)', + '<@(cefsimple_sources_win)', + ], + }], + [ 'OS=="win" and multi_threaded_dll', { + 'configurations': { + 'Debug': { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 3, + 'WarnAsError': 'false', + }, + }, + }, + 'Release': { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 2, + 'WarnAsError': 'false', + }, + }, + } + } + }], + [ 'OS=="mac"', { + 'product_name': 'cefsimple', + 'dependencies': [ + 'cefsimple_helper_app', + ], + 'copies': [ + { + # Add libraries and helper app. + 'destination': '<(PRODUCT_DIR)/cefsimple.app/Contents/Frameworks', + 'files': [ + '<(PRODUCT_DIR)/cefsimple Helper.app', + ], + }, + ], + 'postbuilds': [ + { + 'postbuild_name': 'Add framework', + 'action': [ + 'cp', + '-Rf', + '${CONFIGURATION}/<(framework_name).framework', + '${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app/Contents/Frameworks/' + ], + }, + { + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + { + # This postbuid step is responsible for creating the following + # helpers: + # + # cefsimple Helper EH.app and cefsimple Helper NP.app are created + # from cefsimple Helper.app. + # + # The EH helper is marked for an executable heap. The NP helper + # is marked for no PIE (ASLR). + 'postbuild_name': 'Make More Helpers', + 'action': [ + 'tools/make_more_helpers.sh', + 'Frameworks', + 'cefsimple', + ], + }, + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + '$(CONFIGURATION)/<(framework_name).framework/<(framework_name)', + ], + }, + 'sources': [ + '<@(includes_mac)', + '<@(cefsimple_sources_mac)', + ], + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'copies': [ + { + 'destination': '<(PRODUCT_DIR)/', + 'files': [ + 'Resources/cef.pak', + 'Resources/cef_100_percent.pak', + 'Resources/cef_200_percent.pak', + 'Resources/devtools_resources.pak', + 'Resources/icudtl.dat', + 'Resources/locales/', + 'Resources/natives_blob.bin', + 'Resources/snapshot_blob.bin', + '$(BUILDTYPE)/chrome-sandbox', + '$(BUILDTYPE)/libcef.so', + '$(BUILDTYPE)/libffmpegsumo.so', + '$(BUILDTYPE)/libpdf.so', + ], + }, + ], + 'link_settings': { + 'ldflags': [ + # Look for libcef.so in the current directory. Path can also be + # specified using the LD_LIBRARY_PATH environment variable. + '-Wl,-rpath,.', + ], + 'libraries': [ + "$(BUILDTYPE)/libcef.so", + "-lX11", + ], + }, + 'sources': [ + '<@(includes_linux)', + '<@(cefsimple_sources_linux)', + ], + }], + ], + }, + { + 'target_name': 'libcef_dll_wrapper', + 'type': 'static_library', + 'msvs_guid': 'A9D6DC71-C0DC-4549-AEA0-3B15B44E86A9', + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'sources': [ + '<@(includes_common)', + '<@(includes_capi)', + '<@(includes_wrapper)', + '<@(libcef_dll_wrapper_sources_common)', + ], + 'xcode_settings': { + # Target build path. + 'SYMROOT': 'xcodebuild', + }, + 'conditions': [ + [ 'OS=="win" and multi_threaded_dll', { + 'configurations': { + 'Debug': { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 3, + 'WarnAsError': 'false', + }, + }, + }, + 'Release': { + 'msvs_settings': { + 'VCCLCompilerTool': { + 'RuntimeLibrary': 2, + 'WarnAsError': 'false', + }, + }, + } + } + }], + ], + }, + ], + 'conditions': [ + ['OS=="mac"', { + 'targets': [ + { + 'target_name': 'cefclient_helper_app', + 'type': 'executable', + 'variables': { 'enable_wexit_time_destructors': 1, }, + 'product_name': 'cefclient Helper', + 'mac_bundle': 1, + 'dependencies': [ + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + '$(CONFIGURATION)/<(framework_name).framework/<(framework_name)', + ], + }, + 'sources': [ + '<@(cefclient_sources_mac_helper)', + ], + # TODO(mark): Come up with a fancier way to do this. It should only + # be necessary to list helper-Info.plist once, not the three times it + # is listed here. + 'mac_bundle_resources!': [ + 'cefclient/mac/helper-Info.plist', + ], + # TODO(mark): For now, don't put any resources into this app. Its + # resources directory will be a symbolic link to the browser app's + # resources directory. + 'mac_bundle_resources/': [ + ['exclude', '.*'], + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'cefclient/mac/helper-Info.plist', + }, + 'postbuilds': [ + { + # The framework defines its load-time path + # (DYLIB_INSTALL_NAME_BASE) relative to the main executable + # (chrome). A different relative path needs to be used in + # cefclient_helper_app. + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../../../../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + ], + }, # target cefclient_helper_app + { + 'target_name': 'cefsimple_helper_app', + 'type': 'executable', + 'variables': { 'enable_wexit_time_destructors': 1, }, + 'product_name': 'cefsimple Helper', + 'mac_bundle': 1, + 'dependencies': [ + 'libcef_dll_wrapper', + ], + 'defines': [ + 'USING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + '$(CONFIGURATION)/<(framework_name).framework/<(framework_name)', + ], + }, + 'sources': [ + '<@(cefsimple_sources_mac_helper)', + ], + # TODO(mark): Come up with a fancier way to do this. It should only + # be necessary to list helper-Info.plist once, not the three times it + # is listed here. + 'mac_bundle_resources!': [ + 'cefsimple/mac/helper-Info.plist', + ], + # TODO(mark): For now, don't put any resources into this app. Its + # resources directory will be a symbolic link to the browser app's + # resources directory. + 'mac_bundle_resources/': [ + ['exclude', '.*'], + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'cefsimple/mac/helper-Info.plist', + }, + 'postbuilds': [ + { + # The framework defines its load-time path + # (DYLIB_INSTALL_NAME_BASE) relative to the main executable + # (chrome). A different relative path needs to be used in + # cefsimple_helper_app. + 'postbuild_name': 'Fix Framework Link', + 'action': [ + 'install_name_tool', + '-change', + '@executable_path/<(framework_name)', + '@executable_path/../../../../Frameworks/<(framework_name).framework/<(framework_name)', + '${BUILT_PRODUCTS_DIR}/${EXECUTABLE_PATH}' + ], + }, + ], + }, # target cefsimple_helper_app + ], + }], # OS=="mac" + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'targets': [ + { + 'target_name': 'gtk', + 'type': 'none', + 'variables': { + # gtk requires gmodule, but it does not list it as a dependency + # in some misconfigured systems. + 'gtk_packages': 'gmodule-2.0 gtk+-2.0 gthread-2.0 gtk+-unix-print-2.0', + }, + 'direct_dependent_settings': { + 'cflags': [ + '$(shell <(pkg-config) --cflags <(gtk_packages))', + ], + }, + 'link_settings': { + 'ldflags': [ + '$(shell <(pkg-config) --libs-only-L --libs-only-other <(gtk_packages))', + ], + 'libraries': [ + '$(shell <(pkg-config) --libs-only-l <(gtk_packages))', + ], + }, + }, + { + 'target_name': 'gtkglext', + 'type': 'none', + 'variables': { + # gtkglext is required by the cefclient OSR example. + 'gtk_packages': 'gtkglext-1.0', + }, + 'direct_dependent_settings': { + 'cflags': [ + '$(shell <(pkg-config) --cflags <(gtk_packages))', + ], + }, + 'link_settings': { + 'ldflags': [ + '$(shell <(pkg-config) --libs-only-L --libs-only-other <(gtk_packages))', + ], + 'libraries': [ + '$(shell <(pkg-config) --libs-only-l <(gtk_packages))', + ], + }, + }, + ], + }], # OS=="linux" or OS=="freebsd" or OS=="openbsd" + ], +} diff --git a/tools/distrib/linux/README.minimal.txt b/tools/distrib/linux/README.minimal.txt new file mode 100644 index 000000000..abe1d2224 --- /dev/null +++ b/tools/distrib/linux/README.minimal.txt @@ -0,0 +1,17 @@ +CONTENTS +-------- + +Release Contains libcef.so and other components required to run the release + version of CEF-based applications. By default these files should be + placed in the same directory as the executable. + +Resources Contains resources required by libcef.so. By default these files + should be placed in the same directory as libcef.so. + + +USAGE +----- + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/linux/README.redistrib.txt b/tools/distrib/linux/README.redistrib.txt new file mode 100644 index 000000000..5e9bd4a88 --- /dev/null +++ b/tools/distrib/linux/README.redistrib.txt @@ -0,0 +1,47 @@ +REDISTRIBUTION +-------------- + +This binary distribution contains the below components. Components listed under +the "required" section must be redistributed with all applications using CEF. +Components listed under the "optional" section may be excluded if the related +features will not be used. + +Required components: + +* CEF core library + libcef.so + +* Unicode support + icudtl.dat + +* V8 initial snapshot + natives_blob.bin + snapshot_blob.bin + +Optional components: + +* Localized resources + locales/ + Note: Contains localized strings for WebKit UI controls. A .pak file is loaded + from this folder based on the value of environment variables which are read + with the following precedence order: LANGUAGE, LC_ALL, LC_MESSAGES and LANG. + Only configured locales need to be distributed. If no locale is configured the + default locale of "en-US" will be used. Locale file loading can be disabled + completely using CefSettings.pack_loading_disabled. The locales folder path + can be customized using CefSettings.locales_dir_path. + +* Other resources + cef.pak + cef_100_percent.pak + cef_200_percent.pak + devtools_resources.pak + Note: Contains WebKit image and inspector resources. Pack file loading can be + disabled completely using CefSettings.pack_loading_disabled. The resources + directory path can be customized using CefSettings.resources_dir_path. + +* FFmpeg audio and video support + libffmpegsumo.so + Note: Without this component HTML5 audio and video will not function. + +* PDF support + libpdf.so diff --git a/tools/distrib/linux/README.standard.txt b/tools/distrib/linux/README.standard.txt new file mode 100644 index 000000000..9144f976c --- /dev/null +++ b/tools/distrib/linux/README.standard.txt @@ -0,0 +1,41 @@ +CONTENTS +-------- + +cefclient Contains the cefclient sample application configured to build + using the files in this distribution. This application demonstrates + a wide range of CEF functionalities. + +cefsimple Contains the cefsimple sample application configured to build + using the files in this distribution. This application demonstrates + the minimal functionality required to create a browser window. + +Debug Contains libcef.so and other components required to run the debug + version of CEF-based applications. By default these files should be + placed in the same directory as the executable and will be copied + there as part of the build process. + +include Contains all required CEF header files. + +libcef_dll Contains the source code for the libcef_dll_wrapper static library + that all applications using the CEF C++ API must link against. + +Release Contains libcef.so and other components required to run the release + version of CEF-based applications. By default these files should be + placed in the same directory as the executable and will be copied + there as part of the build process. + +Resources Contains resources required by libcef.so. By default these files + should be placed in the same directory as libcef.so and will be + copied there as part of the build process. + + +USAGE +----- + +Building using CMake: + CMake can be used to generate project files in many different formats. See + usage instructions at the top of the CMakeLists.txt file. + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/linux/build.sh b/tools/distrib/linux/build.sh new file mode 100755 index 000000000..08b4e49d8 --- /dev/null +++ b/tools/distrib/linux/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +if [ -z "$1" ]; then + echo "ERROR: Please specify a build target: Debug or Release" +else + make -j8 cefclient cefsimple BUILDTYPE=$1 + if [ $? -eq 0 ]; then + echo "Giving SUID permissions to chrome-sandbox..." + echo "(using sudo so you may be asked for your password)" + sudo -- chown root:root "out/$1/chrome-sandbox" && + sudo -- chmod 4755 "out/$1/chrome-sandbox" + fi +fi diff --git a/tools/distrib/mac/README.minimal.txt b/tools/distrib/mac/README.minimal.txt new file mode 100644 index 000000000..0b276f8c1 --- /dev/null +++ b/tools/distrib/mac/README.minimal.txt @@ -0,0 +1,14 @@ +CONTENTS +-------- + +Release Contains the "Chromium Embedded Framework.framework" and other + components required to run the release version of CEF-based + applications. + + +USAGE +----- + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/mac/README.redistrib.txt b/tools/distrib/mac/README.redistrib.txt new file mode 100644 index 000000000..bc897d9d2 --- /dev/null +++ b/tools/distrib/mac/README.redistrib.txt @@ -0,0 +1,113 @@ +REDISTRIBUTION +-------------- + +This binary distribution contains the below components. Components listed under +the "required" section must be redistributed with all applications using CEF. +Components listed under the "optional" section may be excluded if the related +features will not be used. + +Applications using CEF on OS X must follow a specific app bundle structure. +Replace "cefclient" in the below example with your application name. + +cefclient.app/ + Contents/ + Frameworks/ + Chromium Embedded Framework.framework/ + Chromium Embedded Framework <= main application library + Libraries/ + ffmpegsumo.so <= HTML5 audio/video support library + PDF.plugin <= Pepper plugin for PDF support + Resources/ + cef.pak <= non-localized resources and strings + cef_100_percent.pak <====^ + cef_200_percent.pak <====^ + devtools_resources.pak <=^ + crash_inspector, crash_report_sender <= breakpad support + icudtl.dat <= unicode support + natives_blob.bin, snapshot_blob.bin <= V8 initial snapshot + en.lproj/, ... <= locale-specific resources and strings + Info.plist + cefclient Helper.app/ + Contents/ + Info.plist + MacOS/ + cefclient Helper <= helper executable + Pkginfo + cefclient Helper EH.app/ + Contents/ + Info.plist + MacOS/ + cefclient Helper EH <= helper executable + Pkginfo + cefclient Helper NP.app/ + Contents/ + Info.plist + MacOS/ + cefclient Helper NP <= helper executable + Pkginfo + Info.plist + MacOS/ + cefclient <= cefclient application executable + Pkginfo + Resources/ + binding.html, ... <= cefclient application resources + +The "Chromium Embedded Framework.framework" is an unversioned framework that +contains CEF binaries and resources. Executables (cefclient, cefclient Helper, +etc) are linked to the "Chromium Embedded Framework" library using +install_name_tool and a path relative to @executable_path. + +The "cefclient Helper" apps are used for executing separate processes +(renderer, plugin, etc) with different characteristics. They need to have +separate app bundles and Info.plist files so that, among other things, they +don't show dock icons. The "EH" helper, which is used when launching plugin +processes, has the MH_NO_HEAP_EXECUTION bit cleared to allow an executable +heap. The "NP" helper, which is used when launching NaCl plugin processes +only, has the MH_PIE bit cleared to disable ASLR. This is set up as part of +the build process using scripts from the tools/ directory. Examine the Xcode +project included with the binary distribution or the originating cefclient.gyp +file for a better idea of the script dependencies. + +Required components: + +* CEF framework library + Chromium Embedded Framework.framework/Chromium Embedded Framework + +* Unicode support + Chromium Embedded Framework.framework/Resources/icudtl.dat + +* V8 initial snapshot + Chromium Embedded Framework.framework/Resources/natives_blob.bin + Chromium Embedded Framework.framework/Resources/snapshot_blob.bin + +Optional components: + +* Localized resources + Chromium Embedded Framework.framework/Resources/*.lproj/ + Note: Contains localized strings for WebKit UI controls. A .pak file is loaded + from this folder based on the CefSettings.locale value. Only configured + locales need to be distributed. If no locale is configured the default locale + of "en" will be used. Locale file loading can be disabled completely using + CefSettings.pack_loading_disabled. + +* Other resources + Chromium Embedded Framework.framework/Resources/cef.pak + Chromium Embedded Framework.framework/Resources/cef_100_percent.pak + Chromium Embedded Framework.framework/Resources/cef_200_percent.pak + Chromium Embedded Framework.framework/Resources/devtools_resources.pak + Note: Contains WebKit image and inspector resources. Pack file loading can be + disabled completely using CefSettings.pack_loading_disabled. The resources + directory path can be customized using CefSettings.resources_dir_path. + +* FFmpeg audio and video support + Chromium Embedded Framework.framework/Libraries/ffmpegsumo.so + Note: Without this component HTML5 audio and video will not function. + +* PDF support + Chromium Embedded Framework.framework/Libraries/PDF.plugin + +* Breakpad support + Chromium Embedded Framework.framework/Resources/crash_inspector + Chromium Embedded Framework.framework/Resources/crash_report_sender + Chromium Embedded Framework.framework/Resources/Info.plist + Note: Without these components breakpad support will not function. diff --git a/tools/distrib/mac/README.standard.txt b/tools/distrib/mac/README.standard.txt new file mode 100644 index 000000000..91c1d68b8 --- /dev/null +++ b/tools/distrib/mac/README.standard.txt @@ -0,0 +1,37 @@ +CONTENTS +-------- + +cefclient Contains the cefclient sample application configured to build + using the files in this distribution. This application demonstrates + a wide range of CEF functionalities. + +cefsimple Contains the cefsimple sample application configured to build + using the files in this distribution. This application demonstrates + the minimal functionality required to create a browser window. + +Debug Contains the "Chromium Embedded Framework.framework" and other + components required to run the debug version of CEF-based + applications. + +include Contains all required CEF header files. + +libcef_dll Contains the source code for the libcef_dll_wrapper static library + that all applications using the CEF C++ API must link against. + +Release Contains the "Chromium Embedded Framework.framework" and other + components required to run the release version of CEF-based + applications. + +tools Scripts that perform post-processing on Mac release targets. + + +USAGE +----- + +Building using CMake: + CMake can be used to generate project files in many different formats. See + usage instructions at the top of the CMakeLists.txt file. + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/mac/transfer.cfg b/tools/distrib/mac/transfer.cfg new file mode 100644 index 000000000..952c06166 --- /dev/null +++ b/tools/distrib/mac/transfer.cfg @@ -0,0 +1,33 @@ +# Additional handling of transfer files. +# target: Target location relative to the target release directory. This +# value is required. +# source: Source location relative to the CEF root directory. This value +# is optional. If specified the target will be copied to this location +# and a TRANSFER-README.txt file will be created. +# post-process: Post-processing operation to perform. This value is +# optional and may be any one of the following: +# 'normalize_headers': Replace fully-qualified project header paths with +# the optionally specified 'new_header_path' value. + +[ + { + 'source' : '../build/mac/change_mach_o_flags_from_xcode.sh', + 'target' : 'tools/change_mach_o_flags_from_xcode.sh', + }, + { + 'source' : '../build/mac/change_mach_o_flags.py', + 'target' : 'tools/change_mach_o_flags.py', + }, + { + 'source' : '../build/mac/strip_from_xcode', + 'target' : 'tools/strip_from_xcode', + }, + { + 'source' : '../build/mac/strip_save_dsym', + 'target' : 'tools/strip_save_dsym', + }, + { + 'source' : '../build/mac/make_more_helpers.sh', + 'target' : 'tools/make_more_helpers.sh', + }, +] diff --git a/tools/distrib/transfer.cfg b/tools/distrib/transfer.cfg new file mode 100644 index 000000000..a0e42dc57 --- /dev/null +++ b/tools/distrib/transfer.cfg @@ -0,0 +1,13 @@ +# Additional handling of transfer files. +# target: Target location relative to the target release directory. This +# value is required. +# source: Source location relative to the CEF root directory. This value +# is optional. If specified the target will be copied to this location +# and a TRANSFER-README.txt file will be created. +# post-process: Post-processing operation to perform. This value is +# optional and may be any one of the following: +# 'normalize_headers': Replace fully-qualified project header paths with +# the optionally specified 'new_header_path' value. + +[ +] \ No newline at end of file diff --git a/tools/distrib/win/README.minimal.txt b/tools/distrib/win/README.minimal.txt new file mode 100644 index 000000000..ac450fbd2 --- /dev/null +++ b/tools/distrib/win/README.minimal.txt @@ -0,0 +1,19 @@ +CONTENTS +-------- + +Release Contains libcef.dll, libcef.lib and other components required to + build and run the release version of CEF-based applications. By + default these files should be placed in the same directory as the + executable. + +Resources Contains resources required by libcef.dll. By default these files + should be placed in the same directory as libcef.dll. By default + these files should be placed in the same directory as libcef.dll. + + +USAGE +----- + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/win/README.redistrib.txt b/tools/distrib/win/README.redistrib.txt new file mode 100644 index 000000000..697484f6b --- /dev/null +++ b/tools/distrib/win/README.redistrib.txt @@ -0,0 +1,56 @@ +REDISTRIBUTION +-------------- + +This binary distribution contains the below components. Components listed under +the "required" section must be redistributed with all applications using CEF. +Components listed under the "optional" section may be excluded if the related +features will not be used. + +Required components: + +* CEF core library + libcef.dll + +* Unicode support + icudtl.dat + +Optional components: + +* Localized resources + locales/ + Note: Contains localized strings for WebKit UI controls. A .pak file is loaded + from this folder based on the CefSettings.locale value. Only configured + locales need to be distributed. If no locale is configured the default locale + of "en-US" will be used. Locale file loading can be disabled completely using + CefSettings.pack_loading_disabled. The locales folder path can be customized + using CefSettings.locales_dir_path. + +* Other resources + cef.pak + cef_100_percent.pak + cef_200_percent.pak + devtools_resources.pak + Note: Contains WebKit image and inspector resources. Pack file loading can be + disabled completely using CefSettings.pack_loading_disabled. The resources + directory path can be customized using CefSettings.resources_dir_path. + +* FFmpeg audio and video support + ffmpegsumo.dll + Note: Without this component HTML5 audio and video will not function. + +* PDF support + pdf.dll + Note: Without this component printing will not function. + +* Angle and Direct3D support + d3dcompiler_43.dll (required for Windows XP) + d3dcompiler_47.dll (required for Windows Vista and newer) + libEGL.dll + libGLESv2.dll + Note: Without these components HTML5 accelerated content like 2D canvas, 3D + CSS and WebGL will not function. + +* Windows Vista 64-bit sandbox support (32-bit distributions only) + wow_helper.exe + Note: Without this component the 32-bit build of CEF will not run on 64-bit + Vista machines with the sandbox enabled. diff --git a/tools/distrib/win/README.standard.txt b/tools/distrib/win/README.standard.txt new file mode 100644 index 000000000..e323cdf6a --- /dev/null +++ b/tools/distrib/win/README.standard.txt @@ -0,0 +1,42 @@ +CONTENTS +-------- + +cefclient Contains the cefclient sample application configured to build + using the files in this distribution. This application demonstrates + a wide range of CEF functionalities. + +cefsimple Contains the cefsimple sample application configured to build + using the files in this distribution. This application demonstrates + the minimal functionality required to create a browser window. + +Debug Contains libcef.dll, libcef.lib and other components required to + build and run the debug version of CEF-based applications. By + default these files should be placed in the same directory as the + executable and will be copied there as part of the build process. + +include Contains all required CEF header files. + +libcef_dll Contains the source code for the libcef_dll_wrapper static library + that all applications using the CEF C++ API must link against. + +Release Contains libcef.dll, libcef.lib and other components required to + build and run the release version of CEF-based applications. By + default these files should be placed in the same directory as the + executable and will be copied there as part of the build process. + +Resources Contains resources required by libcef.dll. By default these files + should be placed in the same directory as libcef.dll. By default + these files should be placed in the same directory as libcef.dll + and will be copied there as part of the build process. + + +USAGE +----- + +Building using CMake: + CMake can be used to generate project files in many different formats. See + usage instructions at the top of the CMakeLists.txt file. + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded diff --git a/tools/distrib/win/d3dcompiler_43.dll b/tools/distrib/win/d3dcompiler_43.dll new file mode 100644 index 000000000..ab9616191 Binary files /dev/null and b/tools/distrib/win/d3dcompiler_43.dll differ diff --git a/tools/distrib/win/transfer.cfg b/tools/distrib/win/transfer.cfg new file mode 100644 index 000000000..4788c39e8 --- /dev/null +++ b/tools/distrib/win/transfer.cfg @@ -0,0 +1,21 @@ +# Additional handling of transfer files. +# target: Target location relative to the target release directory. This +# value is required. +# source: Source location relative to the CEF root directory. This value +# is optional. If specified the target will be copied to this location +# and a TRANSFER-README.txt file will be created. +# post-process: Post-processing operation to perform. This value is +# optional and may be any one of the following: +# 'normalize_headers': Replace fully-qualified project header paths with +# the optionally specified 'new_header_path' value. + +[ + { + 'source' : '../build/win/compatibility.manifest', + 'target' : 'cefclient/compatibility.manifest', + }, + { + 'source' : '../build/win/compatibility.manifest', + 'target' : 'cefsimple/compatibility.manifest', + }, +] diff --git a/tools/exec_util.py b/tools/exec_util.py new file mode 100644 index 000000000..522f89d2f --- /dev/null +++ b/tools/exec_util.py @@ -0,0 +1,27 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file + +from subprocess import Popen, PIPE +import sys + +def exec_cmd(cmd, path, input_file=None): + """ Execute the specified command and return the result. """ + out = '' + err = '' + parts = cmd.split() + try: + if not input_file: + process = Popen(parts, cwd=path, stdout=PIPE, stderr=PIPE, + shell=(sys.platform == 'win32')) + else: + with open(input_file, 'rb') as f: + process = Popen(parts, cwd=path, stdout=PIPE, stderr=PIPE, + stdin=f, + shell=(sys.platform == 'win32')) + out, err = process.communicate() + except IOError, (errno, strerror): + raise + except: + raise + return {'out': out, 'err': err} diff --git a/tools/file_util.py b/tools/file_util.py new file mode 100644 index 000000000..a5fb76585 --- /dev/null +++ b/tools/file_util.py @@ -0,0 +1,141 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from glob import iglob +import os +import shutil +import sys +import time + +def read_file(name, normalize = True): + """ Read a file. """ + try: + f = open(name, 'r') + # read the data + data = f.read() + if normalize: + # normalize line endings + data = data.replace("\r\n", "\n") + return data + except IOError, (errno, strerror): + sys.stderr.write('Failed to read file '+name+': '+strerror) + raise + else: + f.close() + +def write_file(name, data): + """ Write a file. """ + try: + f = open(name, 'w') + # write the data + f.write(data) + except IOError, (errno, strerror): + sys.stderr.write('Failed to write file '+name+': '+strerror) + raise + else: + f.close() + +def path_exists(name): + """ Returns true if the path currently exists. """ + return os.path.exists(name) + +def backup_file(name): + """ Rename the file to a name that includes the current time stamp. """ + move_file(name, name+'.'+time.strftime('%Y-%m-%d-%H-%M-%S')) + +def copy_file(src, dst, quiet = True): + """ Copy a file. """ + try: + shutil.copy(src, dst) + if not quiet: + sys.stdout.write('Transferring '+src+' file.\n') + except IOError, (errno, strerror): + sys.stderr.write('Failed to copy file from '+src+' to '+dst+': '+strerror) + raise + +def move_file(src, dst, quiet = True): + """ Move a file. """ + try: + shutil.move(src, dst) + if not quiet: + sys.stdout.write('Moving '+src+' file.\n') + except IOError, (errno, strerror): + sys.stderr.write('Failed to move file from '+src+' to '+dst+': '+strerror) + raise + +def copy_files(src_glob, dst_folder, quiet = True): + """ Copy multiple files. """ + for fname in iglob(src_glob): + dst = os.path.join(dst_folder, os.path.basename(fname)) + if os.path.isdir(fname): + copy_dir(fname, dst, quiet) + else: + copy_file(fname, dst, quiet) + +def remove_file(name, quiet = True): + """ Remove the specified file. """ + try: + if path_exists(name): + os.remove(name) + if not quiet: + sys.stdout.write('Removing '+name+' file.\n') + except IOError, (errno, strerror): + sys.stderr.write('Failed to remove file '+name+': '+strerror) + raise + +def copy_dir(src, dst, quiet = True): + """ Copy a directory tree. """ + try: + remove_dir(dst, quiet) + shutil.copytree(src, dst) + if not quiet: + sys.stdout.write('Transferring '+src+' directory.\n') + except IOError, (errno, strerror): + sys.stderr.write('Failed to copy directory from '+src+' to '+dst+': '+strerror) + raise + +def remove_dir(name, quiet = True): + """ Remove the specified directory. """ + try: + if path_exists(name): + shutil.rmtree(name) + if not quiet: + sys.stdout.write('Removing '+name+' directory.\n') + except IOError, (errno, strerror): + sys.stderr.write('Failed to remove directory '+name+': '+strerror) + raise + +def make_dir(name, quiet = True): + """ Create the specified directory. """ + try: + if not path_exists(name): + if not quiet: + sys.stdout.write('Creating '+name+' directory.\n') + os.makedirs(name) + except IOError, (errno, strerror): + sys.stderr.write('Failed to create directory '+name+': '+strerror) + raise + +def get_files(search_glob): + """ Returns all files matching the search glob. """ + # Sort the result for consistency across platforms. + return sorted(iglob(search_glob)) + +def read_version_file(file, args): + """ Read and parse a version file (key=value pairs, one per line). """ + lines = read_file(file).split("\n") + for line in lines: + parts = line.split('=', 1) + if len(parts) == 2: + args[parts[0]] = parts[1] + +def eval_file(src): + """ Loads and evaluates the contents of the specified file. """ + return eval(read_file(src), {'__builtins__': None}, None) + +def normalize_path(path): + """ Normalizes the path separator to match the Unix standard. """ + if sys.platform == 'win32': + return path.replace('\\', '/') + return path diff --git a/tools/gclient_hook.py b/tools/gclient_hook.py new file mode 100644 index 000000000..fda9e4d8a --- /dev/null +++ b/tools/gclient_hook.py @@ -0,0 +1,106 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. +# Portions copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +from gclient_util import * +import os, sys + +# The CEF directory is the parent directory of _this_ script. +cef_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) +# The src directory is the parent directory of the CEF directory. +src_dir = os.path.abspath(os.path.join(cef_dir, os.pardir)) + +print "\nGenerating CEF version header file..." +gyper = [ 'python', 'tools/make_version_header.py', + '--header', 'include/cef_version.h', + '--cef_version', 'VERSION', + '--chrome_version', '../chrome/VERSION', + '--cpp_header_dir', 'include' ] +RunAction(cef_dir, gyper) + +print "\nPatching build configuration and source files for CEF..." +patcher = [ 'python', 'tools/patcher.py', + '--patch-config', 'patch/patch.cfg' ] +RunAction(cef_dir, patcher) + +print "\nGenerating CEF project files..." + +# depot_tools currently bundles VS2013 Express Update 1 which causes linker +# errors with Debug builds (see issue #1304). Don't use the bundled version +# unless explicitly requested. +if not 'DEPOT_TOOLS_WIN_TOOLCHAIN' in os.environ.keys(): + os.environ['DEPOT_TOOLS_WIN_TOOLCHAIN'] = '0' + +# By default GYP+Ninja on Windows expects Visual Studio to be installed on the +# local machine. To build when Visual Studio is extracted to a directory but not +# installed (e.g. via a custom toolchain) you have two options: +# +# 1. Set up the environment using only environment variables: +# set WIN_CUSTOM_TOOLCHAIN=1 +# set VS_ROOT= +# set SDK_ROOT= +# set INCLUDE= +# set PATH= +# set LIB= +# +# 2. Set up the environment using a combination of environment variables and the +# "%GYP_MSVS_OVERRIDE_PATH%\VC\vcvarsall.bat" script: +# set GYP_MSVS_OVERRIDE_PATH= +# set GYP_DEFINES="windows_sdk_path=" +# +# The following environment variables must also be set: +# set DEPOT_TOOLS_WIN_TOOLCHAIN=0 +# set GYP_MSVS_VERSION= +# set CEF_VCVARS= +custom_toolchain = False +if bool(int(os.environ.get('WIN_CUSTOM_TOOLCHAIN', '0'))): + required_vars = [ + 'GYP_MSVS_VERSION', + 'VS_ROOT', + 'SDK_ROOT', + 'INCLUDE', + 'PATH', + 'LIB', + ] + for var in required_vars: + if not var in os.environ.keys(): + raise Exception('%s environment variable must be set' % var) + + custom_toolchain = True + + # Set windows_sdk_path via GYP_DEFINES. + gyp_defines = '' + if 'GYP_DEFINES' in os.environ.keys(): + gyp_defines = os.environ['GYP_DEFINES'] + ' ' + gyp_defines = gyp_defines + \ + 'windows_sdk_path=' + os.environ['SDK_ROOT'].replace('\\', '/') + os.environ['GYP_DEFINES'] = gyp_defines + + # Necessary to return correct VS version information via GetVSVersion in + # src/tools/gyp/pylib/gyp/msvs_emulation.py. + os.environ['GYP_MSVS_OVERRIDE_PATH'] = os.environ['VS_ROOT'] + + # Generate environment files (environment.x64, environment.x86) in each + # build output directory. + # When using the default toolchain this is done by GenerateEnvironmentFiles + # in src/tools/gyp/pylib/gyp/msvs_emulation.py. + setup_script = os.path.join(cef_dir, 'tools/setup_toolchain.py') + win_tool_script = os.path.join(src_dir, 'tools/gyp/pylib/gyp/win_tool.py') + out_dirs = ['Debug', 'Debug_x64', 'Release', 'Release_x64'] + for out_dir in out_dirs: + out_dir_abs = os.path.join(src_dir, 'out', out_dir) + if not os.path.exists(out_dir_abs): + os.makedirs(out_dir_abs) + cmd = ['python', setup_script, + os.environ['VS_ROOT'], win_tool_script, os.environ['SDK_ROOT']] + RunAction(out_dir_abs, cmd) + +os.environ['CEF_DIRECTORY'] = os.path.basename(cef_dir) +gyper = [ 'python', '../build/gyp_chromium', 'cef.gyp', '-I', 'cef.gypi' ] +if custom_toolchain: + # Disable GYP's auto-detection of the VS install. + gyper.extend(['-G', 'ninja_use_custom_environment_files']) +if 'GYP_ARGUMENTS' in os.environ.keys(): + gyper.extend(os.environ['GYP_ARGUMENTS'].split(' ')) +RunAction(cef_dir, gyper) diff --git a/tools/gclient_util.py b/tools/gclient_util.py new file mode 100644 index 000000000..300841456 --- /dev/null +++ b/tools/gclient_util.py @@ -0,0 +1,45 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. +# Portions copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import os, sys + +try: + # depot_tools may already be in the import path. + import gclient_utils +except ImportError, e: + # Search the PATH environment variable to find the depot_tools folder. + depot_tools = None; + paths = os.environ.get('PATH').split(os.pathsep) + for path in paths: + if os.path.exists(os.path.join(path, 'gclient_utils.py')): + depot_tools = path + break + + if depot_tools is None: + print >> sys.stderr, 'Error: could not find depot_tools in PATH.' + sys.exit(2) + + # Add depot_tools to import path. + sys.path.append(depot_tools) + import gclient_utils + +# Copied from gclient.py python code. +def RunAction(dir, command): + """Runs the action.""" + if command[0] == 'python': + # If the hook specified "python" as the first item, the action is a + # Python script. Run it by starting a new copy of the same + # interpreter. + command[0] = sys.executable + + try: + gclient_utils.CheckCallAndFilterAndHeader( + command, cwd=dir, always=True) + except gclient_utils.Error, e: + # Use a discrete exit status code of 2 to indicate that a hook action + # failed. Users of this script may wish to treat hook action failures + # differently from VC failures. + print >> sys.stderr, 'Error: %s' % str(e) + sys.exit(2) diff --git a/tools/git_util.py b/tools/git_util.py new file mode 100644 index 000000000..91e495959 --- /dev/null +++ b/tools/git_util.py @@ -0,0 +1,44 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file + +from exec_util import exec_cmd +import os + +def is_checkout(path): + """ Returns true if the path represents a git checkout. """ + return os.path.exists(os.path.join(path, '.git')) + +def get_hash(path = '.', branch = 'HEAD'): + """ Returns the git hash for the specified branch/tag/hash. """ + cmd = "git rev-parse %s" % (branch) + result = exec_cmd(cmd, path) + if result['out'] != '': + return result['out'].strip() + return 'Unknown' + +def get_url(path = '.'): + """ Returns the origin url for the specified path. """ + cmd = "git config --get remote.origin.url" + result = exec_cmd(cmd, path) + if result['out'] != '': + return result['out'].strip() + return 'Unknown' + +def get_svn_revision(path = '.', branch = 'HEAD'): + """ Returns the SVN revision associated with the specified path and git + branch/tag/hash. """ + svn_rev = "None" + cmd = "git log --grep=^git-svn-id: -n 1 %s" % (branch) + result = exec_cmd(cmd, path) + if result['err'] == '': + for line in result['out'].split('\n'): + if line.find("git-svn-id") > 0: + svn_rev = line.split("@")[1].split()[0] + break + return svn_rev + +def get_changed_files(path = '.'): + """ Retrieves the list of changed files. """ + # not implemented + return [] diff --git a/tools/make_capi_header.py b/tools/make_capi_header.py new file mode 100644 index 000000000..8cf897773 --- /dev/null +++ b/tools/make_capi_header.py @@ -0,0 +1,202 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from cef_parser import * +from date_util import * + +def make_capi_global_funcs(funcs, defined_names, translate_map, indent): + result = '' + first = True + for func in funcs: + comment = func.get_comment() + if first or len(comment) > 0: + result += '\n'+format_comment(comment, indent, translate_map); + if func.get_retval().get_type().is_result_string(): + result += indent+'// The resulting string must be freed by calling cef_string_userfree_free().\n' + result += wrap_code(indent+'CEF_EXPORT '+ + func.get_capi_proto(defined_names)+';') + if first: + first = False + return result + +def make_capi_member_funcs(funcs, defined_names, translate_map, indent): + result = '' + first = True + for func in funcs: + comment = func.get_comment() + if first or len(comment) > 0: + result += '\n'+format_comment(comment, indent, translate_map) + if func.get_retval().get_type().is_result_string(): + result += indent+'// The resulting string must be freed by calling cef_string_userfree_free().\n' + parts = func.get_capi_parts() + result += wrap_code(indent+parts['retval']+' (CEF_CALLBACK *'+ + parts['name']+')('+ + string.join(parts['args'], ', ')+');') + if first: + first = False + return result + +def make_capi_header(header, filename): + # structure names that have already been defined + defined_names = header.get_defined_structs() + + # map of strings that will be changed in C++ comments + translate_map = header.get_capi_translations() + + # header string + result = \ +"""// Copyright (c) $YEAR$ Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool and should not edited +// by hand. See the translator.README.txt file in the tools directory for +// more information. +// + +#ifndef $GUARD$ +#define $GUARD$ +#pragma once + +""" + classes = header.get_classes(filename) + + # identify all includes and forward declarations + all_includes = set([]) + all_declares = set([]) + for cls in classes: + includes = cls.get_includes() + for include in includes: + all_includes.add(include) + declares = cls.get_forward_declares() + for declare in declares: + all_declares.add(header.get_class(declare).get_capi_name()) + + # output includes + if len(all_includes) > 0: + sorted_includes = sorted(all_includes) + for include in sorted_includes: + result += '#include "include/capi/' + include + '_capi.h"\n' + else: + result += '#include "include/capi/cef_base_capi.h"\n' + + result += \ +""" +#ifdef __cplusplus +extern "C" { +#endif + +""" + + # output forward declarations + if len(all_declares) > 0: + sorted_declares = sorted(all_declares) + for declare in sorted_declares: + result += 'struct _' + declare + ';\n' + + # output classes + for cls in classes: + # virtual functions are inside the structure + classname = cls.get_capi_name() + result += '\n'+format_comment(cls.get_comment(), '', translate_map); + result += 'typedef struct _'+classname+ \ + ' {\n ///\n // Base structure.\n ///\n cef_base_t base;\n' + funcs = cls.get_virtual_funcs() + result += make_capi_member_funcs(funcs, defined_names, + translate_map, ' ') + result += '} '+classname+';\n\n' + + defined_names.append(cls.get_capi_name()) + + # static functions become global + funcs = cls.get_static_funcs() + if len(funcs) > 0: + result += make_capi_global_funcs(funcs, defined_names, + translate_map, '')+'\n' + + # output global functions + funcs = header.get_funcs(filename) + if len(funcs) > 0: + result += make_capi_global_funcs(funcs, defined_names, translate_map, '') + + # footer string + result += \ +""" +#ifdef __cplusplus +} +#endif + +#endif // $GUARD$ +""" + + # add the copyright year + result = result.replace('$YEAR$', get_year()) + # add the guard string + guard = 'CEF_INCLUDE_CAPI_'+string.upper(filename.replace('.', '_capi_'))+'_' + result = result.replace('$GUARD$', guard) + + return result + + +def write_capi_header(header, filepath, backup): + capi_path = get_capi_file_name(filepath) + if path_exists(capi_path): + oldcontents = read_file(capi_path) + else: + oldcontents = '' + + filename = os.path.split(filepath)[1] + newcontents = make_capi_header(header, filename) + if newcontents != oldcontents: + if backup and oldcontents != '': + backup_file(capi_path) + write_file(capi_path, newcontents) + return True + + return False + + +# test the module +if __name__ == "__main__": + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) < 2: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # create the header object + header = obj_header() + header.add_file(sys.argv[1]) + + # dump the result to stdout + filename = os.path.split(sys.argv[1])[1] + sys.stdout.write(make_capi_header(header, filename)) diff --git a/tools/make_cmake.py b/tools/make_cmake.py new file mode 100644 index 000000000..7aa0807bc --- /dev/null +++ b/tools/make_cmake.py @@ -0,0 +1,249 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +import os +from file_util import * +import sys + +# script directory. +script_dir = os.path.dirname(__file__) + +# CEF root directory. +cef_dir = os.path.abspath(os.path.join(script_dir, os.pardir)) + +def get_files_for_variable(cmake_path, variables, variable): + """ Returns the path values associated with |variable| and relative to the + |cmake_path| directory. """ + if not variable in variables: + raise Exception('Variable %s does not exist' % variable) + + # Cmake file directory. + cmake_dirname = os.path.dirname(cmake_path) + '/' + + # Return path values relative to the cmake file directory. + # Example 1: + # cmake file = "/path/to/libcef_dll/CMakeLists.txt" + # include path = "/path/to/libcef_dll/wrapper/cef_browser_info_map.h" + # return path = "wrapper/cef_browser_info_map.h" + # Example 2: + # cmake file = "/path/to/libcef_dll/CMakeLists.txt" + # include path = "/path/to/include/internal/cef_export.h" + # return path = "../include/internal/cef_export.h" + new_paths = [] + paths = variables[variable] + for path in paths: + if path[0] == '<': + # Skip gyp include variables + continue + + abspath = os.path.join(cef_dir, path) + newpath = normalize_path(os.path.relpath(abspath, cmake_dirname)) + new_paths.append(newpath) + return new_paths + +def format_cmake_set(name, values): + result = 'set(%s\n' % name + for value in values: + result += ' %s\n' % value + return result + ' )\n' + +def format_cmake_group(cmake_path, name, files, platform_sep, append_macro): + platforms = {} + common = [] + + # Folder will be the cmake parent directory name combined with the path to + # first file in the files list. + # Example 1: + # cmake file = "/path/to/libcef_dll/CMakeLists.txt" + # include path = "wrapper/cef_browser_info_map.h" + # folder = "libcef_dll\\\\wrapper" + # Example 2: + # cmake file = "/path/to/libcef_dll/CMakeLists.txt" + # include path = "../include/internal/cef_export.h" + # folder = "include\\\\internal" + folder = os.path.basename(os.path.dirname(cmake_path)) + folder = os.path.dirname(os.path.normpath(os.path.join(folder, files[0]))) + folder = normalize_path(folder).replace('/', '\\\\\\\\') + + # Group the files by platform. + for file in files: + parts = file.split(platform_sep) + file = parts[0] + if len(parts) > 1: + # Add the file under the platform. + platform = parts[1] + if not platform in platforms: + platforms[platform] = [] + platforms[platform].append(file) + else: + common.append(file) + + result = '' + if len(common) > 0: + result += format_cmake_set(name, common) + + if len(platforms) > 0: + keys = sorted(platforms.keys()) + for key in keys: + result += format_cmake_set(name + '_' + key, platforms[key]) + result += '%s(%s)\n' % (append_macro, name) + + result += 'source_group(%s FILES ${%s})\n\n' % (folder, name) + return result + +def format_cmake_library(name, group_names): + result = 'add_library(%s\n' % name + for group in group_names: + result += ' ${%s}\n' % group + return result + ' )\n\n' + +def process_cmake_template_segment(segment, segment_ct, cmake_path, variables): + prefix = None + library = None + set = None + includes = [] + suffix = '_SRCS' # Appended to each group name before the platform name. + platform_sep = ':' # Used to separate value from platform name. + append_macro = 'APPEND_PLATFORM_SOURCES' # CMake macro name. + + # Extract values from |segment|. Example |segment| contents: + # 'prefix': 'cefsimple', + # 'includes': [ + # 'cefsimple_sources_common', + # 'cefsimple_sources_win:WINDOWS', + # 'cefsimple_sources_mac:MACOSX', + # 'cefsimple_sources_linux:LINUX', + # ], + values = eval('{' + segment + '}', {'__builtins__': None}, None) + if 'prefix' in values: + prefix = values['prefix'] + else: + raise Exception('Missing prefix value in segment %d' % segment_ct) + + if 'library' in values: + library = values['library'] + + if 'set' in values: + set = values['set'] + + if 'append_macro' in values: + append_macro = values['append_macro'] + + if 'includes' in values and len(values['includes']) > 0: + for include in values['includes']: + parts = include.strip().split(platform_sep) + files = get_files_for_variable(cmake_path, variables, parts[0]) + if len(parts) == 2: + # Append the platform to each file path. + files = [file + platform_sep + parts[1] for file in files] + includes.extend(files) + else: + raise Exception('Missing includes value in segment %d' % segment_ct) + + # Sort the file paths alphabetically. + includes.sort() + + # Group files by path. + # For example, '../include/base/foo.h' and '../include/base/bar.h' will be + # grouped as 'PREFIX_INCLUDE_BASE'. + groups = {} + for include in includes: + paths = include.split('/') + label = prefix + for path in paths[0:-1]: + if path == '..': + continue + label += '_' + path + label = label.replace('.', '_').upper() + if not label in groups: + groups[label] = [] + groups[label].append(include) + + # Create the output results. + result = '' + + keys = sorted(groups.keys()) + for key in keys: + # Add a group of files that share the same path. + result += format_cmake_group(cmake_path, key + suffix, groups[key], \ + platform_sep, append_macro) + + if not library is None: + # Add the library declaration if requested. + result += format_cmake_library(library, [key + suffix for key in keys]) + + if not set is None: + # Add the set declaration if requested. + result += format_cmake_set(set, \ + ['${' + key + suffix + '}' for key in keys]) + + return result.strip() + +def process_cmake_template(input, output, variables, quiet = False): + """ Reads the |input| template, parses variable substitution sections and + writes |output|. """ + if not quiet: + sys.stdout.write('Processing "%s" to "%s"...\n' % (input, output)) + + if not os.path.exists(input): + raise Exception('File %s does not exist' % input) + + cmake_path = normalize_path(os.path.abspath(input)) + template = read_file(cmake_path) + + delim_start = '{{' + delim_end = '}}' + + # Process the template file, replacing segments delimited by |delim_start| + # and |delim_end|. + result = '' + end = 0 + segment_ct = 0 + while True: + start = template.find(delim_start, end) + if start == -1: + break + result += template[end:start] + end = template.find(delim_end, start + len(delim_start)) + if end == -1: + break + segment = template[start + len(delim_start):end] + segment_ct = segment_ct + 1 + result += process_cmake_template_segment(segment, segment_ct, \ + cmake_path, variables) + end += len(delim_end) + result += template[end:] + + # Only write the output file if the contents have changed. + changed = True + if os.path.exists(output): + existing = read_file(output) + changed = result != existing + if changed: + write_file(output, result) + +def read_gypi_variables(source): + """ Read the |source| gypi file and extract the variables section. """ + path = os.path.join(cef_dir, source + '.gypi') + if not os.path.exists(path): + raise Exception('File %s does not exist' % path) + contents = eval_file(path) + if not 'variables' in contents: + raise Exception('File %s does not have a variables section' % path) + return contents['variables'] + +# File entry point. +if __name__ == "__main__": + # Verify that the correct number of command-line arguments are provided. + if len(sys.argv) != 3: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # Read the gypi files and combine into a single dictionary. + variables1 = read_gypi_variables('cef_paths') + variables2 = read_gypi_variables('cef_paths2') + variables = dict(variables1.items() + variables2.items()) + + # Process the cmake template. + process_cmake_template(sys.argv[1], sys.argv[2], variables) diff --git a/tools/make_cppdocs.bat b/tools/make_cppdocs.bat new file mode 100644 index 000000000..279436074 --- /dev/null +++ b/tools/make_cppdocs.bat @@ -0,0 +1,18 @@ +@echo off +setlocal + +if "%1"=="" ( +set CPPDOC_EXE="C:\Program Files (x86)\richfeit\CppDoc\CppDoc.exe" +set CPPDOC_REV="XXX" +) else ( +set CPPDOC_EXE="C:\Program Files (x86)\richfeit\CppDoc\cppdoc_cmd.exe" +set CPPDOC_REV="%1" +) + +if not exist %CPPDOC_EXE% ( +echo ERROR: Please install CppDoc from http://www.cppdoc.com/ +) else ( +%CPPDOC_EXE% -overwrite -title="CEF3 C++ API Docs - Revision %CPPDOC_REV%" -footer="
Chromium Embedded Framework (CEF) Copyright © 2012 Marshall A. Greenblatt
" -namespace-as-project -comment-format="///;//;///" -classdir=projects -module="cppdoc-standard" -extensions=h -languages="c=cpp,cc=cpp,cpp=cpp,cs=csharp,cxx=cpp,h=cpp,hpp=cpp,hxx=cpp,java=java" -D"OS_WIN" -D"USING_CEF_SHARED" -D"__cplusplus" -D"CEF_STRING_TYPE_UTF16" -enable-author=false -enable-deprecations=true -enable-since=true -enable-version=false -file-links-for-globals=false -generate-deprecations-list=false -generate-hierarchy=true -header-background-dark="#ccccff" -header-background-light="#eeeeff" -include-private=false -include-protected=true -index-file-base=index -overview-html=overview.html -reduce-summary-font=true -selected-text-background=navy -selected-text-foreground=white -separate-index-pages=false -show-cppdoc-version=false -show-timestamp=false -summary-html=project.html -suppress-details=false -suppress-frames-links=false -table-background=white -wrap-long-lines=false ..\include #cef_runnable.h #cef_tuple.h #capi "..\docs\index.html" +) + +endlocal \ No newline at end of file diff --git a/tools/make_cpptoc_header.py b/tools/make_cpptoc_header.py new file mode 100644 index 000000000..2bf5a5f6d --- /dev/null +++ b/tools/make_cpptoc_header.py @@ -0,0 +1,105 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from cef_parser import * + +def make_cpptoc_header(header, clsname): + cls = header.get_class(clsname) + if cls is None: + raise Exception('Class does not exist: '+clsname) + + dllside = cls.is_library_side() + defname = string.upper(get_capi_name(clsname[3:], False)) + capiname = cls.get_capi_name() + + result = get_copyright() + + result += '#ifndef CEF_LIBCEF_DLL_CPPTOC_'+defname+'_CPPTOC_H_\n'+ \ + '#define CEF_LIBCEF_DLL_CPPTOC_'+defname+'_CPPTOC_H_\n' + \ + '#pragma once\n' + + if dllside: + result += """ +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED +""" + else: + result += """ +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED +""" + + # include the headers for this class + result += '\n#include "include/'+cls.get_file_name()+'"\n' \ + '#include "include/capi/'+cls.get_capi_file_name()+'"\n' + + # include headers for any forward declared classes that are not in the same file + declares = cls.get_forward_declares() + for declare in declares: + dcls = header.get_class(declare) + if dcls.get_file_name() != cls.get_file_name(): + result += '#include "include/'+dcls.get_file_name()+'"\n' \ + '#include "include/capi/'+dcls.get_capi_file_name()+'"\n' + + result += """#include "libcef_dll/cpptoc/cpptoc.h" + +// Wrap a C++ class with a C structure. +""" + + if dllside: + result += '// This class may be instantiated and accessed DLL-side only.\n' + else: + result += '// This class may be instantiated and accessed wrapper-side only.\n' + + result += 'class '+clsname+'CppToC\n'+ \ + ' : public CefCppToC<'+clsname+'CppToC, '+clsname+', '+capiname+'> {\n'+ \ + ' public:\n'+ \ + ' explicit '+clsname+'CppToC('+clsname+'* cls);\n'+ \ + '};\n\n' + + if dllside: + result += '#endif // BUILDING_CEF_SHARED\n' + else: + result += '#endif // USING_CEF_SHARED\n' + + result += '#endif // CEF_LIBCEF_DLL_CPPTOC_'+defname+'_CPPTOC_H_\n' + + return wrap_code(result) + + +def write_cpptoc_header(header, clsname, dir, backup): + file = dir+os.sep+get_capi_name(clsname[3:], False)+'_cpptoc.h' + + if path_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + newcontents = make_cpptoc_header(header, clsname) + if newcontents != oldcontents: + if backup and oldcontents != '': + backup_file(file) + write_file(file, newcontents) + return True + + return False + + +# test the module +if __name__ == "__main__": + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) < 3: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # create the header object + header = obj_header() + header.add_file(sys.argv[1]) + + # dump the result to stdout + sys.stdout.write(make_cpptoc_header(header, sys.argv[2])) diff --git a/tools/make_cpptoc_impl.py b/tools/make_cpptoc_impl.py new file mode 100644 index 000000000..7d7f0aedb --- /dev/null +++ b/tools/make_cpptoc_impl.py @@ -0,0 +1,571 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from cef_parser import * + +def make_cpptoc_impl_proto(name, func, parts): + if isinstance(func, obj_function_virtual): + proto = parts['retval']+' CEF_CALLBACK' + else: + proto = 'CEF_EXPORT '+parts['retval'] + + proto += ' '+name+'('+string.join(parts['args'], ', ')+')' + return proto + +def make_cpptoc_function_impl_existing(name, func, impl, defined_names): + notify(name+' has manual edits') + + # retrieve the C API prototype parts + parts = func.get_capi_parts(defined_names) + + changes = format_translation_changes(impl, parts) + if len(changes) > 0: + notify(name+' prototype changed') + + return wrap_code(make_cpptoc_impl_proto(name, func, parts))+'{'+ \ + changes+impl['body']+'\n}\n' + return result + +def make_cpptoc_function_impl_new(name, func, defined_names): + # retrieve the C API prototype parts + parts = func.get_capi_parts(defined_names) + result = make_cpptoc_impl_proto(name, func, parts)+' {' + + invalid = [] + + # retrieve the function arguments + args = func.get_arguments() + + # determine the argument types + for arg in args: + if arg.get_arg_type() == 'invalid': + invalid.append(arg.get_name()) + + # retrieve the function return value + retval = func.get_retval() + retval_type = retval.get_retval_type() + if retval_type == 'invalid': + invalid.append('(return value)') + retval_default = '' + else: + retval_default = retval.get_retval_default(True) + if len(retval_default) > 0: + retval_default = ' '+retval_default; + + if len(invalid) > 0: + notify(name+' could not be autogenerated') + # code could not be auto-generated + result += '\n // BEGIN DELETE BEFORE MODIFYING' + result += '\n // AUTO-GENERATED CONTENT' + result += '\n // COULD NOT IMPLEMENT DUE TO: '+string.join(invalid, ', ') + result += '\n #pragma message("Warning: "__FILE__": '+name+' is not implemented")' + result += '\n // END DELETE BEFORE MODIFYING' + result += '\n}\n\n' + return wrap_code(result) + + result += '\n // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING\n' + + result_len = len(result) + + optional = [] + + # parameter verification + if isinstance(func, obj_function_virtual): + result += '\n DCHECK(self);'\ + '\n if (!self)'\ + '\n return'+retval_default+';' + + for arg in args: + arg_type = arg.get_arg_type() + arg_name = arg.get_type().get_name() + + # skip optional params + optional_params = arg.parent.get_attrib_list('optional_param') + if not optional_params is None and arg_name in optional_params: + optional.append(arg_name) + continue + + comment = '\n // Verify param: '+arg_name+'; type: '+arg_type + + if arg_type == 'simple_byref' or arg_type == 'simple_byref_const' or \ + arg_type == 'simple_byaddr' or arg_type == 'bool_byref' or arg_type == 'bool_byaddr' or \ + arg_type == 'struct_byref_const' or arg_type == 'struct_byref' or \ + arg_type == 'string_byref_const' or arg_type == 'string_byref' or \ + arg_type == 'refptr_same' or arg_type == 'refptr_same_byref' or \ + arg_type == 'refptr_diff' or arg_type == 'refptr_diff_byref' or \ + arg_type == 'string_vec_byref' or arg_type == 'string_vec_byref_const' or \ + arg_type == 'string_map_single_byref' or arg_type == 'string_map_single_byref_const' or \ + arg_type == 'string_map_multi_byref' or arg_type == 'string_map_multi_byref_const': + result += comment+\ + '\n DCHECK('+arg_name+');'\ + '\n if (!'+arg_name+')'\ + '\n return'+retval_default+';' + elif arg_type == 'simple_vec_byref' or arg_type == 'bool_vec_byref' or \ + arg_type == 'refptr_vec_same_byref' or arg_type == 'refptr_vec_diff_byref': + result += comment+\ + '\n DCHECK('+arg_name+'Count && (*'+arg_name+'Count == 0 || '+arg_name+'));'\ + '\n if (!'+arg_name+'Count || (*'+arg_name+'Count > 0 && !'+arg_name+'))'\ + '\n return'+retval_default+';' + elif arg_type == 'simple_vec_byref_const' or arg_type == 'bool_vec_byref_const' or \ + arg_type == 'refptr_vec_same_byref_const' or arg_type == 'refptr_vec_diff_byref_const': + result += comment+\ + '\n DCHECK('+arg_name+'Count == 0 || '+arg_name+');'\ + '\n if ('+arg_name+'Count > 0 && !'+arg_name+')'\ + '\n return'+retval_default+';' + + # check index params + index_params = arg.parent.get_attrib_list('index_param') + if not index_params is None and arg_name in index_params: + result += comment+\ + '\n DCHECK_GE('+arg_name+', 0);'\ + '\n if ('+arg_name+' < 0)'\ + '\n return'+retval_default+';' + + if len(optional) > 0: + # Wrap the comment at 80 characters. + str = '\n // Unverified params: ' + optional[0] + for name in optional[1:]: + str += ',' + if len(str) + len(name) + 1 > 80: + result += str + str = '\n //' + str += ' ' + name + result += str + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # parameter translation + params = [] + + for arg in args: + arg_type = arg.get_arg_type() + arg_name = arg.get_type().get_name() + + comment = '\n // Translate param: '+arg_name+'; type: '+arg_type + + if arg_type == 'simple_byval' or arg_type == 'simple_byaddr': + params.append(arg_name) + elif arg_type == 'simple_byref' or arg_type == 'simple_byref_const': + data_type = arg.get_type().get_type() + default = arg.get_type().get_result_simple_default() + result += comment+\ + '\n '+data_type+' '+arg_name+'Val = '+arg_name+'?*'+arg_name+':'+default+';' + params.append(arg_name+'Val') + elif arg_type == 'bool_byval': + params.append(arg_name+'?true:false') + elif arg_type == 'bool_byref' or arg_type == 'bool_byaddr': + result += comment+\ + '\n bool '+arg_name+'Bool = ('+arg_name+' && *'+arg_name+')?true:false;' + if arg_type == 'bool_byref': + params.append(arg_name+'Bool') + else: + params.append('&'+arg_name+'Bool') + elif arg_type == 'struct_byref_const': + struct_type = arg.get_type().get_type() + result += comment+\ + '\n '+struct_type+' '+arg_name+'Obj;'\ + '\n if ('+arg_name+')'\ + '\n '+arg_name+'Obj.Set(*'+arg_name+', false);' + params.append(arg_name+'Obj') + elif arg_type == 'struct_byref': + struct_type = arg.get_type().get_type() + result += comment+\ + '\n '+struct_type+' '+arg_name+'Obj;'\ + '\n if ('+arg_name+')'\ + '\n '+arg_name+'Obj.AttachTo(*'+arg_name+');' + params.append(arg_name+'Obj') + elif arg_type == 'string_byref_const': + params.append('CefString('+arg_name+')') + elif arg_type == 'string_byref': + result += comment+\ + '\n CefString '+arg_name+'Str('+arg_name+');' + params.append(arg_name+'Str') + elif arg_type == 'refptr_same' or arg_type == 'refptr_diff': + refptr_class = arg.get_type().get_refptr_type() + if arg_type == 'refptr_same': + params.append(refptr_class+'CppToC::Unwrap('+arg_name+')') + else: + params.append(refptr_class+'CToCpp::Wrap('+arg_name+')') + elif arg_type == 'refptr_same_byref' or arg_type == 'refptr_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + if arg_type == 'refptr_same_byref': + assign = refptr_class+'CppToC::Unwrap(*'+arg_name+')' + else: + assign = refptr_class+'CToCpp::Wrap(*'+arg_name+')' + result += comment+\ + '\n CefRefPtr<'+refptr_class+'> '+arg_name+'Ptr;'\ + '\n if ('+arg_name+' && *'+arg_name+')'\ + '\n '+arg_name+'Ptr = '+assign+';'\ + '\n '+refptr_class+'* '+arg_name+'Orig = '+arg_name+'Ptr.get();' + params.append(arg_name+'Ptr') + elif arg_type == 'string_vec_byref' or arg_type == 'string_vec_byref_const': + result += comment+\ + '\n std::vector '+arg_name+'List;'\ + '\n transfer_string_list_contents('+arg_name+', '+arg_name+'List);' + params.append(arg_name+'List') + elif arg_type == 'string_map_single_byref' or arg_type == 'string_map_single_byref_const': + result += comment+\ + '\n std::map '+arg_name+'Map;'\ + '\n transfer_string_map_contents('+arg_name+', '+arg_name+'Map);' + params.append(arg_name+'Map') + elif arg_type == 'string_map_multi_byref' or arg_type == 'string_map_multi_byref_const': + result += comment+\ + '\n std::multimap '+arg_name+'Multimap;'\ + '\n transfer_string_multimap_contents('+arg_name+', '+arg_name+'Multimap);' + params.append(arg_name+'Multimap') + elif arg_type == 'simple_vec_byref' or arg_type == 'bool_vec_byref' or \ + arg_type == 'refptr_vec_same_byref' or arg_type == 'refptr_vec_diff_byref': + vec_type = arg.get_type().get_vector_type() + if arg_type == 'simple_vec_byref': + assign = arg_name+'[i]' + elif arg_type == 'bool_vec_byref': + assign = arg_name+'[i]?true:false' + elif arg_type == 'refptr_vec_same_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CppToC::Unwrap('+arg_name+'[i])' + elif arg_type == 'refptr_vec_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CToCpp::Wrap('+arg_name+'[i])' + result += comment+\ + '\n std::vector<'+vec_type+' > '+arg_name+'List;'\ + '\n if ('+arg_name+'Count && *'+arg_name+'Count > 0 && '+arg_name+') {'\ + '\n for (size_t i = 0; i < *'+arg_name+'Count; ++i) {'\ + '\n '+arg_name+'List.push_back('+assign+');'\ + '\n }'\ + '\n }' + params.append(arg_name+'List') + elif arg_type == 'simple_vec_byref_const' or arg_type == 'bool_vec_byref_const' or \ + arg_type == 'refptr_vec_same_byref_const' or arg_type == 'refptr_vec_diff_byref_const': + vec_type = arg.get_type().get_vector_type() + if arg_type == 'simple_vec_byref_const': + assign = arg_name+'[i]' + elif arg_type == 'bool_vec_byref_const': + assign = arg_name+'[i]?true:false' + elif arg_type == 'refptr_vec_same_byref_const': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CppToC::Unwrap('+arg_name+'[i])' + elif arg_type == 'refptr_vec_diff_byref_const': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CToCpp::Wrap('+arg_name+'[i])' + result += comment+\ + '\n std::vector<'+vec_type+' > '+arg_name+'List;'\ + '\n if ('+arg_name+'Count > 0) {'\ + '\n for (size_t i = 0; i < '+arg_name+'Count; ++i) {'\ + '\n '+arg_name+'List.push_back('+assign+');'\ + '\n }'\ + '\n }' + params.append(arg_name+'List') + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # execution + result += '\n // Execute\n ' + + if retval_type != 'none': + # has a return value + if retval_type == 'simple': + result += retval.get_type().get_result_simple_type() + else: + result += retval.get_type().get_type() + result += ' _retval = ' + + if isinstance(func.parent, obj_class): + # virtual and static class methods + if isinstance(func, obj_function_virtual): + result += func.parent.get_name()+'CppToC::Get(self)->' + else: + result += func.parent.get_name()+'::' + result += func.get_name()+'(' + + if len(params) > 0: + result += '\n '+string.join(params,',\n ') + + result += ');\n' + + result_len = len(result) + + # parameter restoration + for arg in args: + arg_type = arg.get_arg_type() + arg_name = arg.get_type().get_name() + + comment = '\n // Restore param: '+arg_name+'; type: '+arg_type + + if arg_type == 'simple_byref': + result += comment+\ + '\n if ('+arg_name+')'\ + '\n *'+arg_name+' = '+arg_name+'Val;' + elif arg_type == 'bool_byref' or arg_type == 'bool_byaddr': + result += comment+\ + '\n if ('+arg_name+')'\ + '\n *'+arg_name+' = '+arg_name+'Bool?true:false;' + elif arg_type == 'struct_byref': + result += comment+\ + '\n if ('+arg_name+')'\ + '\n '+arg_name+'Obj.DetachTo(*'+arg_name+');' + elif arg_type == 'refptr_same_byref' or arg_type == 'refptr_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + if arg_type == 'refptr_same_byref': + assign = refptr_class+'CppToC::Wrap('+arg_name+'Ptr)' + else: + assign = refptr_class+'CToCpp::Unwrap('+arg_name+'Ptr)' + result += comment+\ + '\n if ('+arg_name+') {'\ + '\n if ('+arg_name+'Ptr.get()) {'\ + '\n if ('+arg_name+'Ptr.get() != '+arg_name+'Orig) {'\ + '\n *'+arg_name+' = '+assign+';'\ + '\n }'\ + '\n } else {'\ + '\n *'+arg_name+' = NULL;'\ + '\n }'\ + '\n }' + elif arg_type == 'string_vec_byref': + result += comment+\ + '\n cef_string_list_clear('+arg_name+');'\ + '\n transfer_string_list_contents('+arg_name+'List, '+arg_name+');' + elif arg_type == 'string_map_single_byref': + result += comment+\ + '\n cef_string_map_clear('+arg_name+');'\ + '\n transfer_string_map_contents('+arg_name+'Map, '+arg_name+');' + elif arg_type == 'string_map_multi_byref': + result += comment+\ + '\n cef_string_multimap_clear('+arg_name+');'\ + '\n transfer_string_multimap_contents('+arg_name+'Multimap, '+arg_name+');' + elif arg_type == 'simple_vec_byref' or arg_type == 'bool_vec_byref' or \ + arg_type == 'refptr_vec_same_byref' or arg_type == 'refptr_vec_diff_byref': + if arg_type == 'simple_vec_byref' or arg_type == 'bool_vec_byref': + assign = arg_name+'List[i]' + elif arg_type == 'refptr_vec_same_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CppToC::Wrap('+arg_name+'List[i])' + elif arg_type == 'refptr_vec_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CToCpp::Unwrap('+arg_name+'List[i])' + result += comment+\ + '\n if ('+arg_name+'Count && '+arg_name+') {'\ + '\n *'+arg_name+'Count = std::min('+arg_name+'List.size(), *'+arg_name+'Count);'\ + '\n if (*'+arg_name+'Count > 0) {'\ + '\n for (size_t i = 0; i < *'+arg_name+'Count; ++i) {'\ + '\n '+arg_name+'[i] = '+assign+';'\ + '\n }'\ + '\n }'\ + '\n }' + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # special handling for the global cef_shutdown function + if name == 'cef_shutdown' and isinstance(func.parent, obj_header): + classes = func.parent.get_classes() + + names = [] + for cls in classes: + if cls.has_attrib('no_debugct_check'): + continue; + + if cls.is_library_side(): + names.append(cls.get_name()+'CppToC') + else: + names.append(cls.get_name()+'CToCpp') + + if len(names) > 0: + names = sorted(names) + result += '\n#ifndef NDEBUG'\ + '\n // Check that all wrapper objects have been destroyed' + for name in names: + result += '\n DCHECK(base::AtomicRefCountIsZero(&'+name+'::DebugObjCt));'; + result += '\n#endif // !NDEBUG' + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # return translation + if retval_type != 'none': + # has a return value + result += '\n // Return type: '+retval_type + if retval_type == 'simple' or retval_type == 'bool': + result += '\n return _retval;' + elif retval_type == 'string': + result += '\n return _retval.DetachToUserFree();' + elif retval_type == 'refptr_same': + refptr_class = retval.get_type().get_refptr_type() + result += '\n return '+refptr_class+'CppToC::Wrap(_retval);' + elif retval_type == 'refptr_diff': + refptr_class = retval.get_type().get_refptr_type() + result += '\n return '+refptr_class+'CToCpp::Unwrap(_retval);' + + if len(result) != result_len: + result += '\n' + + result += '}\n' + return wrap_code(result) + +def make_cpptoc_function_impl(funcs, existing, prefixname, defined_names): + impl = '' + + for func in funcs: + if not prefixname is None: + name = prefixname+'_'+func.get_capi_name() + else: + name = func.get_capi_name() + value = get_next_function_impl(existing, name) + if not value is None \ + and value['body'].find('// AUTO-GENERATED CONTENT') < 0: + # an implementation exists that was not auto-generated + impl += make_cpptoc_function_impl_existing(name, func, value, defined_names) + else: + impl += make_cpptoc_function_impl_new(name, func, defined_names) + + return impl + +def make_cpptoc_class_impl(header, clsname, impl): + # structure names that have already been defined + defined_names = header.get_defined_structs() + + # retrieve the class and populate the defined names + cls = header.get_class(clsname, defined_names) + if cls is None: + raise Exception('Class does not exist: '+clsname) + + capiname = cls.get_capi_name() + prefixname = get_capi_name(clsname[3:], False) + + # retrieve the existing virtual function implementations + existing = get_function_impls(impl, 'CEF_CALLBACK') + + # generate virtual functions + virtualimpl = make_cpptoc_function_impl(cls.get_virtual_funcs(), existing, prefixname, defined_names) + if len(virtualimpl) > 0: + virtualimpl = '\n// MEMBER FUNCTIONS - Body may be edited by hand.\n\n'+virtualimpl + + # the current class is already defined for static functions + defined_names.append(cls.get_capi_name()) + + # retrieve the existing static function implementations + existing = get_function_impls(impl, 'CEF_EXPORT') + + # generate static functions + staticimpl = make_cpptoc_function_impl(cls.get_static_funcs(), existing, None, defined_names) + if len(staticimpl) > 0: + staticimpl = '\n// GLOBAL FUNCTIONS - Body may be edited by hand.\n\n'+staticimpl + + resultingimpl = staticimpl + virtualimpl + + # determine what includes are required by identifying what translation + # classes are being used + includes = format_translation_includes(resultingimpl) + + # build the final output + result = get_copyright() + + result += includes+'\n'+resultingimpl+'\n' + + const = '// CONSTRUCTOR - Do not edit by hand.\n\n'+ \ + clsname+'CppToC::'+clsname+'CppToC('+clsname+'* cls)\n'+ \ + ' : CefCppToC<'+clsname+'CppToC, '+clsname+', '+capiname+'>(cls) '+ \ + '{\n'; + + funcs = cls.get_virtual_funcs() + for func in funcs: + name = func.get_capi_name() + const += ' struct_.struct_.'+name+' = '+prefixname+'_'+name+';\n' + + const += '}\n\n'+ \ + '#ifndef NDEBUG\n'+ \ + 'template<> base::AtomicRefCount CefCppToC<'+clsname+'CppToC, '+clsname+', '+capiname+'>::DebugObjCt = 0;\n'+ \ + '#endif\n' + result += wrap_code(const) + + return result + +def make_cpptoc_global_impl(header, impl): + # structure names that have already been defined + defined_names = header.get_defined_structs() + + # retrieve the existing global function implementations + existing = get_function_impls(impl, 'CEF_EXPORT') + + # generate global functions + impl = make_cpptoc_function_impl(header.get_funcs(), existing, None, defined_names) + if len(impl) > 0: + impl = '\n// GLOBAL FUNCTIONS - Body may be edited by hand.\n\n'+impl + + includes = '' + + # include required headers for global functions + filenames = [] + for func in header.get_funcs(): + filename = func.get_file_name() + if not filename in filenames: + includes += '#include "include/'+func.get_file_name()+'"\n' \ + '#include "include/capi/'+func.get_capi_file_name()+'"\n' + filenames.append(filename) + + # determine what includes are required by identifying what translation + # classes are being used + includes += format_translation_includes(impl) + + # build the final output + result = get_copyright() + + result += includes+'\n'+impl + + return result + +def write_cpptoc_impl(header, clsname, dir, backup): + if clsname is None: + # global file + file = dir + else: + # class file + file = dir+os.sep+get_capi_name(clsname[3:], False)+'_cpptoc.cc' + + if path_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + if clsname is None: + newcontents = make_cpptoc_global_impl(header, oldcontents) + else: + newcontents = make_cpptoc_class_impl(header, clsname, oldcontents) + if newcontents != oldcontents: + if backup and oldcontents != '': + backup_file(file) + write_file(file, newcontents) + return True + + return False + + +# test the module +if __name__ == "__main__": + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) < 4: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # create the header object + header = obj_header() + header.add_file(sys.argv[1]) + + # read the existing implementation file into memory + try: + f = open(sys.argv[3], 'r') + data = f.read() + except IOError, (errno, strerror): + raise Exception('Failed to read file '+sys.argv[3]+': '+strerror) + else: + f.close() + + # dump the result to stdout + sys.stdout.write(make_cpptoc_class_impl(header, sys.argv[2], data)) diff --git a/tools/make_ctocpp_header.py b/tools/make_ctocpp_header.py new file mode 100644 index 000000000..ac352b7a6 --- /dev/null +++ b/tools/make_ctocpp_header.py @@ -0,0 +1,124 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from cef_parser import * + +def make_ctocpp_header(header, clsname): + cls = header.get_class(clsname) + if cls is None: + raise Exception('Class does not exist: '+clsname) + + clientside = cls.is_client_side() + defname = string.upper(get_capi_name(clsname[3:], False)) + capiname = cls.get_capi_name() + + result = get_copyright() + + result += '#ifndef CEF_LIBCEF_DLL_CTOCPP_'+defname+'_CTOCPP_H_\n'+ \ + '#define CEF_LIBCEF_DLL_CTOCPP_'+defname+'_CTOCPP_H_\n' + \ + '#pragma once\n' + + if clientside: + result += """ +#ifndef BUILDING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed DLL-side only") +#else // BUILDING_CEF_SHARED +""" + else: + result += """ +#ifndef USING_CEF_SHARED +#pragma message("Warning: "__FILE__" may be accessed wrapper-side only") +#else // USING_CEF_SHARED +""" + + # build the function body + func_body = '' + funcs = cls.get_virtual_funcs() + for func in funcs: + if clientside: + func_body += ' '+func.get_cpp_proto()+' override;\n' + else: + func_body += ' virtual '+func.get_cpp_proto()+' OVERRIDE;\n' + + # include standard headers + if func_body.find('std::map') > 0 or func_body.find('std::multimap') > 0: + result += '\n#include ' + if func_body.find('std::vector') > 0: + result += '\n#include ' + + # include the headers for this class + result += '\n#include "include/'+cls.get_file_name()+'"'+ \ + '\n#include "include/capi/'+cls.get_capi_file_name()+'"\n' + + # include headers for any forward declared classes that are not in the same file + declares = cls.get_forward_declares() + for declare in declares: + dcls = header.get_class(declare) + if dcls.get_file_name() != cls.get_file_name(): + result += '#include "include/'+dcls.get_file_name()+'"\n' \ + '#include "include/capi/'+dcls.get_capi_file_name()+'"\n' + + result += """#include "libcef_dll/ctocpp/ctocpp.h" + +// Wrap a C structure with a C++ class. +""" + + if clientside: + result += '// This class may be instantiated and accessed DLL-side only.\n' + else: + result += '// This class may be instantiated and accessed wrapper-side only.\n' + + result += 'class '+clsname+'CToCpp\n'+ \ + ' : public CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'> {\n'+ \ + ' public:\n'+ \ + ' explicit '+clsname+'CToCpp('+capiname+'* str)\n'+ \ + ' : CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'>(str) {}\n\n'+ \ + ' // '+clsname+' methods\n'; + + result += func_body + result += '};\n\n' + + if clientside: + result += '#endif // BUILDING_CEF_SHARED\n' + else: + result += '#endif // USING_CEF_SHARED\n' + + result += '#endif // CEF_LIBCEF_DLL_CTOCPP_'+defname+'_CTOCPP_H_\n' + + return wrap_code(result) + + +def write_ctocpp_header(header, clsname, dir, backup): + file = dir+os.sep+get_capi_name(clsname[3:], False)+'_ctocpp.h' + + if path_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + newcontents = make_ctocpp_header(header, clsname) + if newcontents != oldcontents: + if backup and oldcontents != '': + backup_file(file) + write_file(file, newcontents) + return True + + return False + + +# test the module +if __name__ == "__main__": + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) < 3: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # create the header object + header = obj_header() + header.add_file(sys.argv[1]) + + # dump the result to stdout + sys.stdout.write(make_ctocpp_header(header, sys.argv[2])) diff --git a/tools/make_ctocpp_impl.py b/tools/make_ctocpp_impl.py new file mode 100644 index 000000000..1d109fb7c --- /dev/null +++ b/tools/make_ctocpp_impl.py @@ -0,0 +1,584 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from cef_parser import * + +def make_ctocpp_impl_proto(clsname, name, func, parts): + const = '' + + if clsname is None: + proto = 'CEF_GLOBAL '+parts['retval']+' ' + else: + proto = parts['retval']+' '+clsname + if isinstance(func, obj_function_virtual): + proto += 'CToCpp' + if func.is_const(): + const = ' const' + + proto += '::' + + proto += name+'('+string.join(parts['args'], ', ')+')'+const + return proto + +def make_ctocpp_function_impl_existing(clsname, name, func, impl): + notify(name+' has manual edits') + + # retrieve the C++ prototype parts + parts = func.get_cpp_parts(True) + + changes = format_translation_changes(impl, parts) + if len(changes) > 0: + notify(name+' prototype changed') + + return wrap_code(make_ctocpp_impl_proto(clsname, name, func, parts))+'{'+ \ + changes+impl['body']+'\n}\n' + +def make_ctocpp_function_impl_new(clsname, name, func): + # build the C++ prototype + parts = func.get_cpp_parts(True) + result = make_ctocpp_impl_proto(clsname, name, func, parts)+' {' + + invalid = [] + + # retrieve the function arguments + args = func.get_arguments() + + # determine the argument types + for arg in args: + if arg.get_arg_type() == 'invalid': + invalid.append(arg.get_name()) + + # retrieve the function return value + retval = func.get_retval() + retval_type = retval.get_retval_type() + if retval_type == 'invalid': + invalid.append('(return value)') + retval_default = '' + else: + retval_default = retval.get_retval_default(False) + if len(retval_default) > 0: + retval_default = ' '+retval_default; + + # add API hash check + if func.has_attrib('api_hash_check'): + result += '\n const char* api_hash = cef_api_hash(0);'\ + '\n if (strcmp(api_hash, CEF_API_HASH_PLATFORM)) {'\ + '\n // The libcef API hash does not match the current header API hash.'\ + '\n NOTREACHED();'\ + '\n return'+retval_default+';'\ + '\n }\n' + + if isinstance(func, obj_function_virtual): + # add the structure size check + result += '\n if (CEF_MEMBER_MISSING(struct_, '+func.get_capi_name()+'))' + result += '\n return'+retval_default+';\n' + + if len(invalid) > 0: + notify(name+' could not be autogenerated') + # code could not be auto-generated + result += '\n // BEGIN DELETE BEFORE MODIFYING' + result += '\n // AUTO-GENERATED CONTENT' + result += '\n // COULD NOT IMPLEMENT DUE TO: '+string.join(invalid, ', ') + result += '\n #pragma message("Warning: "__FILE__": '+name+' is not implemented")' + result += '\n // END DELETE BEFORE MODIFYING' + result += '\n}\n\n' + return wrap_code(result) + + result += '\n // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING\n' + + result_len = len(result) + + optional = [] + + # parameter verification + for arg in args: + arg_type = arg.get_arg_type() + arg_name = arg.get_type().get_name() + + # skip optional params + optional_params = arg.parent.get_attrib_list('optional_param') + if not optional_params is None and arg_name in optional_params: + optional.append(arg_name) + continue + + comment = '\n // Verify param: '+arg_name+'; type: '+arg_type + + if arg_type == 'simple_byaddr' or arg_type == 'bool_byaddr': + result += comment+\ + '\n DCHECK('+arg_name+');'\ + '\n if (!'+arg_name+')'\ + '\n return'+retval_default+';' + elif arg_type == 'refptr_same' or arg_type == 'refptr_diff': + result += comment+\ + '\n DCHECK('+arg_name+'.get());'\ + '\n if (!'+arg_name+'.get())'\ + '\n return'+retval_default+';' + elif arg_type == 'string_byref_const': + result += comment+\ + '\n DCHECK(!'+arg_name+'.empty());'\ + '\n if ('+arg_name+'.empty())'\ + '\n return'+retval_default+';' + + # check index params + index_params = arg.parent.get_attrib_list('index_param') + if not index_params is None and arg_name in index_params: + result += comment+\ + '\n DCHECK_GE('+arg_name+', 0);'\ + '\n if ('+arg_name+' < 0)'\ + '\n return'+retval_default+';' + + if len(optional) > 0: + # Wrap the comment at 80 characters. + str = '\n // Unverified params: ' + optional[0] + for name in optional[1:]: + str += ',' + if len(str) + len(name) + 1 > 80: + result += str + str = '\n //' + str += ' ' + name + result += str + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # parameter translation + params = [] + if isinstance(func, obj_function_virtual): + params.append('struct_') + + for arg in args: + arg_type = arg.get_arg_type() + arg_name = arg.get_type().get_name() + + comment = '\n // Translate param: '+arg_name+'; type: '+arg_type + + if arg_type == 'simple_byval' or arg_type == 'simple_byaddr' or \ + arg_type == 'bool_byval': + params.append(arg_name) + elif arg_type == 'simple_byref' or arg_type == 'simple_byref_const' or \ + arg_type == 'struct_byref_const' or arg_type == 'struct_byref': + params.append('&'+arg_name) + elif arg_type == 'bool_byref': + result += comment+\ + '\n int '+arg_name+'Int = '+arg_name+';' + params.append('&'+arg_name+'Int') + elif arg_type == 'bool_byaddr': + result += comment+\ + '\n int '+arg_name+'Int = '+arg_name+'?*'+arg_name+':0;' + params.append('&'+arg_name+'Int') + elif arg_type == 'string_byref_const': + params.append(arg_name+'.GetStruct()') + elif arg_type == 'string_byref': + params.append(arg_name+'.GetWritableStruct()') + elif arg_type == 'refptr_same': + refptr_class = arg.get_type().get_refptr_type() + params.append(refptr_class+'CToCpp::Unwrap('+arg_name+')') + elif arg_type == 'refptr_diff': + refptr_class = arg.get_type().get_refptr_type() + params.append(refptr_class+'CppToC::Wrap('+arg_name+')') + elif arg_type == 'refptr_same_byref' or arg_type == 'refptr_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + refptr_struct = arg.get_type().get_result_refptr_type_root() + if arg_type == 'refptr_same_byref': + assign = refptr_class+'CToCpp::Unwrap('+arg_name+')' + else: + assign = refptr_class+'CppToC::Wrap('+arg_name+')' + result += comment+\ + '\n '+refptr_struct+'* '+arg_name+'Struct = NULL;'\ + '\n if ('+arg_name+'.get())'\ + '\n '+arg_name+'Struct = '+assign+';'\ + '\n '+refptr_struct+'* '+arg_name+'Orig = '+arg_name+'Struct;' + params.append('&'+arg_name+'Struct') + elif arg_type == 'string_vec_byref' or arg_type == 'string_vec_byref_const': + result += comment+\ + '\n cef_string_list_t '+arg_name+'List = cef_string_list_alloc();'\ + '\n DCHECK('+arg_name+'List);'\ + '\n if ('+arg_name+'List)'\ + '\n transfer_string_list_contents('+arg_name+', '+arg_name+'List);' + params.append(arg_name+'List') + elif arg_type == 'string_map_single_byref' or arg_type == 'string_map_single_byref_const': + result += comment+\ + '\n cef_string_map_t '+arg_name+'Map = cef_string_map_alloc();'\ + '\n DCHECK('+arg_name+'Map);'\ + '\n if ('+arg_name+'Map)'\ + '\n transfer_string_map_contents('+arg_name+', '+arg_name+'Map);' + params.append(arg_name+'Map') + elif arg_type == 'string_map_multi_byref' or arg_type == 'string_map_multi_byref_const': + result += comment+\ + '\n cef_string_multimap_t '+arg_name+'Multimap = cef_string_multimap_alloc();'\ + '\n DCHECK('+arg_name+'Multimap);'\ + '\n if ('+arg_name+'Multimap)'\ + '\n transfer_string_multimap_contents('+arg_name+', '+arg_name+'Multimap);' + params.append(arg_name+'Multimap') + elif arg_type == 'simple_vec_byref' or arg_type == 'bool_vec_byref' or \ + arg_type == 'refptr_vec_same_byref' or arg_type == 'refptr_vec_diff_byref': + count_func = arg.get_attrib_count_func() + vec_type = arg.get_type().get_result_vector_type_root() + if arg_type == 'refptr_vec_same_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CToCpp::Unwrap('+arg_name+'[i])' + elif arg_type == 'refptr_vec_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CppToC::Wrap('+arg_name+'[i])' + else: + assign = arg_name+'[i]' + result += comment+\ + '\n size_t '+arg_name+'Size = '+arg_name+'.size();'\ + '\n size_t '+arg_name+'Count = std::max('+count_func+'(), '+arg_name+'Size);'\ + '\n '+vec_type+'* '+arg_name+'List = NULL;'\ + '\n if ('+arg_name+'Count > 0) {'\ + '\n '+arg_name+'List = new '+vec_type+'['+arg_name+'Count];'\ + '\n DCHECK('+arg_name+'List);'\ + '\n if ('+arg_name+'List) {'\ + '\n memset('+arg_name+'List, 0, sizeof('+vec_type+')*'+arg_name+'Count);'\ + '\n }'\ + '\n if ('+arg_name+'List && '+arg_name+'Size > 0) {'\ + '\n for (size_t i = 0; i < '+arg_name+'Size; ++i) {'\ + '\n '+arg_name+'List[i] = '+assign+';'\ + '\n }'\ + '\n }'\ + '\n }' + params.append('&'+arg_name+'Count') + params.append(arg_name+'List') + elif arg_type == 'simple_vec_byref_const' or arg_type == 'bool_vec_byref_const' or \ + arg_type == 'refptr_vec_same_byref_const' or arg_type == 'refptr_vec_diff_byref_const': + count_func = arg.get_attrib_count_func() + vec_type = arg.get_type().get_result_vector_type_root() + if arg_type == 'refptr_vec_same_byref_const': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CToCpp::Unwrap('+arg_name+'[i])' + elif arg_type == 'refptr_vec_diff_byref_const': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CppToC::Wrap('+arg_name+'[i])' + else: + assign = arg_name+'[i]' + result += comment+\ + '\n const size_t '+arg_name+'Count = '+arg_name+'.size();'\ + '\n '+vec_type+'* '+arg_name+'List = NULL;'\ + '\n if ('+arg_name+'Count > 0) {'\ + '\n '+arg_name+'List = new '+vec_type+'['+arg_name+'Count];'\ + '\n DCHECK('+arg_name+'List);'\ + '\n if ('+arg_name+'List) {'\ + '\n for (size_t i = 0; i < '+arg_name+'Count; ++i) {'\ + '\n '+arg_name+'List[i] = '+assign+';'\ + '\n }'\ + '\n }'\ + '\n }' + params.append(arg_name+'Count') + params.append(arg_name+'List') + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # execution + result += '\n // Execute\n ' + + if retval_type != 'none': + # has a return value + if retval_type == 'simple' or retval_type == 'bool': + result += retval.get_type().get_result_simple_type_root() + elif retval_type == 'string': + result += 'cef_string_userfree_t' + elif retval_type == 'refptr_same' or retval_type == 'refptr_diff': + refptr_struct = retval.get_type().get_result_refptr_type_root() + result += refptr_struct+'*' + + result += ' _retval = ' + + if isinstance(func, obj_function_virtual): + result += 'struct_->' + result += func.get_capi_name()+'(' + + if len(params) > 0: + if not isinstance(func, obj_function_virtual): + result += '\n ' + result += string.join(params,',\n ') + + result += ');\n' + + result_len = len(result) + + # parameter restoration + for arg in args: + arg_type = arg.get_arg_type() + arg_name = arg.get_type().get_name() + + comment = '\n // Restore param:'+arg_name+'; type: '+arg_type + + if arg_type == 'bool_byref': + result += comment+\ + '\n '+arg_name+' = '+arg_name+'Int?true:false;' + elif arg_type == 'bool_byaddr': + result += comment+\ + '\n if ('+arg_name+')'\ + '\n *'+arg_name+' = '+arg_name+'Int?true:false;' + elif arg_type == 'refptr_same_byref' or arg_type == 'refptr_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + refptr_struct = arg.get_type().get_result_refptr_type_root() + if arg_type == 'refptr_same_byref': + assign = refptr_class+'CToCpp::Wrap('+arg_name+'Struct)' + else: + assign = refptr_class+'CppToC::Unwrap('+arg_name+'Struct)' + result += comment+\ + '\n if ('+arg_name+'Struct) {'\ + '\n if ('+arg_name+'Struct != '+arg_name+'Orig) {'\ + '\n '+arg_name+' = '+assign+';'\ + '\n }'\ + '\n } else {'\ + '\n '+arg_name+' = NULL;'\ + '\n }' + elif arg_type == 'string_vec_byref': + result += comment+\ + '\n if ('+arg_name+'List) {'\ + '\n '+arg_name+'.clear();'\ + '\n transfer_string_list_contents('+arg_name+'List, '+arg_name+');'\ + '\n cef_string_list_free('+arg_name+'List);'\ + '\n }' + elif arg_type == 'string_vec_byref_const': + result += comment+\ + '\n if ('+arg_name+'List)'\ + '\n cef_string_list_free('+arg_name+'List);' + elif arg_type == 'string_map_single_byref': + result += comment+\ + '\n if ('+arg_name+'Map) {'\ + '\n '+arg_name+'.clear();'\ + '\n transfer_string_map_contents('+arg_name+'Map, '+arg_name+');'\ + '\n cef_string_map_free('+arg_name+'Map);'\ + '\n }' + elif arg_type == 'string_map_single_byref_const': + result += comment+\ + '\n if ('+arg_name+'Map)'\ + '\n cef_string_map_free('+arg_name+'Map);' + elif arg_type == 'string_map_multi_byref': + result += comment+\ + '\n if ('+arg_name+'Multimap) {'\ + '\n '+arg_name+'.clear();'\ + '\n transfer_string_multimap_contents('+arg_name+'Multimap, '+arg_name+');'\ + '\n cef_string_multimap_free('+arg_name+'Multimap);'\ + '\n }' + elif arg_type == 'string_map_multi_byref_const': + result += comment+\ + '\n if ('+arg_name+'Multimap)'\ + '\n cef_string_multimap_free('+arg_name+'Multimap);' + elif arg_type == 'simple_vec_byref' or arg_type == 'bool_vec_byref' or \ + arg_type == 'refptr_vec_same_byref' or arg_type == 'refptr_vec_diff_byref': + count_func = arg.get_attrib_count_func() + vec_type = arg.get_type().get_result_vector_type_root() + if arg_type == 'refptr_vec_same_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CToCpp::Wrap('+arg_name+'List[i])' + elif arg_type == 'refptr_vec_diff_byref': + refptr_class = arg.get_type().get_refptr_type() + assign = refptr_class+'CppToC::Unwrap('+arg_name+'List[i])' + elif arg_type == 'bool_vec_byref': + assign = arg_name+'List[i]?true:false' + else: + assign = arg_name+'List[i]' + result += comment+\ + '\n '+arg_name+'.clear();'\ + '\n if ('+arg_name+'Count > 0 && '+arg_name+'List) {'\ + '\n for (size_t i = 0; i < '+arg_name+'Count; ++i) {'\ + '\n '+arg_name+'.push_back('+assign+');'\ + '\n }'\ + '\n delete [] '+arg_name+'List;'\ + '\n }' + elif arg_type == 'simple_vec_byref_const' or arg_type == 'bool_vec_byref_const' or \ + arg_type == 'refptr_vec_same_byref_const' or arg_type == 'refptr_vec_diff_byref_const': + result += comment+\ + '\n if ('+arg_name+'List)'\ + '\n delete [] '+arg_name+'List;' + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # special handling for the global CefShutdown function + if name == 'CefShutdown' and isinstance(func.parent, obj_header): + classes = func.parent.get_classes() + + names = [] + for cls in classes: + if cls.has_attrib('no_debugct_check'): + continue; + + if cls.is_library_side(): + names.append(cls.get_name()+'CToCpp') + else: + names.append(cls.get_name()+'CppToC') + + if len(names) > 0: + names = sorted(names) + result += '\n#ifndef NDEBUG'\ + '\n // Check that all wrapper objects have been destroyed' + for name in names: + result += '\n DCHECK(base::AtomicRefCountIsZero(&'+name+'::DebugObjCt));'; + result += '\n#endif // !NDEBUG' + + if len(result) != result_len: + result += '\n' + result_len = len(result) + + # return translation + if retval_type != 'none': + # has a return value + result += '\n // Return type: '+retval_type + if retval_type == 'simple': + result += '\n return _retval;' + elif retval_type == 'bool': + result += '\n return _retval?true:false;' + elif retval_type == 'string': + result += '\n CefString _retvalStr;'\ + '\n _retvalStr.AttachToUserFree(_retval);'\ + '\n return _retvalStr;' + elif retval_type == 'refptr_same': + refptr_class = retval.get_type().get_refptr_type() + result += '\n return '+refptr_class+'CToCpp::Wrap(_retval);' + elif retval_type == 'refptr_diff': + refptr_class = retval.get_type().get_refptr_type() + result += '\n return '+refptr_class+'CppToC::Unwrap(_retval);' + + if len(result) != result_len: + result += '\n' + + result += '}\n' + return wrap_code(result) + +def make_ctocpp_function_impl(clsname, funcs, existing): + impl = '' + + for func in funcs: + name = func.get_name() + value = get_next_function_impl(existing, name) + if not value is None \ + and value['body'].find('// AUTO-GENERATED CONTENT') < 0: + # an implementation exists that was not auto-generated + impl += make_ctocpp_function_impl_existing(clsname, name, func, value) + else: + impl += make_ctocpp_function_impl_new(clsname, name, func) + + return impl + +def make_ctocpp_class_impl(header, clsname, impl): + cls = header.get_class(clsname) + if cls is None: + raise Exception('Class does not exist: '+clsname) + + capiname = cls.get_capi_name() + + # retrieve the existing virtual function implementations + existing = get_function_impls(impl, clsname+'CToCpp::') + + # generate virtual functions + virtualimpl = make_ctocpp_function_impl(clsname, cls.get_virtual_funcs(), existing) + if len(virtualimpl) > 0: + virtualimpl = '\n// VIRTUAL METHODS - Body may be edited by hand.\n\n'+virtualimpl + + # retrieve the existing static function implementations + existing = get_function_impls(impl, clsname+'::') + + # generate static functions + staticimpl = make_ctocpp_function_impl(clsname, cls.get_static_funcs(), existing) + if len(staticimpl) > 0: + staticimpl = '\n// STATIC METHODS - Body may be edited by hand.\n\n'+staticimpl + + resultingimpl = staticimpl + virtualimpl + + # determine what includes are required by identifying what translation + # classes are being used + includes = format_translation_includes(resultingimpl) + + # build the final output + result = get_copyright() + + result += includes+'\n'+resultingimpl+'\n' + + result += wrap_code('#ifndef NDEBUG\n'+ \ + 'template<> base::AtomicRefCount CefCToCpp<'+clsname+'CToCpp, '+clsname+', '+capiname+'>::DebugObjCt = 0;\n'+ \ + '#endif\n') + + return result + +def make_ctocpp_global_impl(header, impl): + # retrieve the existing global function implementations + existing = get_function_impls(impl, 'CEF_GLOBAL') + + # generate static functions + impl = make_ctocpp_function_impl(None, header.get_funcs(), existing) + if len(impl) > 0: + impl = '\n// GLOBAL METHODS - Body may be edited by hand.\n\n'+impl + + includes = '' + + # include required headers for global functions + filenames = [] + for func in header.get_funcs(): + filename = func.get_file_name() + if not filename in filenames: + includes += '#include "include/'+func.get_file_name()+'"\n' \ + '#include "include/capi/'+func.get_capi_file_name()+'"\n' + filenames.append(filename) + + # determine what includes are required by identifying what translation + # classes are being used + includes += format_translation_includes(impl) + + # build the final output + result = get_copyright() + + result += includes+'\n// Define used to facilitate parsing.\n#define CEF_GLOBAL\n\n'+impl + + return result + +def write_ctocpp_impl(header, clsname, dir, backup): + if clsname is None: + # global file + file = dir + else: + # class file + file = dir+os.sep+get_capi_name(clsname[3:], False)+'_ctocpp.cc' + + if path_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + if clsname is None: + newcontents = make_ctocpp_global_impl(header, oldcontents) + else: + newcontents = make_ctocpp_class_impl(header, clsname, oldcontents) + if newcontents != oldcontents: + if backup and oldcontents != '': + backup_file(file) + write_file(file, newcontents) + return True + + return False + + +# test the module +if __name__ == "__main__": + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) < 4: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # create the header object + header = obj_header() + header.add_file(sys.argv[1]) + + # read the existing implementation file into memory + try: + f = open(sys.argv[3], 'r') + data = f.read() + except IOError, (errno, strerror): + raise Exception('Failed to read file '+sys.argv[3]+': '+strerror) + else: + f.close() + + # dump the result to stdout + sys.stdout.write(make_ctocpp_class_impl(header, sys.argv[2], data)) diff --git a/tools/make_distrib.bat b/tools/make_distrib.bat new file mode 100644 index 000000000..c92dc7a46 --- /dev/null +++ b/tools/make_distrib.bat @@ -0,0 +1,2 @@ +@echo off +python.bat make_distrib.py --output-dir ..\binary_distrib\ %* diff --git a/tools/make_distrib.py b/tools/make_distrib.py new file mode 100644 index 000000000..160917a1c --- /dev/null +++ b/tools/make_distrib.py @@ -0,0 +1,699 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from date_util import * +from file_util import * +from make_cmake import process_cmake_template +from optparse import OptionParser +import os +import re +import shlex +import subprocess +import svn_util as svn +import git_util as git +import sys +import zipfile + +def create_archive(input_dir, zip_file): + """ Creates a zip archive of the specified input directory. """ + zf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED, True) + def addDir(dir): + for f in os.listdir(dir): + full_path = os.path.join(dir, f) + if os.path.isdir(full_path): + addDir(full_path) + else: + zf.write(full_path, os.path.relpath(full_path, \ + os.path.join(input_dir, os.pardir))) + addDir(input_dir) + zf.close() + +def create_7z_archive(input_dir, zip_file): + """ Creates a 7z archive of the specified input directory. """ + command = os.environ['CEF_COMMAND_7ZIP'] + run('"' + command + '" a -y ' + zip_file + ' ' + input_dir, os.path.split(zip_file)[0]) + +def create_output_dir(name, parent_dir): + """ Creates an output directory and adds the path to the archive list. """ + output_dir = os.path.abspath(os.path.join(parent_dir, name)) + remove_dir(output_dir, options.quiet) + make_dir(output_dir, options.quiet) + archive_dirs.append(output_dir) + return output_dir + +def get_readme_component(name): + """ Loads a README file component. """ + paths = [] + # platform directory + if platform == 'windows': + platform_cmp = 'win' + elif platform == 'macosx': + platform_cmp = 'mac' + elif platform == 'linux': + platform_cmp = 'linux' + paths.append(os.path.join(script_dir, 'distrib', platform_cmp)) + + # shared directory + paths.append(os.path.join(script_dir, 'distrib')) + + # load the file if it exists + for path in paths: + file = os.path.join(path, 'README.' +name + '.txt') + if path_exists(file): + return read_file(file) + + raise Exception('Readme component not found: ' + name) + +def create_readme(): + """ Creates the README.TXT file. """ + # gather the components + header_data = get_readme_component('header') + mode_data = get_readme_component(mode) + redistrib_data = get_readme_component('redistrib') + footer_data = get_readme_component('footer') + + # format the file + data = header_data + '\n\n' + mode_data + '\n\n' + redistrib_data + '\n\n' + footer_data + data = data.replace('$CEF_URL$', cef_url) + data = data.replace('$CEF_REV$', cef_rev) + data = data.replace('$CEF_VER$', cef_ver) + data = data.replace('$CHROMIUM_URL$', chromium_url) + data = data.replace('$CHROMIUM_REV$', chromium_rev) + data = data.replace('$CHROMIUM_VER$', chromium_ver) + data = data.replace('$DATE$', date) + + if platform == 'windows': + platform_str = 'Windows' + elif platform == 'macosx': + platform_str = 'Mac OS-X' + elif platform == 'linux': + platform_str = 'Linux' + + data = data.replace('$PLATFORM$', platform_str) + + if mode == 'standard': + distrib_type = 'Standard' + distrib_desc = 'This distribution contains all components necessary to build and distribute an\n' \ + 'application using CEF on the ' + platform_str + ' platform. Please see the LICENSING\n' \ + 'section of this document for licensing terms and conditions.' + elif mode == 'minimal': + distrib_type = 'Minimal' + distrib_desc = 'This distribution contains only the components required to distribute an\n' \ + 'application using CEF on the ' + platform_str + ' platform. Please see the LICENSING\n' \ + 'section of this document for licensing terms and conditions.' + elif mode == 'client': + distrib_type = 'Client' + distrib_desc = 'This distribution contains a release build of the cefclient sample application\n' \ + 'for the ' + platform_str + ' platform. Please see the LICENSING section of this document for\n' \ + 'licensing terms and conditions.' + + data = data.replace('$DISTRIB_TYPE$', distrib_type) + data = data.replace('$DISTRIB_DESC$', distrib_desc) + + write_file(os.path.join(output_dir, 'README.txt'), data) + if not options.quiet: + sys.stdout.write('Creating README.TXT file.\n') + +def transfer_gypi_files(src_dir, gypi_paths, gypi_path_prefix, dst_dir, quiet): + """ Transfer files from one location to another. """ + for path in gypi_paths: + # skip gyp includes + if path[:2] == '<@': + continue + src = os.path.join(src_dir, path) + dst = os.path.join(dst_dir, path.replace(gypi_path_prefix, '')) + dst_path = os.path.dirname(dst) + make_dir(dst_path, quiet) + copy_file(src, dst, quiet) + +def normalize_headers(file, new_path = ''): + """ Normalize headers post-processing. Remove the path component from any + project include directives. """ + data = read_file(file) + data = re.sub(r'''#include \"(?!include\/)[a-zA-Z0-9_\/]+\/+([a-zA-Z0-9_\.]+)\"''', \ + "// Include path modified for CEF Binary Distribution.\n#include \""+new_path+"\\1\"", data) + write_file(file, data) + +def transfer_files(cef_dir, script_dir, transfer_cfg, output_dir, quiet): + """ Transfer files based on the specified configuration. """ + if not path_exists(transfer_cfg): + return + + configs = eval_file(transfer_cfg) + for cfg in configs: + dst = os.path.join(output_dir, cfg['target']) + + # perform a copy if source is specified + if not cfg['source'] is None: + src = os.path.join(cef_dir, cfg['source']) + dst_path = os.path.dirname(dst) + make_dir(dst_path, quiet) + copy_file(src, dst, quiet) + + # place a readme file in the destination directory + readme = os.path.join(dst_path, 'README-TRANSFER.txt') + if not path_exists(readme): + copy_file(os.path.join(script_dir, 'distrib/README-TRANSFER.txt'), readme) + open(readme, 'ab').write(cfg['source']+"\n") + + # perform any required post-processing + if 'post-process' in cfg: + post = cfg['post-process'] + if post == 'normalize_headers': + new_path = '' + if cfg.has_key('new_header_path'): + new_path = cfg['new_header_path'] + normalize_headers(dst, new_path) + +def combine_libs(build_dir, libs, dest_lib): + """ Combine multiple static libraries into a single static library. """ + cmdline = 'msvs_env.bat python combine_libs.py -o "%s"' % dest_lib + for lib in libs: + lib_path = os.path.join(build_dir, lib) + if not path_exists(lib_path): + raise Exception('Library not found: ' + lib_path) + cmdline = cmdline + ' "%s"' % lib_path + run(cmdline, os.path.join(cef_dir, 'tools')) + +def run(command_line, working_dir): + """ Run a command. """ + sys.stdout.write('-------- Running "'+command_line+'" in "'+\ + working_dir+'"...'+"\n") + args = shlex.split(command_line.replace('\\', '\\\\')) + return subprocess.check_call(args, cwd=working_dir, env=os.environ, + shell=(sys.platform == 'win32')) + +# cannot be loaded as a module +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + +# parse command-line options +disc = """ +This utility builds the CEF Binary Distribution. +""" + +parser = OptionParser(description=disc) +parser.add_option('--output-dir', dest='outputdir', metavar='DIR', + help='output directory [required]') +parser.add_option('--allow-partial', + action='store_true', dest='allowpartial', default=False, + help='allow creation of partial distributions') +parser.add_option('--no-symbols', + action='store_true', dest='nosymbols', default=False, + help='don\'t create symbol files') +parser.add_option('--no-docs', + action='store_true', dest='nodocs', default=False, + help='don\'t create documentation') +parser.add_option('--no-archive', + action='store_true', dest='noarchive', default=False, + help='don\'t create archives for output directories') +parser.add_option('--ninja-build', + action='store_true', dest='ninjabuild', default=False, + help='build was created using ninja') +parser.add_option('--x64-build', + action='store_true', dest='x64build', default=False, + help='build was created for 64-bit systems') +parser.add_option('--minimal', + action='store_true', dest='minimal', default=False, + help='include only release build binary files') +parser.add_option('--client', + action='store_true', dest='client', default=False, + help='include only the cefclient application') +parser.add_option('-q', '--quiet', + action='store_true', dest='quiet', default=False, + help='do not output detailed status information') +(options, args) = parser.parse_args() + +# Test the operating system. +platform = ''; +if sys.platform == 'win32': + platform = 'windows' +elif sys.platform == 'darwin': + platform = 'macosx' +elif sys.platform.startswith('linux'): + platform = 'linux' + +# the outputdir option is required +if options.outputdir is None: + parser.print_help(sys.stderr) + sys.exit() + +if options.minimal and options.client: + print 'Invalid combination of options' + parser.print_help(sys.stderr) + sys.exit() + +if not options.ninjabuild: + print 'Ninja build is required on all platforms' + sys.exit() + +# script directory +script_dir = os.path.dirname(__file__) + +# CEF root directory +cef_dir = os.path.abspath(os.path.join(script_dir, os.pardir)) + +# src directory +src_dir = os.path.abspath(os.path.join(cef_dir, os.pardir)) + +# retrieve url and revision information for CEF +if svn.is_checkout(cef_dir): + cef_info = svn.get_svn_info(cef_dir) + cef_url = cef_info['url'] + cef_rev = cef_info['revision'] +elif git.is_checkout(cef_dir): + cef_url = git.get_url(cef_dir) + cef_rev = git.get_svn_revision(cef_dir) +else: + raise Exception('Not a valid checkout: %s' % (cef_dir)) + +# retrieve url and revision information for Chromium +if svn.is_checkout(src_dir): + chromium_info = svn.get_svn_info(src_dir) + chromium_url = chromium_info['url'] + chromium_rev = chromium_info['revision'] +elif git.is_checkout(src_dir): + chromium_url = git.get_url(src_dir) + chromium_rev = git.get_hash(src_dir) +else: + raise Exception('Not a valid checkout: %s' % (src_dir)) + +date = get_date() + +# Read and parse the version file (key=value pairs, one per line) +args = {} +read_version_file(os.path.join(cef_dir, 'VERSION'), args) +read_version_file(os.path.join(cef_dir, '../chrome/VERSION'), args) + +cef_ver = args['CEF_MAJOR']+'.'+args['BUILD']+'.'+cef_rev +chromium_ver = args['MAJOR']+'.'+args['MINOR']+'.'+args['BUILD']+'.'+args['PATCH'] + +# list of output directories to be archived +archive_dirs = [] + +platform_arch = '32' +if options.x64build: + platform_arch = '64' + +if platform == 'linux': + platform_arch = '' + lib_dir_name = 'lib' + release_libcef_path = os.path.join(src_dir, 'out', 'Release', lib_dir_name, 'libcef.so'); + debug_libcef_path = os.path.join(src_dir, 'out', 'Debug', lib_dir_name, 'libcef.so'); + file_desc = '' + output = subprocess.check_output('file ' + release_libcef_path + ' ' + debug_libcef_path + '; exit 0', + env=os.environ, stderr=subprocess.STDOUT, shell=True) + if output.find('32-bit') != -1: + platform_arch = '32' + if output.find('64-bit') != -1: + platform_arch = '64' + +# output directory +output_dir_base = 'cef_binary_' + cef_ver +output_dir_name = output_dir_base + '_' + platform + platform_arch + +if options.minimal: + mode = 'minimal' + output_dir_name = output_dir_name + '_minimal' +elif options.client: + mode = 'client' + output_dir_name = output_dir_name + '_client' +else: + mode = 'standard' + +output_dir = create_output_dir(output_dir_name, options.outputdir) + +# create the README.TXT file +create_readme() + +# transfer the LICENSE.txt file +copy_file(os.path.join(cef_dir, 'LICENSE.txt'), output_dir, options.quiet) + +# read the variables list from the autogenerated cef_paths.gypi file +cef_paths = eval_file(os.path.join(cef_dir, 'cef_paths.gypi')) +cef_paths = cef_paths['variables'] + +# read the variables list from the manually edited cef_paths2.gypi file +cef_paths2 = eval_file(os.path.join(cef_dir, 'cef_paths2.gypi')) +cef_paths2 = cef_paths2['variables'] + +if mode == 'standard': + # create the include directory + include_dir = os.path.join(output_dir, 'include') + make_dir(include_dir, options.quiet) + + # create the cefclient directory + cefclient_dir = os.path.join(output_dir, 'cefclient') + make_dir(cefclient_dir, options.quiet) + + # create the cefsimple directory + cefsimple_dir = os.path.join(output_dir, 'cefsimple') + make_dir(cefsimple_dir, options.quiet) + + # create the libcef_dll_wrapper directory + wrapper_dir = os.path.join(output_dir, 'libcef_dll') + make_dir(wrapper_dir, options.quiet) + + # transfer common include files + transfer_gypi_files(cef_dir, cef_paths2['includes_common'], \ + 'include/', include_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['includes_capi'], \ + 'include/', include_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['includes_wrapper'], \ + 'include/', include_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths['autogen_cpp_includes'], \ + 'include/', include_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths['autogen_capi_includes'], \ + 'include/', include_dir, options.quiet) + + # transfer common cefclient files + transfer_gypi_files(cef_dir, cef_paths2['cefclient_sources_common'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['cefclient_bundle_resources_common'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + + # transfer common cefsimple files + transfer_gypi_files(cef_dir, cef_paths2['cefsimple_sources_common'], \ + 'tests/cefsimple/', cefsimple_dir, options.quiet) + + # transfer common libcef_dll_wrapper files + transfer_gypi_files(cef_dir, cef_paths2['libcef_dll_wrapper_sources_common'], \ + 'libcef_dll/', wrapper_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths['autogen_client_side'], \ + 'libcef_dll/', wrapper_dir, options.quiet) + + # transfer gyp files + copy_file(os.path.join(script_dir, 'distrib/cefclient.gyp'), output_dir, options.quiet) + paths_gypi = os.path.join(cef_dir, 'cef_paths2.gypi') + data = read_file(paths_gypi) + data = data.replace('tests/cefclient/', 'cefclient/') + data = data.replace('tests/cefsimple/', 'cefsimple/') + write_file(os.path.join(output_dir, 'cef_paths2.gypi'), data) + copy_file(os.path.join(cef_dir, 'cef_paths.gypi'), \ + os.path.join(output_dir, 'cef_paths.gypi'), options.quiet) + + # transfer additional files + transfer_files(cef_dir, script_dir, os.path.join(script_dir, 'distrib/transfer.cfg'), \ + output_dir, options.quiet) + + # process cmake templates + variables = dict(cef_paths.items() + cef_paths2.items()) + process_cmake_template(os.path.join(cef_dir, 'CMakeLists.txt.in'), \ + os.path.join(output_dir, 'CMakeLists.txt'), \ + variables, options.quiet) + process_cmake_template(os.path.join(cef_dir, 'macros.cmake.in'), \ + os.path.join(output_dir, 'macros.cmake'), \ + variables, options.quiet) + process_cmake_template(os.path.join(cef_dir, 'libcef_dll', 'CMakeLists.txt.in'), \ + os.path.join(output_dir, 'libcef_dll', 'CMakeLists.txt'), \ + variables, options.quiet) + process_cmake_template(os.path.join(cef_dir, 'tests', 'cefclient', 'CMakeLists.txt.in'), \ + os.path.join(output_dir, 'cefclient', 'CMakeLists.txt'), \ + variables, options.quiet) + process_cmake_template(os.path.join(cef_dir, 'tests', 'cefsimple', 'CMakeLists.txt.in'), \ + os.path.join(output_dir, 'cefsimple', 'CMakeLists.txt'), \ + variables, options.quiet) + +if platform == 'windows': + binaries = [ + 'd3dcompiler_47.dll', + 'ffmpegsumo.dll', + 'libcef.dll', + 'libEGL.dll', + 'libGLESv2.dll', + 'pdf.dll', + ] + if not options.x64build: + binaries.append('wow_helper.exe') + + out_dir = os.path.join(src_dir, 'out') + libcef_dll_file = 'libcef.dll.lib' + sandbox_libs = [ + 'obj\\base\\base.lib', + 'obj\\base\\base_static.lib', + 'obj\\cef\\cef_sandbox.lib', + 'obj\\base\\third_party\\dynamic_annotations\\dynamic_annotations.lib', + 'obj\\sandbox\\sandbox.lib', + ] + + valid_build_dir = None + + build_dir_suffix = '' + if options.x64build: + build_dir_suffix = '_x64' + + if mode == 'standard': + # transfer Debug files + build_dir = os.path.join(out_dir, 'Debug' + build_dir_suffix); + if not options.allowpartial or path_exists(os.path.join(build_dir, 'cefclient.exe')): + valid_build_dir = build_dir + dst_dir = os.path.join(output_dir, 'Debug') + make_dir(dst_dir, options.quiet) + copy_files(os.path.join(script_dir, 'distrib/win/*.dll'), dst_dir, options.quiet) + for binary in binaries: + copy_file(os.path.join(build_dir, binary), os.path.join(dst_dir, binary), options.quiet) + copy_file(os.path.join(build_dir, libcef_dll_file), os.path.join(dst_dir, 'libcef.lib'), \ + options.quiet) + combine_libs(build_dir, sandbox_libs, os.path.join(dst_dir, 'cef_sandbox.lib')); + + if not options.nosymbols: + # create the symbol output directory + symbol_output_dir = create_output_dir(output_dir_name + '_debug_symbols', options.outputdir) + # transfer contents + copy_file(os.path.join(build_dir, 'libcef.dll.pdb'), symbol_output_dir, options.quiet) + else: + sys.stderr.write("No Debug build files.\n") + + # transfer Release files + build_dir = os.path.join(out_dir, 'Release' + build_dir_suffix); + if not options.allowpartial or path_exists(os.path.join(build_dir, 'cefclient.exe')): + valid_build_dir = build_dir + dst_dir = os.path.join(output_dir, 'Release') + make_dir(dst_dir, options.quiet) + copy_files(os.path.join(script_dir, 'distrib/win/*.dll'), dst_dir, options.quiet) + for binary in binaries: + copy_file(os.path.join(build_dir, binary), os.path.join(dst_dir, binary), options.quiet) + + if mode != 'client': + copy_file(os.path.join(build_dir, libcef_dll_file), os.path.join(dst_dir, 'libcef.lib'), \ + options.quiet) + combine_libs(build_dir, sandbox_libs, os.path.join(dst_dir, 'cef_sandbox.lib')); + else: + copy_file(os.path.join(build_dir, 'cefclient.exe'), dst_dir, options.quiet) + + if not options.nosymbols: + # create the symbol output directory + symbol_output_dir = create_output_dir(output_dir_name + '_release_symbols', options.outputdir) + # transfer contents + copy_file(os.path.join(build_dir, 'libcef.dll.pdb'), symbol_output_dir, options.quiet) + else: + sys.stderr.write("No Release build files.\n") + + if not valid_build_dir is None: + # transfer resource files + build_dir = valid_build_dir + if mode == 'client': + dst_dir = os.path.join(output_dir, 'Release') + else: + dst_dir = os.path.join(output_dir, 'Resources') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cef.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cef_100_percent.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cef_200_percent.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'devtools_resources.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'icudtl.dat'), dst_dir, options.quiet) + copy_dir(os.path.join(build_dir, 'locales'), os.path.join(dst_dir, 'locales'), options.quiet) + + if mode == 'standard': + # transfer include files + transfer_gypi_files(cef_dir, cef_paths2['includes_win'], \ + 'include/', include_dir, options.quiet) + + # transfer cefclient files + transfer_gypi_files(cef_dir, cef_paths2['cefclient_sources_win'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + + # transfer cefsimple files + transfer_gypi_files(cef_dir, cef_paths2['cefsimple_sources_win'], \ + 'tests/cefsimple/', cefsimple_dir, options.quiet) + + # transfer additional files, if any + transfer_files(cef_dir, script_dir, os.path.join(script_dir, 'distrib/win/transfer.cfg'), \ + output_dir, options.quiet) + + if not options.nodocs: + # generate doc files + os.popen('make_cppdocs.bat '+cef_rev) + + src_dir = os.path.join(cef_dir, 'docs') + if path_exists(src_dir): + # create the docs output directory + docs_output_dir = create_output_dir(output_dir_base + '_docs', options.outputdir) + # transfer contents + copy_dir(src_dir, docs_output_dir, options.quiet) + +elif platform == 'macosx': + out_dir = os.path.join(src_dir, 'out') + + valid_build_dir = None + framework_name = 'Chromium Embedded Framework' + + if mode == 'standard': + # transfer Debug files + build_dir = os.path.join(out_dir, 'Debug') + if not options.allowpartial or path_exists(os.path.join(build_dir, 'cefclient.app')): + valid_build_dir = build_dir + dst_dir = os.path.join(output_dir, 'Debug') + make_dir(dst_dir, options.quiet) + copy_dir(os.path.join(build_dir, 'cefclient.app/Contents/Frameworks/%s.framework' % framework_name), \ + os.path.join(dst_dir, '%s.framework' % framework_name), options.quiet) + + # transfer Release files + build_dir = os.path.join(out_dir, 'Release') + if not options.allowpartial or path_exists(os.path.join(build_dir, 'cefclient.app')): + valid_build_dir = build_dir + dst_dir = os.path.join(output_dir, 'Release') + make_dir(dst_dir, options.quiet) + if mode != 'client': + copy_dir(os.path.join(build_dir, 'cefclient.app/Contents/Frameworks/%s.framework' % framework_name), \ + os.path.join(dst_dir, '%s.framework' % framework_name), options.quiet) + else: + copy_dir(os.path.join(build_dir, 'cefclient.app'), os.path.join(dst_dir, 'cefclient.app'), options.quiet) + + if not options.nosymbols: + # create the symbol output directory + symbol_output_dir = create_output_dir(output_dir_name + '_release_symbols', options.outputdir) + + # create the real dSYM file from the "fake" dSYM file + sys.stdout.write("Creating the real dSYM file...\n") + src_path = os.path.join(build_dir, \ + '%s.framework.dSYM/Contents/Resources/DWARF/%s' % (framework_name, framework_name)) + dst_path = os.path.join(symbol_output_dir, '%s.dSYM' % framework_name) + run('dsymutil "%s" -o "%s"' % (src_path, dst_path), cef_dir) + + if mode == 'standard': + # transfer include files + transfer_gypi_files(cef_dir, cef_paths2['includes_mac'], \ + 'include/', include_dir, options.quiet) + + # transfer cefclient files + transfer_gypi_files(cef_dir, cef_paths2['cefclient_sources_mac'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['cefclient_sources_mac_helper'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['cefclient_bundle_resources_mac'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + + # transfer cefclient/mac files + copy_dir(os.path.join(cef_dir, 'tests/cefclient/mac/'), os.path.join(output_dir, 'cefclient/mac/'), \ + options.quiet) + + # transfer cefsimple files + transfer_gypi_files(cef_dir, cef_paths2['cefsimple_sources_mac'], \ + 'tests/cefsimple/', cefsimple_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['cefsimple_sources_mac_helper'], \ + 'tests/cefsimple/', cefsimple_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['cefsimple_bundle_resources_mac'], \ + 'tests/cefsimple/', cefsimple_dir, options.quiet) + + # transfer cefsimple/mac files + copy_dir(os.path.join(cef_dir, 'tests/cefsimple/mac/'), os.path.join(output_dir, 'cefsimple/mac/'), \ + options.quiet) + + # transfer additional files, if any + transfer_files(cef_dir, script_dir, os.path.join(script_dir, 'distrib/mac/transfer.cfg'), \ + output_dir, options.quiet) + +elif platform == 'linux': + out_dir = os.path.join(src_dir, 'out') + lib_dir_name = 'lib' + + valid_build_dir = None + + if mode == 'standard': + # transfer Debug files + build_dir = os.path.join(out_dir, 'Debug'); + if not options.allowpartial or path_exists(os.path.join(build_dir, 'cefclient')): + valid_build_dir = build_dir + dst_dir = os.path.join(output_dir, 'Debug') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'chrome_sandbox'), os.path.join(dst_dir, 'chrome-sandbox'), options.quiet) + copy_file(os.path.join(build_dir, lib_dir_name, 'libcef.so'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'libffmpegsumo.so'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'libpdf.so'), dst_dir, options.quiet) + else: + sys.stderr.write("No Debug build files.\n") + + # transfer Release files + build_dir = os.path.join(out_dir, 'Release'); + if not options.allowpartial or path_exists(os.path.join(build_dir, 'cefclient')): + valid_build_dir = build_dir + dst_dir = os.path.join(output_dir, 'Release') + make_dir(dst_dir, options.quiet) + + if mode == 'client': + lib_dst_dir = os.path.join(dst_dir, lib_dir_name) + make_dir(lib_dst_dir, options.quiet) + copy_file(os.path.join(build_dir, lib_dir_name, 'libcef.so'), lib_dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cefclient'), dst_dir, options.quiet) + else: + copy_file(os.path.join(build_dir, lib_dir_name, 'libcef.so'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'chrome_sandbox'), os.path.join(dst_dir, 'chrome-sandbox'), options.quiet) + copy_file(os.path.join(build_dir, 'libffmpegsumo.so'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'libpdf.so'), dst_dir, options.quiet) + else: + sys.stderr.write("No Release build files.\n") + + if not valid_build_dir is None: + # transfer resource files + build_dir = valid_build_dir + if mode == 'client': + dst_dir = os.path.join(output_dir, 'Release') + copy_dir(os.path.join(build_dir, 'files'), os.path.join(dst_dir, 'files'), options.quiet) + else: + dst_dir = os.path.join(output_dir, 'Resources') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cef.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cef_100_percent.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'cef_200_percent.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'devtools_resources.pak'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'icudtl.dat'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'natives_blob.bin'), dst_dir, options.quiet) + copy_file(os.path.join(build_dir, 'snapshot_blob.bin'), dst_dir, options.quiet) + copy_dir(os.path.join(build_dir, 'locales'), os.path.join(dst_dir, 'locales'), options.quiet) + + if mode == 'standard': + # transfer include files + transfer_gypi_files(cef_dir, cef_paths2['includes_linux'], \ + 'include/', include_dir, options.quiet) + + # transfer cefclient files + transfer_gypi_files(cef_dir, cef_paths2['cefclient_sources_linux'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + transfer_gypi_files(cef_dir, cef_paths2['cefclient_bundle_resources_linux'], \ + 'tests/cefclient/', cefclient_dir, options.quiet) + + # transfer cefsimple files + transfer_gypi_files(cef_dir, cef_paths2['cefsimple_sources_linux'], \ + 'tests/cefsimple/', cefsimple_dir, options.quiet) + + # transfer additional files, if any + copy_file(os.path.join(script_dir, 'distrib/linux/build.sh'), output_dir, options.quiet) + transfer_files(cef_dir, script_dir, os.path.join(script_dir, 'distrib/linux/transfer.cfg'), \ + output_dir, options.quiet) + +if not options.noarchive: + # create an archive for each output directory + archive_extenstion = '.zip' + if os.getenv('CEF_COMMAND_7ZIP', '') != '': + archive_extenstion = '.7z' + for dir in archive_dirs: + zip_file = os.path.split(dir)[1] + archive_extenstion + if not options.quiet: + sys.stdout.write('Creating '+zip_file+"...\n") + if archive_extenstion == '.zip': + create_archive(dir, os.path.join(dir, os.pardir, zip_file)) + else: + create_7z_archive(dir, os.path.join(dir, os.pardir, zip_file)) diff --git a/tools/make_distrib.sh b/tools/make_distrib.sh new file mode 100755 index 000000000..273a3e16b --- /dev/null +++ b/tools/make_distrib.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python make_distrib.py --output-dir ../binary_distrib/ $@ diff --git a/tools/make_gypi_file.py b/tools/make_gypi_file.py new file mode 100644 index 000000000..e5cefd7a9 --- /dev/null +++ b/tools/make_gypi_file.py @@ -0,0 +1,108 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from cef_parser import * + +def make_gypi_file(header): + # header string + result = \ +"""# Copyright (c) $YEAR$ The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. +# +# --------------------------------------------------------------------------- +# +# This file was generated by the CEF translator tool and should not edited +# by hand. See the translator.README.txt file in the tools directory for +# more information. +# + +{ + 'variables': { +""" + + filenames = sorted(header.get_file_names()) + + # cpp includes + result += " 'autogen_cpp_includes': [\n" + for filename in filenames: + result += " 'include/"+filename+"',\n" + result += " ],\n" + + # capi includes + result += " 'autogen_capi_includes': [\n" + for filename in filenames: + result += " 'include/capi/"+get_capi_file_name(filename)+"',\n" + result += " ],\n" + + classes = sorted(header.get_class_names()) + + # library side includes + result += " 'autogen_library_side': [\n" + for clsname in classes: + cls = header.get_class(clsname) + filename = get_capi_name(clsname[3:], False) + if cls.is_library_side(): + result += " 'libcef_dll/cpptoc/"+filename+"_cpptoc.cc',\n" \ + " 'libcef_dll/cpptoc/"+filename+"_cpptoc.h',\n" + else: + result += " 'libcef_dll/ctocpp/"+filename+"_ctocpp.cc',\n" \ + " 'libcef_dll/ctocpp/"+filename+"_ctocpp.h',\n" + result += " ],\n" + + # client side includes + result += " 'autogen_client_side': [\n" + for clsname in classes: + cls = header.get_class(clsname) + filename = get_capi_name(clsname[3:], False) + if cls.is_library_side(): + result += " 'libcef_dll/ctocpp/"+filename+"_ctocpp.cc',\n" \ + " 'libcef_dll/ctocpp/"+filename+"_ctocpp.h',\n" + else: + result += " 'libcef_dll/cpptoc/"+filename+"_cpptoc.cc',\n" \ + " 'libcef_dll/cpptoc/"+filename+"_cpptoc.h',\n" + result += " ],\n" + + # footer string + result += \ +""" }, +} +""" + + # add the copyright year + result = result.replace('$YEAR$', get_year()) + + return result + +def write_gypi_file(header, file, backup): + if path_exists(file): + oldcontents = read_file(file) + else: + oldcontents = '' + + newcontents = make_gypi_file(header) + if newcontents != oldcontents: + if backup and oldcontents != '': + backup_file(file) + write_file(file, newcontents) + return True + + return False + + +# test the module +if __name__ == "__main__": + import sys + + # verify that the correct number of command-line arguments are provided + if len(sys.argv) < 2: + sys.stderr.write('Usage: '+sys.argv[0]+' ') + sys.exit() + + # create the header object + header = obj_header() + header.add_file(sys.argv[1]) + + # dump the result to stdout + sys.stdout.write(make_gypi_file(header)) diff --git a/tools/make_pack_header.py b/tools/make_pack_header.py new file mode 100644 index 000000000..0b4cb2e04 --- /dev/null +++ b/tools/make_pack_header.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python +# Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license +# that can be found in the LICENSE file. + +""" +A simple utility function to merge pack resource files into a single resource file. +""" + +from date_util import * +from file_util import * +import os +import re +import string +import sys + + +def MakeFileSegment(input): + result = """ + +// --------------------------------------------------------------------------- +// From $FILE$: +""" + + filename = os.path.split(input)[1] + result = result.replace('$FILE$', filename) + + contents = read_file(input) + + # identify the defines in the file + p = re.compile('#define\s([A-Za-z0-9_]{1,})\s([0-9]{1,})') + list = p.findall(contents) + for name, id in list: + result += "\n#define %s %s" % (name, id) + + return result + + +def MakeFile(output, input): + # header string + result = \ +"""// Copyright (c) $YEAR$ Marshall A. Greenblatt. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * 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. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// 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. +// +// --------------------------------------------------------------------------- +// +// This file is generated by the make_pack_header.py tool. +// + +#ifndef $GUARD$ +#define $GUARD$ +#pragma once""" + + # sort the input files by name + input = sorted(input, key=lambda path: os.path.split(path)[1]) + + # generate the file segments + for file in input: + result += MakeFileSegment(file) + + # footer string + result += \ +""" + +#endif // $GUARD$ +""" + + # add the copyright year + result = result.replace('$YEAR$', get_year()) + # add the guard string + filename = os.path.split(output)[1] + guard = 'CEF_INCLUDE_'+string.upper(filename.replace('.', '_'))+'_' + result = result.replace('$GUARD$', guard) + + if path_exists(output): + old_contents = read_file(output) + else: + old_contents = '' + + if (result != old_contents): + write_file(output, result) + sys.stdout.write('File '+output+' updated.\n') + else: + sys.stdout.write('File '+output+' is already up to date.\n') + +def main(argv): + if len(argv) < 3: + print ("Usage:\n %s [input_file2] ... " % + argv[0]) + sys.exit(-1) + MakeFile(argv[1], argv[2:]) + + +if '__main__' == __name__: + main(sys.argv) diff --git a/tools/make_version_header.bat b/tools/make_version_header.bat new file mode 100644 index 000000000..86e3094f8 --- /dev/null +++ b/tools/make_version_header.bat @@ -0,0 +1,2 @@ +@echo off +python.bat tools\make_version_header.py --header include\cef_version.h --cef_version VERSION --chrome_version ../chrome/VERSION --cpp_header_dir include diff --git a/tools/make_version_header.py b/tools/make_version_header.py new file mode 100644 index 000000000..84d49f52a --- /dev/null +++ b/tools/make_version_header.py @@ -0,0 +1,176 @@ +# Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from date_util import * +from file_util import * +from optparse import OptionParser +from cef_api_hash import cef_api_hash +import svn_util as svn +import git_util as git +import sys + +# cannot be loaded as a module +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + + +# parse command-line options +disc = """ +This utility creates the version header file. +""" + +parser = OptionParser(description=disc) +parser.add_option('--header', dest='header', metavar='FILE', + help='output version header file [required]') +parser.add_option('--cef_version', dest='cef_version', metavar='FILE', + help='input CEF version config file [required]') +parser.add_option('--chrome_version', dest='chrome_version', metavar='FILE', + help='input Chrome version config file [required]') +parser.add_option('--cpp_header_dir', dest='cpp_header_dir', metavar='DIR', + help='input directory for C++ header files [required]') +parser.add_option('-q', '--quiet', + action='store_true', dest='quiet', default=False, + help='do not output detailed status information') +(options, args) = parser.parse_args() + +# the header option is required +if options.header is None or options.cef_version is None or options.chrome_version is None or options.cpp_header_dir is None: + parser.print_help(sys.stdout) + sys.exit() + +def write_svn_header(header, chrome_version, cef_version, cpp_header_dir): + """ Creates the header file for the current revision and Chrome version information + if the information has changed or if the file doesn't already exist. """ + + if not path_exists(chrome_version): + raise Exception('Chrome version file '+chrome_version+' does not exist.') + if not path_exists(cef_version): + raise Exception('CEF version file '+cef_version+' does not exist.') + + args = {} + read_version_file(chrome_version, args) + read_version_file(cef_version, args) + + if path_exists(header): + oldcontents = read_file(header) + else: + oldcontents = '' + + year = get_year() + + if svn.is_checkout('.'): + revision = svn.get_revision() + elif git.is_checkout('.'): + revision = git.get_svn_revision() + else: + raise Exception('Not a valid checkout') + + # calculate api hashes + api_hash_calculator = cef_api_hash(cpp_header_dir, verbose = False) + api_hashes = api_hash_calculator.calculate() + + newcontents = '// Copyright (c) '+year+' Marshall A. Greenblatt. All rights reserved.\n'+\ + '//\n'+\ + '// Redistribution and use in source and binary forms, with or without\n'+\ + '// modification, are permitted provided that the following conditions are\n'+\ + '// met:\n'+\ + '//\n'+\ + '// * Redistributions of source code must retain the above copyright\n'+\ + '// notice, this list of conditions and the following disclaimer.\n'+\ + '// * Redistributions in binary form must reproduce the above\n'+\ + '// copyright notice, this list of conditions and the following disclaimer\n'+\ + '// in the documentation and/or other materials provided with the\n'+\ + '// distribution.\n'+\ + '// * Neither the name of Google Inc. nor the name Chromium Embedded\n'+\ + '// Framework nor the names of its contributors may be used to endorse\n'+\ + '// or promote products derived from this software without specific prior\n'+\ + '// written permission.\n'+\ + '//\n'+\ + '// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n'+\ + '// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n'+\ + '// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n'+\ + '// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n'+\ + '// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n'+\ + '// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n'+\ + '// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n'+\ + '// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n'+\ + '// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n'+\ + '// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n'+\ + '// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'+\ + '//\n'+\ + '// ---------------------------------------------------------------------------\n'+\ + '//\n'+\ + '// This file is generated by the make_version_header.py tool.\n'+\ + '//\n\n'+\ + '#ifndef CEF_INCLUDE_CEF_VERSION_H_\n'+\ + '#define CEF_INCLUDE_CEF_VERSION_H_\n\n'+\ + '#define CEF_VERSION_MAJOR ' + args['CEF_MAJOR'] + '\n'+\ + '#define CEF_REVISION ' + revision + '\n'+\ + '#define COPYRIGHT_YEAR ' + year + '\n\n'+\ + '#define CHROME_VERSION_MAJOR ' + args['MAJOR'] + '\n'+\ + '#define CHROME_VERSION_MINOR ' + args['MINOR'] + '\n'+\ + '#define CHROME_VERSION_BUILD ' + args['BUILD'] + '\n'+\ + '#define CHROME_VERSION_PATCH ' + args['PATCH'] + '\n\n'+\ + '#define DO_MAKE_STRING(p) #p\n'+\ + '#define MAKE_STRING(p) DO_MAKE_STRING(p)\n\n'+\ + '#ifndef APSTUDIO_HIDDEN_SYMBOLS\n\n'\ + '#include "include/internal/cef_export.h"\n\n'+\ + '#ifdef __cplusplus\n'+\ + 'extern "C" {\n'+\ + '#endif\n\n'+\ + '// The API hash is created by analyzing CEF header files for C API type\n'+\ + '// definitions. The hash value will change when header files are modified\n'+\ + '// in a way that may cause binary incompatibility with other builds. The\n'+\ + '// universal hash value will change if any platform is affected whereas the\n'+\ + '// platform hash values will change only if that particular platform is\n'+\ + '// affected.\n'+\ + '#define CEF_API_HASH_UNIVERSAL "' + api_hashes['universal'] + '"\n'+\ + '#if defined(OS_WIN)\n'+\ + '#define CEF_API_HASH_PLATFORM "' + api_hashes['windows'] + '"\n'+\ + '#elif defined(OS_MACOSX)\n'+\ + '#define CEF_API_HASH_PLATFORM "' + api_hashes['macosx'] + '"\n'+\ + '#elif defined(OS_LINUX)\n'+\ + '#define CEF_API_HASH_PLATFORM "' + api_hashes['linux'] + '"\n'+\ + '#endif\n\n'+\ + '///\n'+\ + '// Returns the CEF build revision for the libcef library.\n'+\ + '///\n'+\ + 'CEF_EXPORT int cef_build_revision();\n\n'+\ + '///\n'+\ + '// Returns CEF version information for the libcef library. The |entry|\n'+\ + '// parameter describes which version component will be returned:\n'+\ + '// 0 - CEF_VERSION_MAJOR\n'+\ + '// 1 - CEF_REVISION\n'+\ + '// 2 - CHROME_VERSION_MAJOR\n'+\ + '// 3 - CHROME_VERSION_MINOR\n'+\ + '// 4 - CHROME_VERSION_BUILD\n'+\ + '// 5 - CHROME_VERSION_PATCH\n'+\ + '///\n'+\ + 'CEF_EXPORT int cef_version_info(int entry);\n\n'+\ + '///\n'+\ + '// Returns CEF API hashes for the libcef library. The returned string is owned\n'+\ + '// by the library and should not be freed. The |entry| parameter describes which\n'+\ + '// hash value will be returned:\n'+\ + '// 0 - CEF_API_HASH_PLATFORM\n'+\ + '// 1 - CEF_API_HASH_UNIVERSAL\n'+\ + '///\n'+\ + 'CEF_EXPORT const char* cef_api_hash(int entry);\n\n'+\ + '#ifdef __cplusplus\n'+\ + '}\n'+\ + '#endif\n\n'+\ + '#endif // APSTUDIO_HIDDEN_SYMBOLS\n\n'+\ + '#endif // CEF_INCLUDE_CEF_VERSION_H_\n' + if newcontents != oldcontents: + write_file(header, newcontents) + return True + + return False + +written = write_svn_header(options.header, options.chrome_version, options.cef_version, options.cpp_header_dir) +if not options.quiet: + if written: + sys.stdout.write('File '+options.header+' updated.\n') + else: + sys.stdout.write('File '+options.header+' is already up to date.\n') diff --git a/tools/make_version_header.sh b/tools/make_version_header.sh new file mode 100755 index 000000000..4cac35f4a --- /dev/null +++ b/tools/make_version_header.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python tools/make_version_header.py --header include/cef_version.h --cef_version VERSION --chrome_version ../chrome/VERSION --cpp_header_dir include diff --git a/tools/msvs_env.bat b/tools/msvs_env.bat new file mode 100644 index 000000000..07b440691 --- /dev/null +++ b/tools/msvs_env.bat @@ -0,0 +1,60 @@ +@echo off +:: Copyright (c) 2013 The Chromium Embedded Framework Authors. All rights +:: reserved. Use of this source code is governed by a BSD-style license +:: that can be found in the LICENSE file. + +:: Set up the environment for use with MSVS tools and then execute whatever +:: was specified on the command-line. + +set RC= +setlocal + +:: In case it's already provided via the environment. +set vcvars="%CEF_VCVARS%" +if exist %vcvars% goto found_vcvars + +:: Hardcoded list of MSVS paths. +:: Alternatively we could 'reg query' this key: +:: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\10.0\Setup\VS;ProductDir +set vcvars="%PROGRAMFILES(X86)%\Microsoft Visual Studio 12.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +set vcvars="%PROGRAMFILES(X86)%\Microsoft Visual Studio 11.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +set vcvars="%PROGRAMFILES(X86)%\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +set vcvars="%PROGRAMFILES%\Microsoft Visual Studio 12.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +set vcvars="%PROGRAMFILES%\Microsoft Visual Studio 11.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +set vcvars="%PROGRAMFILES%\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +:: VS 2008 vcvars isn't standalone, it needs this env var. +set VS90COMNTOOLS=%PROGRAMFILES(X86)%\Microsoft Visual Studio 9.0\Common7\Tools\ +set vcvars="%PROGRAMFILES(X86)%\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars +set VS90COMNTOOLS=%PROGRAMFILES%\Microsoft Visual Studio 9.0\Common7\Tools\ +set vcvars="%PROGRAMFILES%\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat" +if exist %vcvars% goto found_vcvars + +set RC=1 +echo Failed to find vcvars +goto end + +:found_vcvars +echo vcvars: +echo %vcvars% +call %vcvars% + +echo PATH: +echo %PATH% +%* + +:end +endlocal & set RC=%ERRORLEVEL% +goto omega + +:returncode +exit /B %RC% + +:omega +call :returncode %RC% diff --git a/tools/patch.bat b/tools/patch.bat new file mode 100644 index 000000000..0b68f6193 --- /dev/null +++ b/tools/patch.bat @@ -0,0 +1,2 @@ +@echo off +python.bat tools\patcher.py --patch-config patch/patch.cfg \ No newline at end of file diff --git a/tools/patch.sh b/tools/patch.sh new file mode 100755 index 000000000..b9dde9bc0 --- /dev/null +++ b/tools/patch.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python tools/patcher.py --patch-config patch/patch.cfg diff --git a/tools/patch_updater.py b/tools/patch_updater.py new file mode 100644 index 000000000..886d7266a --- /dev/null +++ b/tools/patch_updater.py @@ -0,0 +1,157 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +from optparse import OptionParser +import os +import re +import sys +from exec_util import exec_cmd +import svn_util as svn +import git_util as git + +def msg(message): + """ Output a message. """ + sys.stdout.write('--> ' + message + "\n") + +def warn(message): + """ Output a warning. """ + sys.stdout.write('-' * 80 + "\n") + sys.stdout.write('!!!! WARNING: ' + message + "\n") + sys.stdout.write('-' * 80 + "\n") + +def extract_paths(file): + """ Extract the list of modified paths from the patch file. """ + paths = [] + fp = open(file) + for line in fp: + if line[:4] != '+++ ': + continue + match = re.match('^([^\t]+)', line[4:]) + if not match: + continue + paths.append(match.group(1).strip()) + return paths + +# Cannot be loaded as a module. +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + +# Parse command-line options. +disc = """ +This utility updates existing patch files. +""" + +parser = OptionParser(description=disc) +parser.add_option('--resave', + action='store_true', dest='resave', default=False, + help='re-save existing patch files to pick up manual changes') +parser.add_option('--revert', + action='store_true', dest='revert', default=False, + help='revert all changes from existing patch files') +(options, args) = parser.parse_args() + +if options.resave and options.revert: + print 'Invalid combination of options.' + parser.print_help(sys.stderr) + sys.exit() + +# The CEF root directory is the parent directory of _this_ script. +cef_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) +src_dir = os.path.join(cef_dir, os.pardir) + +# Determine the type of Chromium checkout. +if svn.is_checkout(src_dir): + src_is_git = False +elif git.is_checkout(src_dir): + src_is_git = True +else: + raise Exception('Not a valid checkout: %s' % src_dir) + +patch_dir = os.path.join(cef_dir, 'patch') +patch_cfg = os.path.join(patch_dir, 'patch.cfg') +if not os.path.isfile(patch_cfg): + raise Exception('File does not exist: %s' % patch_cfg) + +# Read the patch configuration file. +msg('Reading patch config %s' % patch_cfg) +scope = {} +execfile(patch_cfg, scope) +patches = scope["patches"] + +# Read each individual patch file. +patches_dir = os.path.join(patch_dir, 'patches') +for patch in patches: + sys.stdout.write('\n') + patch_file = os.path.join(patches_dir, patch['name']+'.patch') + + if os.path.isfile(patch_file): + msg('Reading patch file %s' % patch_file) + patch_root = patch['path'] + patch_root_abs = os.path.abspath(os.path.join(cef_dir, patch_root)) + + # Retrieve the list of paths modified by the patch file. + patch_paths = extract_paths(patch_file) + + # List of paths added by the patch file. + added_paths = [] + + if not options.resave: + # Revert any changes to existing files in the patch. + for patch_path in patch_paths: + patch_path_abs = os.path.abspath(os.path.join(patch_root_abs, \ + patch_path)) + if os.path.exists(patch_path_abs): + msg('Reverting changes to %s' % patch_path_abs) + if src_is_git: + cmd = 'git checkout -- %s' % (patch_path_abs) + else: + cmd = 'svn revert %s' % (patch_path_abs) + result = exec_cmd(cmd, patch_root_abs) + if result['err'] != '': + msg('Failed to revert file: %s' % result['err']) + msg('Deleting file %s' % patch_path_abs) + os.remove(patch_path_abs) + added_paths.append(patch_path_abs) + if result['out'] != '': + sys.stdout.write(result['out']) + else: + msg('Skipping non-existing file %s' % patch_path_abs) + added_paths.append(patch_path_abs) + + if not options.revert: + # Apply the patch file. + msg('Applying patch to %s' % patch_root_abs) + result = exec_cmd('patch -p0', patch_root_abs, patch_file) + if result['err'] != '': + raise Exception('Failed to apply patch file: %s' % result['err']) + sys.stdout.write(result['out']) + if result['out'].find('FAILED') != -1: + warn('Failed to apply %s, fix manually and run with --resave' % \ + patch['name']) + continue + + if not options.revert: + msg('Saving changes to %s' % patch_file) + if src_is_git and added_paths: + # Inform git of the added paths so they appear in the patch file. + cmd = 'git add -N %s' % ' '.join(added_paths) + result = exec_cmd(cmd, patch_root_abs) + if result['err'] != '' and result['err'].find('warning:') != 0: + raise Exception('Failed to add paths: %s' % result['err']) + + # Re-create the patch file. + patch_paths_str = ' '.join(patch_paths) + if src_is_git: + cmd = 'git diff --no-prefix --relative %s' % patch_paths_str + else: + cmd = 'svn diff %s' % patch_paths_str + result = exec_cmd(cmd, patch_root_abs) + if result['err'] != '' and result['err'].find('warning:') != 0: + raise Exception('Failed to create patch file: %s' % result['err']) + f = open(patch_file, 'wb') + f.write(result['out']) + f.close() + else: + raise Exception('Patch file does not exist: %s' % patch_file) diff --git a/tools/patch_util.py b/tools/patch_util.py new file mode 100644 index 000000000..700884bc0 --- /dev/null +++ b/tools/patch_util.py @@ -0,0 +1,593 @@ +""" Patch utility to apply unified diffs """ +""" Brute-force line-by-line parsing + + Project home: http://code.google.com/p/python-patch/ + + This file is subject to the MIT license available here: + http://www.opensource.org/licenses/mit-license.php + + CEF Changes + ----------- + + 2013/01/03 + - Add support for patches containing new files + + 2009/07/22 + - Add a 'root_directory' argument to PatchInfo::apply + - Fix a Python 2.4 compile error in PatchInfo::parse_stream + +""" + +__author__ = "techtonik.rainforce.org" +__version__ = "8.12-1" + +import copy +import logging +import os +import re +from stat import * +# cStringIO doesn't support unicode in 2.5 +from StringIO import StringIO +from logging import debug, info, warning + +from os.path import exists, isfile +from os import unlink + +debugmode = False + + +def from_file(filename): + """ read and parse patch file + return PatchInfo() object + """ + + info("reading patch from file %s" % filename) + fp = open(filename, "rb") + patch = PatchInfo(fp) + fp.close() + return patch + + +def from_string(s): + """ parse text string and return PatchInfo() object """ + return PatchInfo( + StringIO.StringIO(s) + ) + + +class HunkInfo(object): + """ parsed hunk data (hunk starts with @@ -R +R @@) """ + + def __init__(self): + # define HunkInfo data members + self.startsrc=None + self.linessrc=None + self.starttgt=None + self.linestgt=None + self.invalid=False + self.text=[] + + def copy(self): + return copy.copy(self) + +# def apply(self, estream): +# """ write hunk data into enumerable stream +# return strings one by one until hunk is +# over +# +# enumerable stream are tuples (lineno, line) +# where lineno starts with 0 +# """ +# pass + + + + +class PatchInfo(object): + """ patch information container """ + + def __init__(self, stream=None): + """ parse incoming stream """ + + # define PatchInfo data members + # table with a row for every source file + + #: list of source filenames + self.source=None + self.target=None + #: list of lists of hunks + self.hunks=None + #: file endings statistics for every hunk + self.hunkends=None + + if stream: + self.parse_stream(stream) + + def copy(self): + return copy.copy(self) + + def parse_stream(self, stream): + """ parse unified diff """ + self.source = [] + self.target = [] + self.hunks = [] + self.hunkends = [] + + # define possible file regions that will direct the parser flow + header = False # comments before the patch body + filenames = False # lines starting with --- and +++ + + hunkhead = False # @@ -R +R @@ sequence + hunkbody = False # + hunkskip = False # skipping invalid hunk mode + + header = True + lineends = dict(lf=0, crlf=0, cr=0) + nextfileno = 0 + nexthunkno = 0 #: even if index starts with 0 user messages number hunks from 1 + + # hunkinfo holds parsed values, hunkactual - calculated + hunkinfo = HunkInfo() + hunkactual = dict(linessrc=None, linestgt=None) + + fe = enumerate(stream) + for lineno, line in fe: + + # analyze state + if header and line.startswith("--- "): + header = False + # switch to filenames state + filenames = True + #: skip hunkskip and hunkbody code until you read definition of hunkhead + if hunkbody: + # process line first + if re.match(r"^[- \+\\]", line): + # gather stats about line endings + if line.endswith("\r\n"): + self.hunkends[nextfileno-1]["crlf"] += 1 + elif line.endswith("\n"): + self.hunkends[nextfileno-1]["lf"] += 1 + elif line.endswith("\r"): + self.hunkends[nextfileno-1]["cr"] += 1 + + if line.startswith("-"): + hunkactual["linessrc"] += 1 + elif line.startswith("+"): + hunkactual["linestgt"] += 1 + elif not line.startswith("\\"): + hunkactual["linessrc"] += 1 + hunkactual["linestgt"] += 1 + hunkinfo.text.append(line) + # todo: handle \ No newline cases + else: + warning("invalid hunk no.%d at %d for target file %s" % (nexthunkno, lineno+1, self.target[nextfileno-1])) + # add hunk status node + self.hunks[nextfileno-1].append(hunkinfo.copy()) + self.hunks[nextfileno-1][nexthunkno-1]["invalid"] = True + # switch to hunkskip state + hunkbody = False + hunkskip = True + + # check exit conditions + if hunkactual["linessrc"] > hunkinfo.linessrc or hunkactual["linestgt"] > hunkinfo.linestgt: + warning("extra hunk no.%d lines at %d for target %s" % (nexthunkno, lineno+1, self.target[nextfileno-1])) + # add hunk status node + self.hunks[nextfileno-1].append(hunkinfo.copy()) + self.hunks[nextfileno-1][nexthunkno-1]["invalid"] = True + # switch to hunkskip state + hunkbody = False + hunkskip = True + elif hunkinfo.linessrc == hunkactual["linessrc"] and hunkinfo.linestgt == hunkactual["linestgt"]: + self.hunks[nextfileno-1].append(hunkinfo.copy()) + # switch to hunkskip state + hunkbody = False + hunkskip = True + + # detect mixed window/unix line ends + ends = self.hunkends[nextfileno-1] + if ((ends["cr"]!=0) + (ends["crlf"]!=0) + (ends["lf"]!=0)) > 1: + warning("inconsistent line ends in patch hunks for %s" % self.source[nextfileno-1]) + if debugmode: + debuglines = dict(ends) + debuglines.update(file=self.target[nextfileno-1], hunk=nexthunkno) + debug("crlf: %(crlf)d lf: %(lf)d cr: %(cr)d\t - file: %(file)s hunk: %(hunk)d" % debuglines) + + if hunkskip: + match = re.match("^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))?", line) + if match: + # switch to hunkhead state + hunkskip = False + hunkhead = True + elif line.startswith("--- "): + # switch to filenames state + hunkskip = False + filenames = True + if debugmode and len(self.source) > 0: + debug("- %2d hunks for %s" % (len(self.hunks[nextfileno-1]), self.source[nextfileno-1])) + + if filenames: + if line.startswith("--- "): + if nextfileno in self.source: + warning("skipping invalid patch for %s" % self.source[nextfileno]) + del self.source[nextfileno] + # double source filename line is encountered + # attempt to restart from this second line + re_filename = "^--- ([^\t]+)" + match = re.match(re_filename, line) + if not match: + warning("skipping invalid filename at line %d" % lineno) + # switch back to header state + filenames = False + header = True + else: + self.source.append(match.group(1).strip()) + elif not line.startswith("+++ "): + if nextfileno in self.source: + warning("skipping invalid patch with no target for %s" % self.source[nextfileno]) + del self.source[nextfileno] + else: + # this should be unreachable + warning("skipping invalid target patch") + filenames = False + header = True + else: + if nextfileno in self.target: + warning("skipping invalid patch - double target at line %d" % lineno) + del self.source[nextfileno] + del self.target[nextfileno] + nextfileno -= 1 + # double target filename line is encountered + # switch back to header state + filenames = False + header = True + else: + re_filename = "^\+\+\+ ([^\t]+)" + match = re.match(re_filename, line) + if not match: + warning("skipping invalid patch - no target filename at line %d" % lineno) + # switch back to header state + filenames = False + header = True + else: + self.target.append(match.group(1)) + nextfileno += 1 + # switch to hunkhead state + filenames = False + hunkhead = True + nexthunkno = 0 + self.hunks.append([]) + self.hunkends.append(lineends.copy()) + continue + + + if hunkhead: + match = re.match("^@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))?", line) + if not match: + if nextfileno-1 not in self.hunks: + warning("skipping invalid patch with no hunks for file %s" % self.target[nextfileno-1]) + # switch to header state + hunkhead = False + header = True + continue + else: + # switch to header state + hunkhead = False + header = True + else: + hunkinfo.startsrc = int(match.group(1)) + if match.group(3): + hunkinfo.linessrc = int(match.group(3)) + else: + hunkinfo.linessrc = 1 + hunkinfo.starttgt = int(match.group(4)) + if match.group(6): + hunkinfo.linestgt = int(match.group(6)) + else: + hunkinfo.linestgt = 1 + hunkinfo.invalid = False + hunkinfo.text = [] + + hunkactual["linessrc"] = hunkactual["linestgt"] = 0 + + # switch to hunkbody state + hunkhead = False + hunkbody = True + nexthunkno += 1 + continue + else: + if not hunkskip: + warning("patch file incomplete - %s" % filename) + # sys.exit(?) + else: + # duplicated message when an eof is reached + if debugmode and len(self.source) > 0: + debug("- %2d hunks for %s" % (len(self.hunks[nextfileno-1]), self.source[nextfileno-1])) + + info("total files: %d total hunks: %d" % (len(self.source), sum(len(hset) for hset in self.hunks))) + + def apply(self, root_directory = None): + """ apply parsed patch """ + + total = len(self.source) + for fileno, filename in enumerate(self.source): + + f2patch = filename + if not root_directory is None: + f2patch = root_directory + f2patch + if not exists(f2patch): + # if the patch contains a single hunk at position 0 consider it a new file + if len(self.hunks[fileno]) == 1 and self.hunks[fileno][0].startsrc == 0: + hunklines = [x[1:].rstrip("\r\n") for x in self.hunks[fileno][0].text if x[0] in " +"] + if len(hunklines) > 0: + warning("creating file %s" % (f2patch)) + f = open(f2patch, "wb") + for line in hunklines: + f.write(line + "\n") + f.close() + continue + + f2patch = self.target[fileno] + if not exists(f2patch): + warning("source/target file does not exist\n--- %s\n+++ %s" % (filename, f2patch)) + continue + if not isfile(f2patch): + warning("not a file - %s" % f2patch) + continue + filename = f2patch + + info("processing %d/%d:\t %s" % (fileno+1, total, filename)) + + # validate before patching + f2fp = open(filename) + hunkno = 0 + hunk = self.hunks[fileno][hunkno] + hunkfind = [] + hunkreplace = [] + validhunks = 0 + canpatch = False + for lineno, line in enumerate(f2fp): + if lineno+1 < hunk.startsrc: + continue + elif lineno+1 == hunk.startsrc: + hunkfind = [x[1:].rstrip("\r\n") for x in hunk.text if x[0] in " -"] + hunkreplace = [x[1:].rstrip("\r\n") for x in hunk.text if x[0] in " +"] + #pprint(hunkreplace) + hunklineno = 0 + + # todo \ No newline at end of file + + # check hunks in source file + if lineno+1 < hunk.startsrc+len(hunkfind)-1: + if line.rstrip("\r\n") == hunkfind[hunklineno]: + hunklineno+=1 + else: + debug("hunk no.%d doesn't match source file %s" % (hunkno+1, filename)) + # file may be already patched, but we will check other hunks anyway + hunkno += 1 + if hunkno < len(self.hunks[fileno]): + hunk = self.hunks[fileno][hunkno] + continue + else: + break + + # check if processed line is the last line + if lineno+1 == hunk.startsrc+len(hunkfind)-1: + debug("file %s hunk no.%d -- is ready to be patched" % (filename, hunkno+1)) + hunkno+=1 + validhunks+=1 + if hunkno < len(self.hunks[fileno]): + hunk = self.hunks[fileno][hunkno] + else: + if validhunks == len(self.hunks[fileno]): + # patch file + canpatch = True + break + else: + if hunkno < len(self.hunks[fileno]) and \ + (len(self.hunks[fileno]) != 1 or self.hunks[fileno][0].startsrc != 0): + warning("premature end of source file %s at hunk %d" % (filename, hunkno+1)) + + f2fp.close() + + if validhunks < len(self.hunks[fileno]): + if check_patched(filename, self.hunks[fileno]): + warning("already patched %s" % filename) + else: + warning("source file is different - %s" % filename) + if canpatch: + backupname = filename+".orig" + if exists(backupname): + warning("can't backup original file to %s - aborting" % backupname) + else: + import shutil + shutil.move(filename, backupname) + if patch_hunks(backupname, filename, self.hunks[fileno]): + warning("successfully patched %s" % filename) + unlink(backupname) + else: + warning("error patching file %s" % filename) + shutil.copy(filename, filename+".invalid") + warning("invalid version is saved to %s" % filename+".invalid") + # todo: proper rejects + shutil.move(backupname, filename) + + # todo: check for premature eof + + + +def check_patched(filename, hunks): + matched = True + fp = open(filename) + + class NoMatch(Exception): + pass + + # special case for new files + try: + if len(hunks) == 1 and hunks[0].startsrc == 0: + hunklines = [x[1:].rstrip("\r\n") for x in hunks[0].text if x[0] in " +"] + if len(hunklines) > 0: + for line in hunklines: + srcline = fp.readline() + if not len(srcline) or srcline.rstrip("\r\n") != line: + raise NoMatch + srcline = fp.readline() + if len(srcline): + raise NoMatch + fp.close() + return True + except NoMatch: + fp.close() + fp = open(filename) + + lineno = 1 + line = fp.readline() + hno = None + try: + if not len(line): + raise NoMatch + for hno, h in enumerate(hunks): + # skip to line just before hunk starts + while lineno < h.starttgt-1: + line = fp.readline() + lineno += 1 + if not len(line): + raise NoMatch + for hline in h.text: + # todo: \ No newline at the end of file + if not hline.startswith("-") and not hline.startswith("\\"): + line = fp.readline() + lineno += 1 + if not len(line): + raise NoMatch + if line.rstrip("\r\n") != hline[1:].rstrip("\r\n"): + warning("file is not patched - failed hunk: %d" % (hno+1)) + raise NoMatch + except NoMatch: + matched = False + # todo: display failed hunk, i.e. expected/found + + fp.close() + return matched + + + +def patch_stream(instream, hunks): + """ given a source stream and hunks iterable, yield patched stream + + converts lineends in hunk lines to the best suitable format + autodetected from input + """ + + # todo: At the moment substituted lineends may not be the same + # at the start and at the end of patching. Also issue a + # warning/throw about mixed lineends (is it really needed?) + + hunks = iter(hunks) + + srclineno = 1 + + lineends = {'\n':0, '\r\n':0, '\r':0} + def get_line(): + """ + local utility function - return line from source stream + collecting line end statistics on the way + """ + line = instream.readline() + # 'U' mode works only with text files + if line.endswith("\r\n"): + lineends["\r\n"] += 1 + elif line.endswith("\n"): + lineends["\n"] += 1 + elif line.endswith("\r"): + lineends["\r"] += 1 + return line + + + for hno, h in enumerate(hunks): + debug("hunk %d" % (hno+1)) + # skip to line just before hunk starts + while srclineno < h.startsrc: + yield get_line() + srclineno += 1 + + for hline in h.text: + # todo: check \ No newline at the end of file + if hline.startswith("-") or hline.startswith("\\"): + get_line() + srclineno += 1 + continue + else: + if not hline.startswith("+"): + get_line() + srclineno += 1 + line2write = hline[1:] + # detect if line ends are consistent in source file + if sum([bool(lineends[x]) for x in lineends]) == 1: + newline = [x for x in lineends if lineends[x] != 0][0] + yield line2write.rstrip("\r\n")+newline + else: # newlines are mixed + yield line2write + + for line in instream: + yield line + + + +def patch_hunks(srcname, tgtname, hunks): + # get the current file mode + mode = os.stat(srcname)[ST_MODE] + + src = open(srcname, "rb") + tgt = open(tgtname, "wb") + + debug("processing target file %s" % tgtname) + + tgt.writelines(patch_stream(src, hunks)) + + tgt.close() + src.close() + + # restore the file mode + os.chmod(tgtname, mode) + + return True + + + + + + +from optparse import OptionParser +from os.path import exists +import sys + +if __name__ == "__main__": + opt = OptionParser(usage="%prog [options] unipatch-file", version="python-patch %s" % __version__) + opt.add_option("-d", action="store_true", dest="debugmode", help="debug mode") + (options, args) = opt.parse_args() + + if not args: + opt.print_version() + print("") + opt.print_help() + sys.exit() + debugmode = options.debugmode + patchfile = args[0] + if not exists(patchfile) or not isfile(patchfile): + sys.exit("patch file does not exist - %s" % patchfile) + + + if debugmode: + logging.basicConfig(level=logging.DEBUG, format="%(levelname)8s %(message)s") + else: + logging.basicConfig(level=logging.INFO, format="%(message)s") + + + + patch = from_file(patchfile) + #pprint(patch) + patch.apply() + + # todo: document and test line ends handling logic - patch.py detects proper line-endings + # for inserted hunks and issues a warning if patched file has incosistent line ends diff --git a/tools/patcher.README.txt b/tools/patcher.README.txt new file mode 100644 index 000000000..2078770a4 --- /dev/null +++ b/tools/patcher.README.txt @@ -0,0 +1,32 @@ +Chromium Embedded Framework (CEF) Patch Application Tool -- patcher.py +------------------------------------------------------------------------------- + +Document Last Updated: July 23, 2009 + + +OVERVIEW +-------- + +The CEF patch application tool is used by the patch project to apply patches +to the Chromium and WebKit code bases. Currently only unified diff format is +supported. See the README.txt file in the patch directory for information on +how the patch project uses this tool. + +The 'patcher.bat' file can be used to run the patch application tool with +command-line arguments that match the default CEF directory structure and +output options. Run 'patcher.py -h' for a complete list of available command- +line arguments. + + +CREDITS +------- + +Thanks go to techtonik for developing the python-patch script. The +patch_util.py file is a slightly modified version of the original script which +can be found here: http://code.google.com/p/python-patch/ + + +WORK REMAINING +-------------- + +o Add support for the GIT patch format. diff --git a/tools/patcher.py b/tools/patcher.py new file mode 100644 index 000000000..09cb9c5fa --- /dev/null +++ b/tools/patcher.py @@ -0,0 +1,103 @@ +# Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +import pickle +from optparse import OptionParser +import os +import sys +from file_util import * +from patch_util import * + + +# cannot be loaded as a module +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + + +# parse command-line options +disc = """ +This utility applies patch files. +""" + +parser = OptionParser(description=disc) +parser.add_option('--patch-config', dest='patchconfig', metavar='DIR', + help='patch configuration file') +(options, args) = parser.parse_args() + +# the patchconfig option is required +if options.patchconfig is None: + parser.print_help(sys.stdout) + sys.exit() + +# normalize the patch directory value +patchdir = os.path.dirname(os.path.abspath(options.patchconfig)).replace('\\', '/') +if patchdir[-1] != '/': + patchdir += '/' + +# check if the patching should be skipped +if os.path.isfile(patchdir + 'NOPATCH'): + nopatch = True + sys.stdout.write('NOPATCH exists -- files have not been patched.\n') +else: + nopatch = False + # locate the patch configuration file + if not os.path.isfile(options.patchconfig): + sys.stderr.write('File '+options.patchconfig+' does not exist.\n') + sys.exit() + + scope = {} + execfile(options.patchconfig, scope) + patches = scope["patches"] + + for patch in patches: + file = patchdir+'patches/'+patch['name']+'.patch' + dopatch = True + + if 'condition' in patch: + # Check that the environment variable is set. + if patch['condition'] not in os.environ: + sys.stderr.write('Skipping patch file '+file+'\n') + dopatch = False + + if dopatch: + if not os.path.isfile(file): + sys.stderr.write('Patch file '+file+' does not exist.\n') + else: + sys.stderr.write('Reading patch file '+file+'\n') + dir = patch['path'] + patchObj = from_file(file) + patchObj.apply(dir) + if 'note' in patch: + separator = '-' * 79 + '\n' + sys.stderr.write(separator) + sys.stderr.write('NOTE: '+patch['note']+'\n') + sys.stderr.write(separator) + +# read the current include file, if any +incfile = patchdir + 'patch_state.h' +if nopatch: + incnew = """// This file is generated by the patch tool and should not be edited manually. +#ifndef _PATCH_STATE_H +#define _PATCH_STATE_H +// No patches have been applied to the Chromium/WebKit source base. +#define CEF_PATCHES_APPLIED 0 +#endif // _PATCH_STATE_H +""" +else: + incnew = """// This file is generated by the patch tool and should not be edited manually. +#ifndef _PATCH_STATE_H +#define _PATCH_STATE_H +// Patches have been applied to the Chromium/WebKit source base. +#define CEF_PATCHES_APPLIED 1 +#endif // _PATCH_STATE_H +""" + +inccur = '' +if os.path.isfile(incfile): + inccur = read_file(incfile) + +if inccur != incnew: + sys.stdout.write('Writing file '+incfile+'.\n') + write_file(incfile, incnew) \ No newline at end of file diff --git a/tools/repack_locales.py b/tools/repack_locales.py new file mode 100644 index 000000000..2e5014645 --- /dev/null +++ b/tools/repack_locales.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Helper script to repack paks for a list of locales. + +Gyp doesn't have any built-in looping capability, so this just provides a way to +loop over a list of locales when repacking pak files, thus avoiding a +proliferation of mostly duplicate, cut-n-paste gyp actions. +""" + +import getopt +import os +import sys + +sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', + 'tools', 'grit')) +from grit.format import data_pack + +# Some build paths defined by gyp. +GRIT_DIR = None +SHARE_INT_DIR = None +INT_DIR = None + + +class Usage(Exception): + def __init__(self, msg): + self.msg = msg + + +def calc_output(locale, create_dir): + """Determine the file that will be generated for the given locale.""" + #e.g. '<(INTERMEDIATE_DIR)/da.pak', + # For Fake Bidi, generate it at a fixed path so that tests can safely + # reference it. + if locale == 'fake-bidi': + return '%s/%s.pak' % (INT_DIR, locale) + if sys.platform in ('darwin',): + # For Cocoa to find the locale at runtime, it needs to use '_' instead + # of '-' (http://crbug.com/20441). Also, 'en-US' should be represented + # simply as 'en' (http://crbug.com/19165, http://crbug.com/25578). + if locale == 'en-US': + locale = 'en' + dir = '%s/%s.lproj' % (INT_DIR, locale.replace('-', '_')) + if create_dir and not os.path.exists(dir): + os.makedirs(dir) + return dir + '/locale.pak' + else: + return os.path.join(INT_DIR, locale + '.pak') + + +def calc_inputs(locale): + """Determine the files that need processing for the given locale.""" + inputs = [] + + #e.g. + # '<(SHARED_INTERMEDIATE_DIR)/components/strings/components_strings_da.pak' + inputs.append(os.path.join(SHARE_INT_DIR, 'components', 'strings', + 'components_strings_%s.pak' % locale)) + + #e.g. + # '<(SHARED_INTERMEDIATE_DIR)/content/app/strings/content_strings_da.pak' + inputs.append(os.path.join(SHARE_INT_DIR, 'content', 'app', 'strings', + 'content_strings_%s.pak' % locale)) + + #e.g. '<(SHARED_INTERMEDIATE_DIR)/ui/strings/ui_strings_da.pak', + inputs.append(os.path.join(SHARE_INT_DIR, 'ui', 'strings', + 'ui_strings_%s.pak' % locale)) + + #e.g. '<(SHARED_INTERMEDIATE_DIR)/ui/strings/app_locale_settings_da.pak', + inputs.append(os.path.join(SHARE_INT_DIR, 'ui', 'strings', + 'app_locale_settings_%s.pak' % locale)) + + #e.g. '<(SHARED_INTERMEDIATE_DIR)/cef/cef_strings_da.pak' + inputs.append(os.path.join(SHARE_INT_DIR, 'cef', + 'cef_strings_%s.pak' % locale)) + + return inputs + + +def list_outputs(locales): + """Returns the names of files that will be generated for the given locales. + + This is to provide gyp the list of output files, so build targets can + properly track what needs to be built. + """ + outputs = [] + for locale in locales: + outputs.append(calc_output(locale, False)) + # Quote each element so filename spaces don't mess up gyp's attempt to parse + # it into a list. + return " ".join(['"%s"' % x for x in outputs]) + + +def list_inputs(locales): + """Returns the names of files that will be processed for the given locales. + + This is to provide gyp the list of input files, so build targets can properly + track their prerequisites. + """ + inputs = [] + for locale in locales: + inputs += calc_inputs(locale) + # Quote each element so filename spaces don't mess up gyp's attempt to parse + # it into a list. + return " ".join(['"%s"' % x for x in inputs]) + + +def repack_locales(locales): + """ Loop over and repack the given locales.""" + for locale in locales: + inputs = [] + inputs += calc_inputs(locale) + output = calc_output(locale, True) + data_pack.DataPack.RePack(output, inputs) + + +def DoMain(argv): + global GRIT_DIR + global SHARE_INT_DIR + global INT_DIR + + short_options = 'iog:s:x:b:h' + long_options = 'help' + + print_inputs = False + print_outputs = False + usage_msg = '' + + helpstr = """\ +Usage: %s [-h] [-i | -o] -g -x -s [...] + -h, --help Print this help, then exit. + -i Print the expected input file list, then exit. + -o Print the expected output file list, then exit. + -g DIR GRIT build files output directory. + -x DIR Intermediate build files output directory. + -s DIR Shared intermediate build files output directory. + locale [...] One or more locales to repack.""" % ( + os.path.basename(__file__)) + + try: + opts, locales = getopt.getopt(argv, short_options, long_options) + except getopt.GetoptError, msg: + raise Usage(str(msg)) + + if not locales: + usage_msg = 'Please specificy at least one locale to process.\n' + + for o, a in opts: + if o in ('-i'): + print_inputs = True + elif o in ('-o'): + print_outputs = True + elif o in ('-g'): + GRIT_DIR = a + elif o in ('-s'): + SHARE_INT_DIR = a + elif o in ('-x'): + INT_DIR = a + elif o in ('-h', '--help'): + raise Usage(helpstr) + + if not (GRIT_DIR and INT_DIR and SHARE_INT_DIR): + usage_msg += 'Please specify all of "-g" and "-x" and "-s".\n' + if print_inputs and print_outputs: + usage_msg += 'Please specify only one of "-i" or "-o".\n' + + if usage_msg: + raise Usage(usage_msg) + + if print_inputs: + return list_inputs(locales) + + if print_outputs: + return list_outputs(locales) + + if not os.path.exists(INT_DIR): + os.makedirs(INT_DIR) + + return repack_locales(locales) + +if __name__ == '__main__': + results = DoMain(sys.argv[1:]) + if results: + print results diff --git a/tools/revision.py b/tools/revision.py new file mode 100644 index 000000000..1d946029f --- /dev/null +++ b/tools/revision.py @@ -0,0 +1,22 @@ +# Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +import svn_util as svn +import git_util as git +import os +import sys + +# cannot be loaded as a module +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + +if os.path.exists(os.path.join('.', '.svn')): + sys.stdout.write(svn.get_revision()) +elif os.path.exists(os.path.join('.', '.git')): + sys.stdout.write(git.get_svn_revision()) +else: + raise Exception('Not a valid checkout') + + diff --git a/tools/setup_toolchain.py b/tools/setup_toolchain.py new file mode 100644 index 000000000..9e0bb8dca --- /dev/null +++ b/tools/setup_toolchain.py @@ -0,0 +1,112 @@ +# Copyright (c) 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import errno +import os +import re +import subprocess +import sys + +""" +Copies the given "win tool" (which the toolchain uses to wrap compiler +invocations) and the environment blocks for the 32-bit and 64-bit builds on +Windows to the build directory. + +The arguments are the visual studio install location and the location of the +win tool. The script assumes that the root build directory is the current dir +and the files will be written to the current directory. +""" + + +def ExtractImportantEnvironment(): + """Extracts environment variables required for the toolchain from the + current environment.""" + # This list should be kept synchronized with _ExtractImportantEnvironment from + # tools/gyp/pylib/gyp/msvs_emulation.py. + envvars_to_save = ( + 'goma_.*', # TODO(scottmg): This is ugly, but needed for goma. + 'include', # Needed by midl compiler. + 'lib', + 'libpath', + 'path', + 'pathext', + 'systemroot', + 'temp', + 'tmp', + ) + result = {} + for envvar in envvars_to_save: + if envvar in os.environ: + envvar = envvar.lower() + if envvar == 'path': + # Our own rules (for running gyp-win-tool) and other actions in + # Chromium rely on python being in the path. Add the path to this + # python here so that if it's not in the path when ninja is run + # later, python will still be found. + result[envvar.upper()] = os.path.dirname(sys.executable) + \ + os.pathsep + os.environ[envvar] + else: + result[envvar.upper()] = os.environ[envvar] + for required in ('SYSTEMROOT', 'TEMP', 'TMP'): + if required not in result: + raise Exception('Environment variable "%s" ' + 'required to be set to valid path' % required) + return result + + +def FormatAsEnvironmentBlock(envvar_dict): + """Format as an 'environment block' directly suitable for CreateProcess. + Briefly this is a list of key=value\0, terminated by an additional \0. See + CreateProcess documentation for more details.""" + block = '' + nul = '\0' + for key, value in envvar_dict.iteritems(): + block += key + '=' + value + nul + block += nul + return block + + +def CopyTool(source_path): + """Copies the given tool to the current directory, including a warning not + to edit it.""" + with open(source_path) as source_file: + tool_source = source_file.readlines() + + # Add header and write it out to the current directory (which should be the + # root build dir). + with open("gyp-win-tool", 'w') as tool_file: + tool_file.write(''.join([tool_source[0], + '# Generated by setup_toolchain.py do not edit.\n'] + + tool_source[1:])) + +if len(sys.argv) != 4: + print('Usage setup_toolchain.py ' + ' ') + sys.exit(2) +vs_path = sys.argv[1] +tool_source = sys.argv[2] +win_sdk_path = sys.argv[3] + +CopyTool(tool_source) + +important_env_vars = ExtractImportantEnvironment() +path = important_env_vars["PATH"].split(";") + +# Add 32-bit compiler path to the beginning and write the block. +path32 = [os.path.join(vs_path, "VC\\BIN\\amd64_x86")] + \ + [os.path.join(win_sdk_path, "bin\\x86")] + \ + path +important_env_vars["PATH"] = ";".join(path32) +environ = FormatAsEnvironmentBlock(important_env_vars) +with open('environment.x86', 'wb') as env_file: + env_file.write(environ) + +# Add 64-bit compiler path to the beginning and write the block. +path64 = [os.path.join(vs_path, "VC\\BIN\\amd64")] + \ + [os.path.join(win_sdk_path, "bin\\x64")] + \ + path +important_env_vars["PATH"] = ";".join(path64) +environ = FormatAsEnvironmentBlock(important_env_vars) +with open('environment.x64', 'wb') as env_file: + env_file.write(environ) diff --git a/tools/svn_util.py b/tools/svn_util.py new file mode 100644 index 000000000..a0d00337a --- /dev/null +++ b/tools/svn_util.py @@ -0,0 +1,60 @@ +# Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file + +from exec_util import exec_cmd +import os +import urllib +import xml.etree.ElementTree as ET + +def is_checkout(path): + """ Returns true if the path represents an svn checkout. """ + return os.path.exists(os.path.join(path, '.svn')) + +def check_url(url): + """ Check the URL and raise an exception if invalid. """ + if ':' in url[:7]: + parts = url.split(':', 1) + if (parts[0] == 'http' or parts[0] == 'https' or parts[0] == 'svn') and \ + parts[1] == urllib.quote(parts[1]): + return url + raise Exception('Invalid URL: %s' % (url)) + +def get_svn_info(path = '.'): + """ Retrieves the URL and revision from svn info. """ + url = 'None' + rev = 'None' + cmd = "svn info --xml %s" % (path) + is_http = path[0:4] == 'http' + if is_http or os.path.exists(path): + result = exec_cmd(cmd, path if not is_http else '.') + if result['err'] == '': + tree = ET.ElementTree(ET.fromstring(result['out'])) + entry = tree.getroot().find('entry') + url = entry.find('url').text + rev = entry.attrib['revision'] + else: + raise Exception("Failed to execute svn info: %s" % (result['err'])) + return {'url': url, 'revision': rev} + +def get_revision(path = '.'): + """ Retrieves the revision from svn info. """ + info = get_svn_info(path) + if info['revision'] == 'None': + raise Exception('Unable to retrieve SVN revision for %s' % (path)) + return info['revision'] + +def get_changed_files(path = '.'): + """ Retrieves the list of changed files from svn status. """ + files = [] + if os.path.exists(path): + try: + stream = os.popen('svn status '+path) + for line in stream: + status = line[0] + # Return paths with add, modify and switch status. + if status == 'A' or status == 'M' or status == 'S': + files.append(line[8:].strip()) + except IOError, (errno, strerror): + raise + return files diff --git a/tools/translator.README.txt b/tools/translator.README.txt new file mode 100644 index 000000000..2be478f36 --- /dev/null +++ b/tools/translator.README.txt @@ -0,0 +1,1697 @@ +Chromium Embedded Framework (CEF) Translator Tool -- translator.py +------------------------------------------------------------------------------- + +Document Last Updated: February 14, 2012 + + +OVERVIEW +-------- + +The CEF translator tool automatically generates CEF source code based on the +contents of the CEF header file (cef.h). The generated source code includes the +main C API header file (cef_capi.h) and all files in the libcef_dll/cpptoc and +libcef_dll/ctocpp directories. + +If any differences are detected between the new translator-generated output and +the file that currently exists on disk a backup of the existing file will be +created before the new file is written (this behavior can be controlled using +a command-line switch -- see 'translator.py -h' for more information). Header +files (*.h) are completely generated by the translator and should never be +edited by hand. Implementation files (*.cc) may contain user-created content +within method and function body blocks. The user-created content is extracted +from the existing file and inserted into the new translator-generated file. Any +differences between existing method/function prototypes and new method/function +prototypes in manually edited implementations will be noted as a warning in new +output file. + + // WARNING - CHANGED ATTRIBUTES + // REMOVED: const wchar_t* key + // ADDED: int index + // WARNING - CHANGED RETURN VALUE + // WAS: void + // NOW: int + #pragma message("Warning: "__FILE__": MyFunction prototype has changed") + +Auto-generated implementations will be added in the new output file for any +methods/functions that exist in the CEF header file but did not exist in the +current on-disk implementation file. Each time the translator re-generates the +implementation file it will warn if an implementation could not be auto- +generated. Delete the indicated portion of the generated code after adding the +implementation manually. + + size_t CEF_CALLBACK frame_new_func(struct _cef_frame_t* self) + { + // BEGIN DELETE BEFORE MODIFYING + // AUTO-GENERATED CONTENT + #pragma message("Warning: "__FILE__": frame_new_func is not implemented") + // END DELETE BEFORE MODIFYING + } + +If the complete function or method implementation has been auto-generated the +body of the function or method will contain the following comment. + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + +If you edit the implementation manually you should remove this comment so that +CEF will not discard your changes on the next run of the translator tool. + +The 'translator.[bat|sh]' file can be used to run the translator tool with +command- line arguments that match the default CEF directory structure and +output options. Run 'translator.py -h' for a complete list of available command- +line arguments. + + +HEADER ATTRIBUTES +----------------- + +Comment-based attribute tags are added before each function, class and method +definition in the CEF header file to provide the translator with additional +information about how the output should be generated. The attribute tags must +be in the form of a comma-delimited list of name=value pairs. Attribute names +and values must contain only alpha-numeric characters, numbers and underscores, +and must all exist on a single line. + + /*--cef(name1=value1,name2=value2,name3=value3)--*/ + +Supported method/function attributes: + + capi_name=[string] (Optional) Force a specific output name for the + resulting C API function. + optional_param=[param] (Optional) Parameter name that will be optional + instead of required. + index_param=[param] (Optional) Parameter name representing an index + value that will be verified as >= 0. + default_retval=[string] (Required for enumeration types, Optional for other + types) Specify the default return value. + count_func=[param:func] (Required for non-const non-string std::vector + types) Specify the C++ function that returns the + count of elements for a vector parameter. + api_hash_check (Optional) If set an API hash check will be added + to the CToCpp version of the method/function. + +Supported class attributes: + + source=[library|client] (Required) Indicates whether the class + implementation is provided by the library or the + client. This effects the generation of guard + blocks in the cpptoc and ctocpp header files. + no_debugct_check (Optional) If set the debug reference count + of the object will not be checked on shutdown. + + +TRANSLATION RULES +----------------- + +All C++ names in the CEF header file are written in CamelCaps format and all +C API translations are generated in lowercase_underscore format. + + +Translating Classes and Methods +------------------------------- + +Class names and global function names must be prefixed with the 'Cef' string. + + Global function translation + C++: void CefShutdown() + C API: void cef_shutdown() + +The translation of a C++ class name to a C API structure name is prefixed with +'_' and postfixed with '_t'. A typedef of the C API structure to a value +without the prefixed '_' is also provided and may be used interchangeably. + + Class name translation + C++: class CefPostData + C API: typedef struct _cef_post_data_t { ... } cef_post_data_t + +The translation of a C++ virtual class method to a C API member function adds a +'self' structure pointer as the first parameter. This will always be a pointer +to the structure that contains the member function. + + Virtual method translation + C++: virtual void SetFocus(bool enable) + C API: void set_focus(struct _cef_browser_t* self, int enable) + +The translation of a C++ static class method to a C API global function +is prefixed with 'cef_classname_' where 'classname' is the +lowercase_underscore name of the class that contains the static method. Any +repeat of 'classname' in the function name is removed. + + Static method translation + C++: static CefRefPtr CreateRequest() + C API: struct _cef_request_t* cef_request_create() + +Implementation of the wrapper method/function body is generally formatted as +follows. + + Static/Global CppToC (without Return): + + CEF_EXPORT void cef_function(capi_params) + { + // Parameter Verification (Optional) + // Verify the C parameter values. + // ... + + // Parameter Translation (Optional) + // Convert C parameter values to C++ parameter values. + // ... + + // Execution + CefFunction(cpp_arams); + + // Parameter Restoration (Optional) + // Retore the C parameter values if changed. + // ... + } + + Static/Global CppToC (with Return): + + CEF_EXPORT capi_retval cef_function(capi_params) + { + // Parameter Verification (Optional) + // Verify the C parameter values. + // ... + + // Parameter Translation (Optional) + // Convert C parameter values to C++ parameter values. + // ... + + // Execution + cpp_retval _rv = CefFunction(cpp_params); + + // Parameter Restoration (Optional) + // Restore the C parameter values if changed. + // ... + + // Return Translation + // Convert the C++ return value to a C return value. + return ...; + } + + Static/Global CToCpp (without Return): + + void CefFunction(cpp_params) + { + // Parameter Verification (Optional) + // Verify the C++ parameter values. + // ... + + // Parameter Translation (Optional) + // Convert C++ parameter values to C parameter values. + // ... + + // Execution + cef_function(capi_params); + + // Parameter Restoration (Optional) + // Restore the C++ parameter values if changed. + // ... + } + + Static/Global CToCpp (with Return): + + cpp_retval CefFunction(cpp_params) + { + // Parameter Verification (Optional) + // Verify the C++ parameter values. + // ... + + // Parameter Translation (Optional) + // Convert C++ parameter values to C parameter values. + // ... + + // Execution + capi_retval _rv = cef_function(capi_params); + + // Parameter Restoration (Optional) + // Restore the C++ parameter values if changed. + // ... + + // Return Translation + // Convert the C return value to a C++ return value. + return ...; + } + + Member CppToC (without Return): + + CEF_CALLBACK void class_function(cef_class_t* self, capi_params) + { + // Parameter Verification. + // Verify the C parameter values. + DCHECK(self); + DCHECK(...); + if (!self || ...) + return; + + // Parameter Translation (Optional) + // Convert the C parameter values to C++ parameter values. + // ... + + // Execution + CefClassCppToC::Get(self)->CefFunction(cpp_params); + + // Parameter Restoration (Optional) + // Restore the C parameter values if changed. + // ... + } + + Member CppToC (with Return): + + CEF_CALLBACK capi_retval class_function(cef_class_t* self, capi_params) + { + // Parameter Verification. + // Verify the C parameter values. + DCHECK(self); + DCHECK(...); + if (!self || ...) + return default_retval; // Configured or defaulted automatically. + + // Parameter Translation (Optional) + // Convert the C parameter values to C++ parameter values. + // ... + + // Execution + cpp_retval _rv = CefClassCppToC::Get(self)->CefFunction(cpp_params); + + // Parameter Restoration (Optional) + // Restore the C parameter values if changed. + // ... + + // Return Translation + // Convert the C++ return value to a C return value. + return ...; + } + + Member CToCpp (without Return): + + void CefClassCToCpp::Function(cpp_params) + { + // Structure Verification + if (CEF_MEMBER_MISSING(struct_, function)) + return; + + // Parameter Verification (Optional) + // Verify the C++ parameter values. + // ... + + // Parameter Translation (Optional) + // Convert C++ parameter values to C parameter values. + // ... + + // Execution + struct_->class_function(struct_, capi_params); + + // Parameter Restoration (Optional) + // Restore the C++ parameter values if changed. + // ... + } + + Member CToCpp (with Return): + + cpp_retval CefClassCToCpp::Function(cpp_params) + { + // Structure Verification + if (CEF_MEMBER_MISSING(struct_, function)) + return default_retval; // Configured or defaulted automatically. + + // Parameter Verification (Optional) + // Verify the C++ parameter values. + // ... + + // Parameter Translation (Optional) + // Convert C++ parameter values to C parameter values. + // ... + + // Execution + capi_retval _rv = struct_->class_function(struct_, capi_params); + + // Parameter Restoration (Optional) + // Restore the C++ parameter values if changed. + // ... + + // Return Translation + // Convert the C return value to a C++ return value. + return ...; + } + + +Translating Data Types +---------------------- + +Data types that are available in both C++ and C are left unchanged. This +includes the 'double', 'int', 'long', 'size_t' and 'void' basic types. Other +data types have differing levels of support as indicated below. The translation +tool will terminate with an exception if it encounters a data type that it +cannot translate. + +Parameters: + + Simple/enumeration type by value (simple_byval): + C++: int value + C API: int value + + // CppToC Example + CEF_EXPORT void cef_function(int value) + { + // Execution + CefFunction(value); + } + + // CToCpp Example + void CefFunction(int value) + { + // Execution + cef_function(value); + } + + Simple/enumeration type by reference (simple_byref): + C++: int& value + C API: int* value + + // CppToC Example + CEF_EXPORT void cef_function(int* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + int valueVal = value?*value:0; + + // Execution + CefFunction(valueVal); + + // Parameter Restoration + if (value) + *value = valueVal; + } + + // CToCpp Example + void CefFunction(int& value) + { + // Execution + cef_function(&value); + } + + Simple/enumeration const type by reference (simple_byref_const): + C++: const int& value + C API: const int* value + + // CppToC Example + CEF_EXPORT void cef_function(const int* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + int valueVal = value?*value:0; + + // Execution + CefFunction(valueVal); + } + + // CToCpp Example + void CefFunction(const int& value) + { + // Execution + cef_function(&value); + } + + Simple/enumeration type by address (simple_byaddr): + C++: int* value + C API: int* value + + // CppToC Example + CEF_EXPORT void cef_function(int* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Execution + CefFunction(value); + } + + // CToCpp Example + void CefFunction(int* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Execution + cef_function(value); + } + + Boolean type by value (bool_byval): + C++: bool value + C API: int value + + // CppToC Example + CEF_EXPORT void cef_function(int value) + { + // Execution + CefFunction(value?true:false); + } + + // CToCpp Example + void CefFunction(bool value) + { + // Execution + cef_function(value); + } + + Boolean type by reference (bool_byref): + C++: bool& value + C API: int* value + + // CppToC Example + CEF_EXPORT void cef_function(int* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + bool valueBool = (value && *value)?true:false; + + // Execution + CefFunction(valueBool); + + // Parameter Restoration + if (value) + *value = valueBool?true:false; + } + + // CToCpp Example + void CefFunction(bool& value) + { + // Parameter Translation + int valueInt = value; + + // Execution + cef_function(&valueInt); + + // Parameter Restoration + value = valueInt?true:false; + } + + Boolean type by address (bool_byaddr): + C++: bool* value + C API: int* value + + // CppToC Example + CEF_EXPORT void cef_function(int* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + bool valueBool = (value && *value)?true:false; + + // Execution + CefFunction(&valueBool); + + // Parameter Restoration + if (value) + *value = valueBool?true:false; + } + + // CToCpp Example + void CefFunction(bool* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + int valueInt = value?*value:0; + + // Execution + cef_function(&valueInt); + + // Parameter Restoration + if (value) + *value = valueInt?true:false; + } + + Structure const type by reference (struct_byref_const): + C++: const CefPopupFeatures& value + C API: const cef_popup_features_t* value + + // CppToC Example + CEF_EXPORT void cef_function(const cef_popup_features_t* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + CefPopupFeatures valueObj; + // Reference the existing values instead of copying. + if (value) + valueObj.Set(*value, false); + + // Execution + CefFunction(valueObj); + } + + // CToCpp Example + void CefFunction(const CefPopupFeatures& value) + { + // Execution + cef_function(&value); + } + + Structure non-const type by reference (struct_byref): + C++: CefWindowInfo& value + C API: cef_window_info_t* value + + // CppToC Example + CEF_EXPORT void cef_function(cef_window_info_t* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + CefWindowInfo valueObj; + // Take ownership of the values. + if (value) + valueObj.AttachTo(*value); + + // Execution + CefFunction(valueObj); + + // Parameter Restoration + // Return the values to the structure. + if (value) + valueObj.DetachTo(*value); + } + + // CToCpp Example + void CefFunction(CefWindowInfo& value) + { + // Execution + cef_function(&value); + } + + String const type by reference (string_byref_const): + C++: const CefString& value + C API: const cef_string_t* value + + // CppToC Example + CEF_EXPORT void cef_function(const cef_string_t* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Execution + CefFunction(CefString(value)); + } + + // CToCpp Example + void CefFunction(const CefString& value) + { + // Execution + cef_function(value.GetStruct()); + } + + String non-const type by reference (string_byref): + C++: CefString& value + C API: cef_string_t* value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_t* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + CefString valueStr(value); + + // Execution + CefFunction(valueStr); + } + + // CToCpp Example + void CefFunction(CefString& value) + { + // Execution + cef_function(value.GetWritableStruct()); + } + + Smart pointer type same boundary side (refptr_same): + C++: CefRefPtr value + C API: cef_browser_t* value + + // CppToC Example + CEF_EXPORT void cef_function(cef_browser_t* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Execution + CefFunction(CefBrowserCppToC::Unwrap(value)); + } + + // CToCpp Example + void CefFunction(CefRefPtr value) + { + // Execution + cef_function(CefBrowserCToCpp::Unwrap(value)); + } + + Smart pointer type same boundary side by reference (refptr_same_byref): + C++: CefRefPtr& value + C API: cef_client_t** value + + // CppToC Example + CEF_EXPORT void cef_function(cef_client_t** value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + CefRefPtr valuePtr; + if (value && *value) + valuePtr = CefClientCppToC::Unwrap(*value); + CefClient* valueOrig = valuePtr.get(); + + // Execution + CefFunction(valuePtr); + + // Parameter Restoration + if (value) { + if (valuePtr.get()) { + if (valuePtr.get() != valueOrig) { + // The value has been changed. + *value = CefClientCppToC::Wrap(valuePtr); + } + } else { + *value = NULL; + } + } + } + + // CToCpp Example + void CefFunction(CefRefPtr& value) + { + // Parameter Translation + cef_client_t* valueStruct = NULL; + if(value.get()) + valueStruct = CefClientCToCpp::Unwrap(value); + cef_client_t* valueOrig = valueStruct; + + // Execution + cef_function(valueStuct); + + // Parameter Restoration + if (valueStruct) { + if (valueStruct != valueOrig) { + // The value was changed. + value = CefClientCToCpp::Wrap(valueStruct); + } + } else { + value = NULL; + } + } + + Smart pointer type different boundary side (refptr_diff): + C++: CefRefPtr value + C API: cef_browser_t* value + + // CppToC Example + CEF_EXPORT void cef_function(cef_browser_t* value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Execution + CefFunction(CefBrowserCToCpp::Wrap(value)); + } + + // CToCpp Example + void CefFunction(CefRefPtr value) + { + // Execution + cef_function(CefBrowserCppToC::Wrap(value)); + } + + Smart pointer type different boundary side by reference (refptr_diff_byref): + C++: CefRefPtr& value + C API: cef_client_t** value + + // CppToC Example + CEF_EXPORT void cef_function(cef_client_t** value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + CefRefPtr valuePtr; + if (value && *value) + valuePtr = CefClientCToCpp::Wrap(*value); + CefClient* valueOrig = valuePtr.get(); + + // Execution + CefFunction(valuePtr); + + // Parameter Restoration + if (value) { + if (valuePtr.get()) { + if (valuePtr.get() != valueOrig) { + // The value has been changed. + *value = CefClientCToCpp::Unwrap(valuePtr); + } + } else { + *value = NULL; + } + } + } + + // CToCpp Example + void CefFunction(CefRefPtr& value) + { + // Parameter Translation + cef_client_t* valueStruct = NULL; + if(value.get()) + valueStruct = CefClientCppToC::Wrap(value); + cef_client_t* valueOrig = valueStruct; + + // Execution + cef_function(valueStuct); + + // Parameter Restoration + if (valueStruct) { + if (valueStruct != valueOrig) { + // The value was changed. + value = CefClientCppToC::Unwrap(valueStruct); + } + } else { + value = NULL; + } + } + + String vector type by reference (string_vec_byref): + C++: std::vector& value + C API: cef_string_list_t value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_list_t value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + std::vector valueList; + transfer_string_list_contents(value, valueList); + + // Execution + CefFunction(valueList); + + // Parameter Restoration + cef_string_list_clear(value); + transfer_string_list_contents(valueList, value); + } + + // CToCpp Example + void CefFunction(std::vector& value) + { + // Parameter Translation + cef_string_list_t valueList = cef_string_list_alloc(); + DCHECK(valueList); + if (valueList) + transfer_string_list_contents(value, valueList); + + // Execution + cef_function(valueList); + + // Parameter Restoration + if (valueList) { + value.clear(); + transfer_string_list_contents(valueList, value); + cef_string_list_free(valueList); + } + } + + String vector const type by reference (string_vec_byref_const): + C++: const std::vector& value + C API: cef_string_list_t value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_list_t value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + std::vector valueList; + transfer_string_list_contents(value, valueList); + + // Execution + CefFunction(valueList); + } + + // CToCpp Example + void CefFunction(const std::vector& value) + { + // Parameter Translation + cef_string_list_t valueList = cef_string_list_alloc(); + DCHECK(valueList); + if (valueList) + transfer_string_list_contents(value, valueList); + + // Execution + cef_function(valueList); + + // Parameter Restoration + if (valueList) + cef_string_list_free(valueList); + } + + String-to-string single map type by reference (string_map_single_byref): + C++: std::map& value + C API: cef_string_map_t value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_map_t value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + std::map valueMap; + transfer_string_map_contents(value, valueMap); + + // Execution + CefFunction(valueMap); + + // Parameter Restoration + cef_string_map_clear(value); + transfer_string_map_contents(valueMap, value); + } + + // CToCpp Example + void CefFunction(std::map& value) + { + // Parameter Translation + cef_string_map_t valueMap = cef_string_map_alloc(); + DCHECK(valueMap); + if (valueMap) + transfer_string_map_contents(value, valueMap); + + // Execution + cef_function(valueMap); + + // Parameter Restoration + if (valueMap) { + value.clear(); + transfer_string_map_contents(valueMap, value); + cef_string_map_free(valueMap); + } + } + + String-to-string single map const type by reference + (string_map_single_byref_const): + C++: const std::map& value + C API: cef_string_map_t value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_map_t value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + std::map valueMap; + transfer_string_map_contents(value, valueMap); + + // Execution + CefFunction(valueMap); + } + + // CToCpp Example + void CefFunction(const std::map& value) + { + // Parameter Translation + cef_string_map_t valueMap = cef_string_map_alloc(); + DCHECK(valueMap); + if (valueMap) + transfer_string_map_contents(value, valueMap); + + // Execution + cef_function(valueMap); + + // Parameter Restoration + if (valueMap) + cef_string_map_free(valueMap); + } + + String-to-string multi map type by reference (string_map_multi_byref): + C++: std::multimap& value + C API: cef_string_multimap_t value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_multimap_t value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + std::multimap valueMultimap; + transfer_string_multimap_contents(value, valueMultimap); + + // Execution + CefFunction(valueMultimap); + + // Parameter Restoration + cef_string_multimap_clear(value); + transfer_string_multimap_contents(valueMultimap, value); + } + + // CToCpp Example + void CefFunction(std::multimap& value) + { + // Parameter Translation + cef_string_multimap_t valueMultimap = cef_string_multimap_alloc(); + DCHECK(valueMultimap); + if (valueMultimap) + transfer_string_multimap_contents(value, valueMultimap); + + // Execution + cef_function(valueMultimap); + + // Parameter Restoration + if (valueMultimap) { + value.clear(); + transfer_string_multimap_contents(valueMultimap, value); + cef_string_multimap_free(valueMultimap); + } + } + + String-to-string multi map const type by reference + (string_map_multi_byref_const): + C++: const std::multimap& value + C API: cef_string_multimap_t value + + // CppToC Example + CEF_EXPORT void cef_function(cef_string_multimap_t value) + { + // Parameter Verification + DHECK(value); + if (!value) + return; + + // Parameter Translation + std::multimap valueMultimap; + transfer_string_multimap_contents(value, valueMultimap); + + // Execution + CefFunction(valueMultimap); + } + + // CToCpp Example + void CefFunction(const std::multimap& value) + { + // Parameter Translation + cef_string_multimap_t valueMultimap = cef_string_multimap_alloc(); + DCHECK(valueMultimap); + if (valueMultimap) + transfer_string_multimap_contents(value, valueMultimap); + + // Execution + cef_function(valueMultimap); + + // Parameter Restoration + if (valueMultimap) + cef_string_multimap_free(valueMultimap); + } + + Simple/Enumeration vector non-const type by reference (simple_vec_byref): + C++: std::vector& value + C API: size_t* valueCount, int* value + + // CppToC Example + CEF_EXPORT void cef_function(size_t* valueCount, int* value) + { + // Parameter Verification + DCHECK(valueCount && (*valueCount == 0 || value)); + if (!valueCount || (*valueCount > 0 && !value)) + return; + + // Parameter Translation + std::vector valueList; + if (valueCount && *valueCount > 0 && value) { + for (size_t i = 0; i < *valueCount; ++i) + valueList.push_back(value[i]); + } + + // Execution + CefFunction(valueList); + + // Parameter Restoration + if (valueCount && value) { + *valueCount = std::min(valueList.size(), *valueCount); + if (*valueCount > 0) { + for (size_t i = 0; i < *valueCount; ++i) + value[i] = valueList[i]; + } + } + } + + // CToCpp Example + void CefFunction(std::vector& value) + { + // Parameter Translation + // Function identified by the "count_func" method attribute. + size_t valueSize = value.size(); + size_t valueCount = std::max(GetFunctionCount(), valueSize); + int* valueList = NULL; + if (valueCount > 0) { + valueList = new int[valueCount]; + DCHECK(valueList); + if (valueList) + memset(valueList, 0, sizeof(int)*valueCount); + if (valueList && valueSize > 0) { + for (size_t i = 0; i < valueSize; ++i) { + valueList[i] = value[i]; + } + } + } + + // Execution + cef_function(&valueCount, valueList); + + // Parameter Restoration + value.clear(); + if (valueCount > 0 && valueList) { + for (size_t i = 0; i < valueCount; ++i) + value.push_back(valueList[i]); + delete [] valueList; + } + } + + Simple/Enumeration vector const type by reference (simple_vec_byref_const): + C++: const std::vector& value + C API: size_t valueCount, int const* value + + // CppToC Example + CEF_EXPORT void cef_function(size_t valueCount, int const* value) + { + // Parameter Verification + DCHECK(valueCount == 0 || value); + if (valueCount > 0 && !value) + return; + + // Parameter Translation + std::vector valueList; + if (valueCount > 0) { + for (size_t i = 0; i < valueCount; ++i) + valueList.push_back(value[i]); + } + + // Execution + CefFunction(valueList); + } + + // CToCpp Example + void CefFunction(const std::vector& value) + { + // Parameter Translation + const size_t valueCount = value.size(); + int* valueList = NULL; + if (valueCount > 0) { + valueList = new int[valueCount]; + DCHECK(valueList); + if (valueList) { + for (size_t i = 0; i < valueCount; ++i) + valueList[i] = value[i]; + } + } + + // Execution + cef_function(valueCount, valueList); + + // Parameter Restoration + if (valueList) + delete [] valueList; + } + + Boolean vector non-const type by reference (bool_vec_byref): + C++: std::vector& value + C API: size_t* valueCount, int* value + + // CppToC Example + CEF_EXPORT void cef_function(size_t* valueCount, int* value) + { + // Parameter Verification + DCHECK(valueCount && (*valueCount == 0 || value)); + if (!valueCount || (*valueCount > 0 && !value)) + return; + + // Parameter Translation + std::vector valueList; + if (valueCount && *valueCount > 0 && value) { + for (size_t i = 0; i < *valueCount; ++i) + valueList.push_back(value[i]?true:false); + } + + // Execution + CefFunction(valueList); + + // Parameter Restoration + if (valueCount && value) { + *valueCount = std::min(valueList.size(), *valueCount); + if (*valueCount > 0) { + for (size_t i = 0; i < *valueCount; ++i) + value[i] = valueList[i]; + } + } + } + + // CToCpp Example + void CefFunction(std::vector& value) + { + // Parameter Translation + // Function identified by the "count_func" method attribute. + size_t valueSize = value.size(); + size_t valueCount = std::max(GetFunctionCount(), valueSize); + int* valueList = NULL; + if (valueCount > 0) { + valueList = new int[valueCount]; + DCHECK(valueList); + if (valueList) + memset(valueList, 0, sizeof(int)*valueCount); + if (valueList && valueSize > 0) { + for (size_t i = 0; i < valueSize; ++i) { + valueList[i] = value[i]; + } + } + } + + // Execution + cef_function(&valueCount, valueList); + + // Parameter Restoration + value.clear(); + if (valueCount > 0 && valueList) { + for (size_t i = 0; i < valueCount; ++i) + value.push_back(valueList[i]?true:false); + delete [] valueList; + } + } + + Boolean vector const type by reference (bool_vec_byref_const): + C++: const std::vector& value + C API: size_t valueCount, int const* value + + // CppToC Example + CEF_EXPORT void cef_function(size_t valueCount, int const* value) + { + // Parameter Verification + DCHECK(valueCount == 0 || value); + if (valueCount > 0 && !value) + return; + + // Parameter Translation + std::vector valueList; + if (valueCount > 0) { + for (size_t i = 0; i < valueCount; ++i) + valueList.push_back(value[i]?true:false); + } + + // Execution + CefFunction(valueList); + } + + // CToCpp Example + void CefFunction(const std::vector& value) + { + // Parameter Translation + const size_t valueCount = value.size(); + int* valueList = NULL; + if (valueCount > 0) { + valueList = new int[valueCount]; + DCHECK(valueList) + if (valueList) { + for (size_t i = 0; i < valueCount; ++i) + valueList[i] = value[i]; + } + } + + // Execution + cef_function(valueCount, valueList); + + // Parameter Restoration + if (valueList) + delete [] valueList; + } + + Smart pointer vector non-const type same boundary side by reference + (refptr_vec_same_byref): + C++: std::vector>& value + C API: size_t* valueCount, cef_post_data_element_t** value + + // CppToC Example + CEF_EXPORT void cef_function(size_t* valueCount, + cef_post_data_element_t** value) + { + // Parameter Verification + DCHECK(valueCount && (*valueCount == 0 || value)); + if (!valueCount || (*valueCount > 0 && !value)) + return; + + // Parameter Translation + std::vector> valueList; + if (valueCount && *valueCount > 0 && value) { + for (size_t i = 0; i < *valueCount; ++i) + valueList.push_back(CefPostDataElementCppToC::Unwrap(value[i])); + } + + // Execution + CefFunction(valueList); + + // Parameter Restoration + if (valueCount && value) { + *valueCount = std::min(valueList.size(), *valueCount); + if (*valueCount > 0) { + for (size_t i = 0; i < *valueCount; ++i) + value[i] = CefPostDataElementCppToC::Wrap(valueList[i]); + } + } + } + + // CToCpp Example + void CefFunction(std::vector& value) + { + // Parameter Translation + // Function identified by the "count_func" method attribute. + size_t valueSize = value.size(); + size_t valueCount = std::max(GetFunctionCount(), valueSize); + cef_post_data_element_t** valueList = NULL; + if (valueCount > 0) { + valueList = new cef_post_data_element_t*[valueCount]; + DCHECK(valueList); + if (valueList) + memset(valueList, 0, sizeof(cef_post_data_element_t*)*valueCount); + if (valueList && valueSize > 0) { + for (size_t i = 0; i < valueSize; ++i) { + valueList[i] = CefPostDataElementCToCpp::Unwrap(value[i]); + } + } + } + + // Execution + cef_function(&valueCount, valueList); + + // Parameter Restoration + value.clear(); + if (valueCount > 0 && valueList) { + for (size_t i = 0; i < valueCount; ++i) + value.push_back(CefPostDataElementCToCpp::Wrap(valueList[i])); + delete [] valueList; + } + } + + Smart pointer vector const type same boundary side by reference + (refptr_vec_same_byref_const): + C++: const std::vector>& value + C API: size_t valueCount, const cef_v8value_t** value + + // CppToC Example + CEF_EXPORT void cef_function(size_t valueCount, + const cef_v8value_t** value) + { + // Parameter Verification + DCHECK(valueCount == 0 || value); + if (valueCount > 0 && !value) + return; + + // Parameter Translation + std::vector> valueList; + if (valueCount > 0) { + for (size_t i = 0; i < valueCount; ++i) + valueList.push_back(CefV8ValueCppToC::Unwrap(value[i])); + } + + // Execution + CefFunction(valueList); + } + + // CToCpp Example + void CefFunction(const std::vector& value) + { + // Parameter Translation + const size_t valueCount = value.size(); + cef_v8value_t** valueList = NULL; + if (valueCount > 0) { + valueList = new int[valueCount]; + DCHECK(valueList); + if (valueList) { + for (size_t i = 0; i < valueCount; ++i) + valueList[i] = CefV8ValueCToCpp::Unwrap(value[i]); + } + } + + // Execution + cef_function(valueCount, valueList); + + // Parameter Restoration + if (valueList) + delete [] valueList; + } + + Smart pointer vector non-const type different boundary side by reference + (refptr_vec_diff_byref): + C++: std::vector>& value + C API: size_t* valueCount, cef_post_data_element_t** value + + // CppToC Example + CEF_EXPORT void cef_function(size_t* valueCount, + cef_post_data_element_t** value) + { + // Parameter Verification + DCHECK(valueCount && (*valueCount == 0 || value)); + if (!valueCount || (*valueCount > 0 && !value)) + return; + + // Parameter Translation + std::vector> valueList; + if (valueCount && *valueCount > 0 && value) { + for (size_t i = 0; i < *valueCount; ++i) + valueList.push_back(CefPostDataElementCToCpp::Wrap(value[i])); + } + + // Execution + CefFunction(valueList); + + // Parameter Restoration + if (valueCount && value) { + *valueCount = std::min(valueList.size(), *valueCount); + if (*valueCount > 0) { + for (size_t i = 0; i < *valueCount; ++i) + value[i] = CefPostDataElementCToCpp::Unwrap(valueList[i]); + } + } + } + + // CToCpp Example + void CefFunction(std::vector& value) + { + // Parameter Translation + // Function identified by the "count_func" method attribute. + size_t valueSize = value.size(); + size_t valueCount = std::max(GetFunctionCount(), valueSize); + cef_post_data_element_t** valueList = NULL; + if (valueCount > 0) { + valueList = new cef_post_data_element_t*[valueCount]; + DCHECK(valueList); + if (valueList) + memset(valueList, 0, sizeof(cef_post_data_element_t*)*valueCount); + if (valueList && valueSize > 0) { + for (size_t i = 0; i < valueSize; ++i) { + valueList[i] = CefPostDataElementCppToC::Wrap(value[i]); + } + } + } + + // Execution + cef_function(&valueCount, valueList); + + // Parameter Restoration + value.clear(); + if (valueCount > 0 && valueList) { + for (size_t i = 0; i < valueCount; ++i) + value.push_back(CefPostDataElementCppToC::Unwrap(valueList[i])); + delete [] valueList; + } + } + + Smart pointer vector const type different boundary side by reference + (refptr_vec_diff_byref_const): + C++: const std::vector>& value + C API: size_t valueCount, const cef_v8value_t** value + + // CppToC Example + CEF_EXPORT void cef_function(size_t valueCount, + const cef_v8value_t** value) + { + // Parameter Verification + DCHECK(valueCount == 0 || value); + if (valueCount > 0 && !value) + return; + + // Parameter Translation + std::vector> valueList; + if (valueCount > 0) { + for (size_t i = 0; i < valueCount; ++i) + valueList.push_back(CefV8ValueCToCpp::Wrap(value[i])); + } + + // Execution + CefFunction(valueList); + } + + // CToCpp Example + void CefFunction(const std::vector& value) + { + // Parameter Translation + const size_t valueCount = value.size(); + cef_v8value_t** valueList = NULL; + if (valueCount > 0) { + valueList = new int[valueCount]; + DCHECK(valueList); + if (valueList) { + for (size_t i = 0; i < valueCount; ++i) + valueList[i] = CefV8ValueCppToC::Wrap(value[i]); + } + } + + // Execution + cef_function(valueCount, valueList); + + // Parameter Restoration + if (valueList) + delete [] valueList; + } + +Return Values: + + Simple/Enumeration type (simple): + C++: int + C API: int + + // CppToC Example + CEF_EXPORT int cef_function() + { + // Execution + int _rv = CefFunction(); + + // Return Translation + return _rv; + } + + // CToCpp Example + int CefFunction() + { + // Execution + int _rv = cef_function(); + + // Return Translation + return _rv; + } + + Boolean type (bool): + C++: bool + C API: int + + // CppToC Example + CEF_EXPORT int cef_function() + { + // Execution + bool _rv = CefFunction(); + + // Return Translation + return _rv; + } + + // CToCpp Example + bool CefFunction() + { + // Execution + int _rv = cef_function(); + + // Return Translation + return _rv?true:false; + } + + String non-const by reference type (string): + C++: CefString + C API: cef_string_userfree_t + + // CppToC Example + CEF_EXPORT cef_string_userfree_t cef_function() + { + // Execution + CefString _rv = CefFunction(); + + // Return Translation + return _rv.DetachToUserFree(); + } + + // CToCpp Example + CefString CefFunction() + { + // Execution + cef_string_userfree_t _rv = cef_function(); + + // Return Translation + CefString _rvStr; + _rvStr.AttachToUserFree(_rv); + return _rvStr; + } + + Smart pointer type same boundary side (refptr_same): + C++: CefRefPtr + C API: cef_browser_t* + + // CppToC Example + CEF_EXPORT cef_browser_t* cef_function() + { + // Execution + CefRefPtr _rv = CefFunction(); + + // Return Translation + return CefBrowserCppToC::Wrap(_rv); + } + + // CToCpp Example + CefString CefFunction() + { + // Execution + cef_browser_t* _rv = cef_function(); + + // Return Translation + return CefBrowserCToCpp::Wrap(_rv); + } + + Smart pointer type different boundary side (refptr_diff): + C++: CefRefPtr + C API: cef_browser_t* + + // CppToC Example + CEF_EXPORT cef_browser_t* cef_function() + { + // Execution + CefRefPtr _rv = CefFunction(); + + // Return Translation + return CefBrowserCToCpp::Unwrap(_rv); + } + + // CToCpp Example + CefString CefFunction() + { + // Execution + cef_browser_t* _rv = cef_function(); + + // Return Translation + return CefBrowserCppToC::Unwrap(_rv); + } + + +Translating Comments +-------------------- + +Comments from the CEF header file are reproduced in the C API header file with +any referenced C++ types and terminology changed to reflect C API types and +terminology. + +C++: +// Create a new CefV8Value object of the specified type. These methods +// should only be called from within the JavaScript context -- either in a +// CefV8Handler::Execute() callback or a CefHandler::HandleJSBinding() +// callback. + +C API: +// Create a new cef_v8value_t object of the specified type. These functions +// should only be called from within the JavaScript context -- either in a +// cef_v8handler_t::execute() callback or a cef_handler_t::handle_jsbinding() +// callback. + +Situations where the user is responsible for freeing strings allocated and +returned by the library are also noted by comments in the C API header file. + +C API: + // The resulting string must be freed by calling cef_string_free(). + +A comment must occur immediately before the function, class or method that it +documents with no extra space in between. Comments may span multiple lines +but each line must start with the '//' comment identifier. + +C++: + // Set focus for the browser window. If |enable| is true focus will be set + // to the window. Otherwise, focus will be removed. + /*--cef()--*/ + virtual void SetFocus(bool enable) =0; + +If two comments are separated by an empty line it will be assumed that the +higher comment represents a section header and additional space will be added +before it in the translated output. + +C++: + // ARRAY METHODS - These methods are only available on arrays. + + // Returns the number of elements in the array. + /*--cef()--*/ + virtual int GetArrayLength() =0; + +Empty lines and lines with the comment identifier but no content are considered +paragraph breaks for the purposes of wrapping the translated text. Any content +indented more than one space is reproduced as-is without content translation +or wrapping. + +C++: +// Register a new V8 extension with the specified JavaScript extension code and +// handler. Functions implemented by the handler are prototyped using the +// keyword 'native'. The calling of a native function is restricted to the scope +// in which the prototype of the native function is defined. +// +// Example JavaScript extension code: +// +// // create the 'example' global object if it doesn't already exist. +// if (!example) +// example = {}; diff --git a/tools/translator.bat b/tools/translator.bat new file mode 100644 index 000000000..4e5d7727f --- /dev/null +++ b/tools/translator.bat @@ -0,0 +1,3 @@ +@echo off +call python.bat translator.py --cpp-header-dir ..\include --capi-header-dir ..\include\capi --cpptoc-global-impl ..\libcef_dll\libcef_dll.cc --ctocpp-global-impl ..\libcef_dll\wrapper\libcef_dll_wrapper.cc --cpptoc-dir ..\libcef_dll\cpptoc --ctocpp-dir ..\libcef_dll\ctocpp --gypi-file ..\cef_paths.gypi +pause \ No newline at end of file diff --git a/tools/translator.py b/tools/translator.py new file mode 100644 index 000000000..b587cf914 --- /dev/null +++ b/tools/translator.py @@ -0,0 +1,164 @@ +# Copyright (c) 2009 The Chromium Embedded Framework Authors. All rights +# reserved. Use of this source code is governed by a BSD-style license that +# can be found in the LICENSE file. + +import sys +from cef_parser import * +from make_capi_header import * +from make_cpptoc_header import * +from make_cpptoc_impl import * +from make_ctocpp_header import * +from make_ctocpp_impl import * +from make_gypi_file import * +from optparse import OptionParser + + +# cannot be loaded as a module +if __name__ != "__main__": + sys.stderr.write('This file cannot be loaded as a module!') + sys.exit() + + +# parse command-line options +disc = """ +This utility generates files for the CEF C++ to C API translation layer. +""" + +parser = OptionParser(description=disc) +parser.add_option('--cpp-header-dir', dest='cppheaderdir', metavar='DIR', + help='input directory for C++ header files [required]') +parser.add_option('--capi-header-dir', dest='capiheaderdir', metavar='DIR', + help='output directory for C API header files') +parser.add_option('--cpptoc-global-impl', dest='cpptocglobalimpl', metavar='FILE', + help='input/output file for CppToC global translations') +parser.add_option('--ctocpp-global-impl', dest='ctocppglobalimpl', metavar='FILE', + help='input/output file for CppToC global translations') +parser.add_option('--cpptoc-dir', dest='cpptocdir', metavar='DIR', + help='input/output directory for CppToC class translations') +parser.add_option('--ctocpp-dir', dest='ctocppdir', metavar='DIR', + help='input/output directory for CppToC class translations') +parser.add_option('--gypi-file', dest='gypifile', metavar='FILE', + help='output file for path information') +parser.add_option('--no-cpptoc-header', + action='store_true', dest='nocpptocheader', default=False, + help='do not output the CppToC headers') +parser.add_option('--no-cpptoc-impl', + action='store_true', dest='nocpptocimpl', default=False, + help='do not output the CppToC implementations') +parser.add_option('--no-ctocpp-header', + action='store_true', dest='noctocppheader', default=False, + help='do not output the CToCpp headers') +parser.add_option('--no-ctocpp-impl', + action='store_true', dest='noctocppimpl', default=False, + help='do not output the CToCpp implementations') +parser.add_option('--no-backup', + action='store_true', dest='nobackup', default=False, + help='do not create a backup of modified files') +parser.add_option('-c', '--classes', dest='classes', action='append', + help='only translate the specified classes') +parser.add_option('-q', '--quiet', + action='store_true', dest='quiet', default=False, + help='do not output detailed status information') +(options, args) = parser.parse_args() + +# the cppheader option is required +if options.cppheaderdir is None: + parser.print_help(sys.stdout) + sys.exit() + +# make sure the header exists +if not path_exists(options.cppheaderdir): + sys.stderr.write('File '+options.cppheaderdir+' does not exist.') + sys.exit() + +# create the header object +if not options.quiet: + sys.stdout.write('Parsing C++ headers from '+options.cppheaderdir+'...\n') +header = obj_header() +excluded_files = ['cef_application_mac.h', 'cef_version.h'] +header.add_directory(options.cppheaderdir, excluded_files) + +writect = 0 + +if not options.capiheaderdir is None: + #output the C API header + if not options.quiet: + sys.stdout.write('In C API header directory '+options.capiheaderdir+'...\n') + filenames = sorted(header.get_file_names()) + for filename in filenames: + if not options.quiet: + sys.stdout.write('Generating '+filename+' C API header...\n') + writect += write_capi_header(header, + os.path.join(options.capiheaderdir, filename), + not options.nobackup) + +# build the list of classes to parse +allclasses = header.get_class_names() +if not options.classes is None: + for cls in options.classes: + if not cls in allclasses: + sys.stderr.write('ERROR: Unknown class: '+cls) + sys.exit() + classes = options.classes +else: + classes = allclasses + +classes = sorted(classes) + +if not options.cpptocglobalimpl is None: + # output CppToC global file + if not options.quiet: + sys.stdout.write('Generating CppToC global implementation...\n') + writect += write_cpptoc_impl(header, None, options.cpptocglobalimpl, \ + not options.nobackup) + +if not options.ctocppglobalimpl is None: + # output CToCpp global file + if not options.quiet: + sys.stdout.write('Generating CToCpp global implementation...\n') + writect += write_ctocpp_impl(header, None, options.ctocppglobalimpl, \ + not options.nobackup) + +if not options.cpptocdir is None: + # output CppToC class files + if not options.quiet: + sys.stdout.write('In CppToC directory '+options.cpptocdir+'...\n') + + for cls in classes: + if not options.nocpptocheader: + if not options.quiet: + sys.stdout.write('Generating '+cls+'CppToC class header...\n') + writect += write_cpptoc_header(header, cls, options.cpptocdir, + not options.nobackup) + if not options.nocpptocimpl: + if not options.quiet: + sys.stdout.write('Generating '+cls+'CppToC class implementation...\n') + writect += write_cpptoc_impl(header, cls, options.cpptocdir, + not options.nobackup) + +if not options.ctocppdir is None: + # output CppToC class files + if not options.quiet: + sys.stdout.write('In CToCpp directory '+options.ctocppdir+'...\n') + for cls in classes: + if not options.nocpptocheader: + if not options.quiet: + sys.stdout.write('Generating '+cls+'CToCpp class header...\n') + writect += write_ctocpp_header(header, cls, options.ctocppdir, + not options.nobackup) + if not options.nocpptocimpl: + if not options.quiet: + sys.stdout.write('Generating '+cls+'CToCpp class implementation...\n') + writect += write_ctocpp_impl(header, cls, options.ctocppdir, + not options.nobackup) + +if not options.gypifile is None: + # output the gypi file + if not options.quiet: + sys.stdout.write('Generating '+options.gypifile+' file...\n') + writect += write_gypi_file(header, options.gypifile, not options.nobackup) + +if not options.quiet: + sys.stdout.write('Done - Wrote '+str(writect)+' files.\n') + + diff --git a/tools/translator.sh b/tools/translator.sh new file mode 100755 index 000000000..abd1c6e91 --- /dev/null +++ b/tools/translator.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python translator.py --cpp-header-dir ../include --capi-header-dir ../include/capi --cpptoc-global-impl ../libcef_dll/libcef_dll.cc --ctocpp-global-impl ../libcef_dll/wrapper/libcef_dll_wrapper.cc --cpptoc-dir ../libcef_dll/cpptoc --ctocpp-dir ../libcef_dll/ctocpp --gypi-file ../cef_paths.gypi