diff --git a/cef1/AUTHORS.txt b/cef1/AUTHORS.txt new file mode 100644 index 000000000..de57b19ec --- /dev/null +++ b/cef1/AUTHORS.txt @@ -0,0 +1,26 @@ +# 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 diff --git a/cef1/CHROMIUM_BUILD_COMPATIBILITY.txt b/cef1/CHROMIUM_BUILD_COMPATIBILITY.txt new file mode 100644 index 000000000..3e6458c5b --- /dev/null +++ b/cef1/CHROMIUM_BUILD_COMPATIBILITY.txt @@ -0,0 +1,20 @@ +# 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. +# +# To configure a specific Chromium URL: +# gclient config chromium_url +# +# To update to a specific Chromium revision: +# gclient sync --revision src@chromium_revision --jobs 8 --force +# +# This file is integrated with the CEF Automation Tool. See the +# tools/automate/automate.README.txt file for more information. +# +# For general gclient usage information visit: +# http://dev.chromium.org/developers/how-tos/get-the-code + +{ + 'release_url': 'http://src.chromium.org/svn/releases/21.0.1180.18', +} diff --git a/cef1/DEPS b/cef1/DEPS new file mode 100644 index 000000000..0a7dc22e3 --- /dev/null +++ b/cef1/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/cef1/LICENSE.txt b/cef1/LICENSE.txt new file mode 100644 index 000000000..7bba13707 --- /dev/null +++ b/cef1/LICENSE.txt @@ -0,0 +1,29 @@ +// Copyright (c) 2008-2011 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/cef1/cef.gyp b/cef1/cef.gyp new file mode 100644 index 000000000..faf9fce67 --- /dev/null +++ b/cef1/cef.gyp @@ -0,0 +1,866 @@ +# 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, + 'repack_locales_cmd': ['python', 'tools/repack_locales.py'], + 'grit_out_dir': '<(SHARED_INTERMEDIATE_DIR)/cef', + }, + 'conditions': [ + [ 'os_posix==1 and OS!="mac" and OS!="android" and gcc_version==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'], + }, + }], + ], + 'includes': [ + # Bring in the source file lists. + 'cef_paths2.gypi', + ], + 'targets': [ + { + 'target_name': 'cefclient', + 'type': 'executable', + 'mac_bundle': 1, + 'msvs_guid': '6617FED9-C5D4-4907-BF55-A90062A6683F', + 'dependencies': [ + '<(DEPTH)/third_party/npapi/npapi.gyp:npapi', + 'libcef', + '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' + ], + '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. + 'tests/cefclient/mac/Info.plist', + ], + 'xcode_settings': { + 'INFOPLIST_FILE': 'tests/cefclient/mac/Info.plist', + }, + 'conditions': [ + ['OS=="win"', { + 'variables': { + 'repack_path': '../tools/grit/grit/format/repack.py', + }, + 'actions': [ + { + 'action_name': 'repack_locales', + 'inputs': [ + 'tools/repack_locales.py', + # NOTE: Ideally the common command args would be shared + # amongst inputs/outputs/action, but the args include shell + # variables which need to be passed intact, and command + # expansion wants to expand the shell variables. Adding the + # explicit quoting here was the only way it seemed to work. + '>!@(<(repack_locales_cmd) -i -g \"<(grit_out_dir)\" -s \"<(SHARED_INTERMEDIATE_DIR)\" -x \"<(INTERMEDIATE_DIR)\" <(locales))', + ], + 'outputs': [ + '>!@(<(repack_locales_cmd) -o -g \"<(grit_out_dir)\" -s \"<(SHARED_INTERMEDIATE_DIR)\" -x \"<(INTERMEDIATE_DIR)\" <(locales))', + ], + 'action': [ + '<@(repack_locales_cmd)', + '-g', '<(grit_out_dir)', + '-s', '<(SHARED_INTERMEDIATE_DIR)', + '-x', '<(INTERMEDIATE_DIR)', + '<@(locales)', + ], + }, + { + # On Windows chrome.pak will contain only the inspector resources. + # Other resources are built into libcef.dll. + 'action_name': 'repack_resources', + 'variables': { + 'pak_inputs': [ + '<(grit_out_dir)/devtools_resources.pak', + ], + }, + 'inputs': [ + '<(repack_path)', + '<@(pak_inputs)', + ], + 'outputs': [ + '<(INTERMEDIATE_DIR)/repack/chrome.pak', + ], + 'action': ['python', '<(repack_path)', '<@(_outputs)', '<@(pak_inputs)'], + }, + ], + 'copies': [ + { + 'destination': '<(PRODUCT_DIR)/locales', + 'files': [ + '!@(<(repack_locales_cmd) -i -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))', + ], + 'outputs': [ + '>!@(<(repack_locales_cmd) -o -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))', + ], + 'action': [ + '<@(repack_locales_cmd)', + '-g', '<(grit_out_dir)', + '-s', '<(SHARED_INTERMEDIATE_DIR)', + '-x', '<(INTERMEDIATE_DIR)', + '<@(locales)', + ], + }, + { + 'action_name': 'repack_resources', + 'process_outputs_as_mac_bundle_resources': 1, + 'variables': { + 'pak_inputs': [ + '<(grit_out_dir)/devtools_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/net/net_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/ui/ui_resources_standard/ui_resources_standard.pak', + '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_chromium_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_resources.pak', + ], + }, + 'inputs': [ + '<(repack_path)', + '<@(pak_inputs)', + ], + 'outputs': [ + '<(INTERMEDIATE_DIR)/repack/chrome.pak', + ], + 'action': ['python', '<(repack_path)', '<@(_outputs)', '<@(pak_inputs)'], + }, + ], + 'copies': [ + { + # Add library dependencies to the bundle. + 'destination': '<(PRODUCT_DIR)/cefclient.app/Contents/MacOS/', + 'files': [ + '<(PRODUCT_DIR)/libcef.dylib', + '<(PRODUCT_DIR)/ffmpegsumo.so', + ], + }, + { + # Add the WebCore resources to the bundle. + 'destination': '<(PRODUCT_DIR)/cefclient.app/Contents/', + 'files': [ + '../third_party/WebKit/Source/WebCore/Resources/', + ], + }, + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework', + ], + }, + 'sources': [ + '<@(includes_mac)', + '<@(cefclient_sources_mac)', + ], + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'sources': [ + '<@(includes_linux)', + '<@(cefclient_sources_linux)', + ], + 'variables': { + 'repack_path': '../tools/grit/grit/format/repack.py', + }, + 'actions': [ + { + 'action_name': 'repack_locales', + 'inputs': [ + 'tools/repack_locales.py', + # NOTE: Ideally the common command args would be shared + # amongst inputs/outputs/action, but the args include shell + # variables which need to be passed intact, and command + # expansion wants to expand the shell variables. Adding the + # explicit quoting here was the only way it seemed to work. + '>!@(<(repack_locales_cmd) -i -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))', + ], + 'outputs': [ + '>!@(<(repack_locales_cmd) -o -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))', + ], + 'action': [ + '<@(repack_locales_cmd)', + '-g', '<(grit_out_dir)', + '-s', '<(SHARED_INTERMEDIATE_DIR)', + '-x', '<(INTERMEDIATE_DIR)', + '<@(locales)', + ], + }, + { + 'action_name': 'repack_resources', + 'variables': { + 'pak_inputs': [ + '<(grit_out_dir)/devtools_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/net/net_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/ui/ui_resources_standard/ui_resources_standard.pak', + '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_chromium_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_resources.pak', + ], + }, + 'inputs': [ + '<(repack_path)', + '<@(pak_inputs)', + ], + 'outputs': [ + '<(INTERMEDIATE_DIR)/repack/chrome.pak', + ], + 'action': ['python', '<(repack_path)', '<@(_outputs)', '<@(pak_inputs)'], + }, + ], + 'copies': [ + { + 'destination': '<(PRODUCT_DIR)/locales', + 'files': [ + '!@(<(repack_locales_cmd) -i -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))', + ], + 'outputs': [ + '>!@(<(repack_locales_cmd) -o -g \'<(grit_out_dir)\' -s \'<(SHARED_INTERMEDIATE_DIR)\' -x \'<(INTERMEDIATE_DIR)\' <(locales))', + ], + 'action': [ + '<@(repack_locales_cmd)', + '-g', '<(grit_out_dir)', + '-s', '<(SHARED_INTERMEDIATE_DIR)', + '-x', '<(INTERMEDIATE_DIR)', + '<@(locales)', + ], + }, + { + 'action_name': 'repack_resources', + 'process_outputs_as_mac_bundle_resources': 1, + 'variables': { + 'pak_inputs': [ + '<(grit_out_dir)/devtools_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/net/net_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/ui/ui_resources_standard/ui_resources_standard.pak', + '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_chromium_resources.pak', + '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_resources.pak', + ], + }, + 'inputs': [ + '<(repack_path)', + '<@(pak_inputs)', + ], + 'outputs': [ + '<(INTERMEDIATE_DIR)/repack/chrome.pak', + ], + 'action': ['python', '<(repack_path)', '<@(_outputs)', '<@(pak_inputs)'], + }, + ], + 'copies': [ + { + # Add library dependencies to the bundle. + 'destination': '<(PRODUCT_DIR)/cef_unittests.app/Contents/MacOS/', + 'files': [ + '<(PRODUCT_DIR)/libcef.dylib', + '<(PRODUCT_DIR)/ffmpegsumo.so', + ], + }, + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + ], + }, + 'sources': [ + 'tests/unittests/run_all_unittests_mac.mm', + ], + }], + ], + }, + { + 'target_name': 'libcef', + 'type': 'shared_library', + 'msvs_guid': 'C13650D5-CF1A-4259-BE45-B1EBA6280E47', + 'dependencies': [ + '<(DEPTH)/base/base.gyp:base', + '<(DEPTH)/base/base.gyp:base_i18n', + '<(DEPTH)/build/temp_gyp/googleurl.gyp:googleurl', + '<(DEPTH)/media/media.gyp:media', + '<(DEPTH)/net/net.gyp:net', + '<(DEPTH)/net/net.gyp:net_resources', + '<(DEPTH)/printing/printing.gyp:printing', + '<(DEPTH)/sdch/sdch.gyp:sdch', + '<(DEPTH)/skia/skia.gyp:skia', + '<(DEPTH)/third_party/bzip2/bzip2.gyp:bzip2', + '<(DEPTH)/third_party/ffmpeg/ffmpeg.gyp:ffmpeg', + '<(DEPTH)/third_party/icu/icu.gyp:icui18n', + '<(DEPTH)/third_party/icu/icu.gyp:icuuc', + '<(DEPTH)/third_party/leveldatabase/leveldatabase.gyp:leveldatabase', + '<(DEPTH)/third_party/libjpeg_turbo/libjpeg.gyp:libjpeg', + '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', + '<(DEPTH)/third_party/libxml/libxml.gyp:libxml', + '<(DEPTH)/third_party/libxslt/libxslt.gyp:libxslt', + '<(DEPTH)/third_party/modp_b64/modp_b64.gyp:modp_b64', + '<(DEPTH)/third_party/WebKit/Source/WebCore/WebCore.gyp/WebCore.gyp:webcore', + '<(DEPTH)/third_party/WebKit/Source/WebKit/chromium/WebKit.gyp:webkit', + '<(DEPTH)/third_party/zlib/zlib.gyp:zlib', + '<(DEPTH)/ui/ui.gyp:ui_resources_standard', + '<(DEPTH)/ui/ui.gyp:ui', + '<(DEPTH)/v8/tools/gyp/v8.gyp:v8', + '<(DEPTH)/webkit/support/webkit_support.gyp:appcache', + '<(DEPTH)/webkit/support/webkit_support.gyp:blob', + '<(DEPTH)/webkit/support/webkit_support.gyp:database', + '<(DEPTH)/webkit/support/webkit_support.gyp:fileapi', + '<(DEPTH)/webkit/support/webkit_support.gyp:glue', + '<(DEPTH)/webkit/support/webkit_support.gyp:quota', + '<(DEPTH)/webkit/support/webkit_support.gyp:webkit_gpu', + '<(DEPTH)/webkit/support/webkit_support.gyp:webkit_media', + '<(DEPTH)/webkit/support/webkit_support.gyp:webkit_resources', + '<(DEPTH)/webkit/support/webkit_support.gyp:webkit_strings', + '<(DEPTH)/webkit/support/webkit_support.gyp:webkit_user_agent', + 'libcef_static', + ], + 'defines': [ + 'BUILDING_CEF_SHARED', + ], + 'include_dirs': [ + '.', + ], + # Avoid "RC1102: internal error : too many arguments to RCPP" error by + # explicitly specifying a short list of resource include directories. + 'resource_include_dirs' : [ + '.', + '..', + ], + 'sources': [ + '<@(includes_common)', + '<@(includes_capi)', + '<@(libcef_sources_common)', + ], + 'xcode_settings': { + 'INSTALL_PATH': '@executable_path', + 'DYLIB_INSTALL_NAME_BASE': '@executable_path', + # 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'], + }, + 'conditions': [ + ['OS=="win"', { + 'dependencies': [ + '<(DEPTH)/base/allocator/allocator.gyp:allocator', + '<(DEPTH)/breakpad/breakpad.gyp:breakpad_handler', + '<(DEPTH)/third_party/angle/src/build_angle.gyp:libEGL', + '<(DEPTH)/third_party/angle/src/build_angle.gyp:libGLESv2', + '<(DEPTH)/ui/views/views.gyp:views', + ], + 'sources': [ + '<@(includes_win)', + '$(OutDir)/obj/global_intermediate/webkit/webkit_chromium_resources.rc', + '$(OutDir)/obj/global_intermediate/webkit/webkit_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', + }, + }, + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'dependencies':[ + '<(DEPTH)/base/allocator/allocator.gyp:allocator', + ], + 'direct_dependent_settings': { + 'cflags': [ + '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/cef1/include/capi/cef_browser_capi.h b/cef1/include/capi/cef_browser_capi.h new file mode 100644 index 000000000..eccb3f3e9 --- /dev/null +++ b/cef1/include/capi/cef_browser_capi.h @@ -0,0 +1,323 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Structure used to represent a browser window. The functions of this structure +// may be called on any thread unless otherwise indicated in the comments. +/// +typedef struct _cef_browser_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Call this function before destroying a contained browser window. This + // function performs any internal cleanup that may be needed before the + // browser window is destroyed. + /// + void (CEF_CALLBACK *parent_window_will_close)(struct _cef_browser_t* self); + + /// + // Closes this browser window. + /// + void (CEF_CALLBACK *close_browser)(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); + + /// + // 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); + + /// + // Set focus for the browser window. If |enable| is true (1) focus will be set + // to the window. Otherwise, focus will be removed. + /// + void (CEF_CALLBACK *set_focus)(struct _cef_browser_t* self, int enable); + + /// + // Retrieve the window handle for this browser. + /// + cef_window_handle_t (CEF_CALLBACK *get_window_handle)( + struct _cef_browser_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_t* self); + + /// + // 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 client for this browser. + /// + struct _cef_client_t* (CEF_CALLBACK *get_client)(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. This function should only + // be called on the UI thread. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_focused_frame)( + struct _cef_browser_t* self); + + /// + // Returns the frame with the specified name, or NULL if not found. This + // function should only be called on the UI thread. + /// + struct _cef_frame_t* (CEF_CALLBACK *get_frame)(struct _cef_browser_t* self, + const cef_string_t* name); + + /// + // Returns the names of all existing frames. This function should only be + // called on the UI thread. + /// + void (CEF_CALLBACK *get_frame_names)(struct _cef_browser_t* self, + cef_string_list_t names); + + /// + // 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. + /// + void (CEF_CALLBACK *find)(struct _cef_browser_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_t* self, + int clearSelection); + + /// + // Get the zoom level. + /// + double (CEF_CALLBACK *get_zoom_level)(struct _cef_browser_t* self); + + /// + // Change the zoom level to the specified value. + /// + void (CEF_CALLBACK *set_zoom_level)(struct _cef_browser_t* self, + double zoomLevel); + + /// + // Clear the back/forward browsing history. + /// + void (CEF_CALLBACK *clear_history)(struct _cef_browser_t* self); + + /// + // Open developer tools in its own window. + /// + void (CEF_CALLBACK *show_dev_tools)(struct _cef_browser_t* self); + + /// + // Explicitly close the developer tools window if one exists for this browser + // instance. + /// + void (CEF_CALLBACK *close_dev_tools)(struct _cef_browser_t* self); + + /// + // Returns true (1) if window rendering is disabled. + /// + int (CEF_CALLBACK *is_window_rendering_disabled)(struct _cef_browser_t* self); + + /// + // Get the size of the specified element. This function should only be called + // on the UI thread. + /// + int (CEF_CALLBACK *get_size)(struct _cef_browser_t* self, + enum cef_paint_element_type_t type, int* width, int* height); + + /// + // Set the size of the specified element. This function is only used when + // window rendering is disabled. + /// + void (CEF_CALLBACK *set_size)(struct _cef_browser_t* self, + enum cef_paint_element_type_t type, int width, int height); + + /// + // Returns true (1) if a popup is currently visible. This function should only + // be called on the UI thread. + /// + int (CEF_CALLBACK *is_popup_visible)(struct _cef_browser_t* self); + + /// + // Hide the currently visible popup, if any. + /// + void (CEF_CALLBACK *hide_popup)(struct _cef_browser_t* self); + + /// + // Invalidate the |dirtyRect| region of the view. This function is only used + // when window rendering is disabled and will result in a call to + // HandlePaint(). + /// + void (CEF_CALLBACK *invalidate)(struct _cef_browser_t* self, + const cef_rect_t* dirtyRect); + + /// + // Get the raw image data contained in the specified element without + // performing validation. The specified |width| and |height| dimensions must + // match the current element size. On Windows |buffer| must be width*height*4 + // bytes in size and represents a BGRA image with an upper-left origin. This + // function should only be called on the UI thread. + /// + int (CEF_CALLBACK *get_image)(struct _cef_browser_t* self, + enum cef_paint_element_type_t type, int width, int height, + void* buffer); + + /// + // Send a key event to the browser. + /// + void (CEF_CALLBACK *send_key_event)(struct _cef_browser_t* self, + enum cef_key_type_t type, const struct _cef_key_info_t* keyInfo, + int modifiers); + + /// + // 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_t* self, + int x, int y, enum 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_t* self, int x, + int y, 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. + /// + void (CEF_CALLBACK *send_mouse_wheel_event)(struct _cef_browser_t* self, + int x, int y, int deltaX, int deltaY); + + /// + // Send a focus event to the browser. + /// + void (CEF_CALLBACK *send_focus_event)(struct _cef_browser_t* self, + int setFocus); + + /// + // Send a capture lost event to the browser. + /// + void (CEF_CALLBACK *send_capture_lost_event)(struct _cef_browser_t* self); +} cef_browser_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. This function call will not block. +/// +CEF_EXPORT int cef_browser_create(cef_window_info_t* windowInfo, + struct _cef_client_t* client, const cef_string_t* url, + const struct _cef_browser_settings_t* settings); + +/// +// Create a new browser window using the window parameters specified by +// |windowInfo|. This function should only be called on the UI thread. +/// +CEF_EXPORT cef_browser_t* cef_browser_create_sync(cef_window_info_t* windowInfo, + struct _cef_client_t* client, const cef_string_t* url, + const struct _cef_browser_settings_t* settings); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_BROWSER_CAPI_H_ diff --git a/cef1/include/capi/cef_client_capi.h b/cef1/include/capi/cef_client_capi.h new file mode 100644 index 000000000..639acdae9 --- /dev/null +++ b/cef1/include/capi/cef_client_capi.h @@ -0,0 +1,147 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to provide handler implementations. +/// +typedef struct _cef_client_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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 browser request events. + /// + struct _cef_request_handler_t* (CEF_CALLBACK *get_request_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 focus events. + /// + struct _cef_focus_handler_t* (CEF_CALLBACK *get_focus_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 context menu events. + /// + struct _cef_menu_handler_t* (CEF_CALLBACK *get_menu_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for browser permission events. + /// + struct _cef_permission_handler_t* (CEF_CALLBACK *get_permission_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for printing events. + /// + struct _cef_print_handler_t* (CEF_CALLBACK *get_print_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 JavaScript dialog events. + /// + struct _cef_jsdialog_handler_t* (CEF_CALLBACK *get_jsdialog_handler)( + struct _cef_client_t* self); + + /// + // Return the handler for V8 context events. + /// + struct _cef_v8context_handler_t* (CEF_CALLBACK *get_v8context_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 drag events. + /// + struct _cef_drag_handler_t* (CEF_CALLBACK *get_drag_handler)( + struct _cef_client_t* self); +} cef_client_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_CLIENT_CAPI_H_ diff --git a/cef1/include/capi/cef_command_line_capi.h b/cef1/include/capi/cef_command_line_capi.h new file mode 100644 index 000000000..a5a5ea9fc --- /dev/null +++ b/cef1/include/capi/cef_command_line_capi.h @@ -0,0 +1,169 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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; + + /// + // 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); + + /// + // 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); +} cef_command_line_t; + + +/// +// Create a new cef_command_line_t instance. +/// +CEF_EXPORT cef_command_line_t* cef_command_line_create(); + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_COMMAND_LINE_CAPI_H_ diff --git a/cef1/include/capi/cef_content_filter_capi.h b/cef1/include/capi/cef_content_filter_capi.h new file mode 100644 index 000000000..e9ed878a4 --- /dev/null +++ b/cef1/include/capi/cef_content_filter_capi.h @@ -0,0 +1,80 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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_CONTENT_FILTER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_CONTENT_FILTER_CAPI_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Structure to implement for filtering response content. The functions of this +// structure will always be called on the UI thread. +/// +typedef struct _cef_content_filter_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Set |substitute_data| to the replacement for the data in |data| if data + // should be modified. + /// + void (CEF_CALLBACK *process_data)(struct _cef_content_filter_t* self, + const void* data, int data_size, + struct _cef_stream_reader_t** substitute_data); + + /// + // Called when there is no more data to be processed. It is expected that + // whatever data was retained in the last process_data() call, it should be + // returned now by setting |remainder| if appropriate. + /// + void (CEF_CALLBACK *drain)(struct _cef_content_filter_t* self, + struct _cef_stream_reader_t** remainder); +} cef_content_filter_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_CONTENT_FILTER_CAPI_H_ diff --git a/cef1/include/capi/cef_cookie_capi.h b/cef1/include/capi/cef_cookie_capi.h new file mode 100644 index 000000000..d5c6d9bb6 --- /dev/null +++ b/cef1/include/capi/cef_cookie_capi.h @@ -0,0 +1,158 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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. 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); +} 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. Returns NULL if creation fails. +/// +CEF_EXPORT cef_cookie_manager_t* cef_cookie_manager_create_manager( + const cef_string_t* path); + + +/// +// 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/cef1/include/capi/cef_display_handler_capi.h b/cef1/include/capi/cef_display_handler_capi.h new file mode 100644 index 000000000..5f2ea0fb9 --- /dev/null +++ b/cef1/include/capi/cef_display_handler_capi.h @@ -0,0 +1,117 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 the navigation state has changed. + /// + void (CEF_CALLBACK *on_nav_state_change)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, int canGoBack, int canGoForward); + + /// + // 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 size of the content area has changed. + /// + void (CEF_CALLBACK *on_contents_size_change)( + struct _cef_display_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, int width, int height); + + /// + // 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 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. + /// + 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. |text| contains the text + // that will be displayed in the status message and |type| indicates the + // status message type. + /// + void (CEF_CALLBACK *on_status_message)(struct _cef_display_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* value, + enum cef_handler_statustype_t type); + + /// + // 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/cef1/include/capi/cef_dom_capi.h b/cef1/include/capi/cef_dom_capi.h new file mode 100644 index 000000000..1807ea203 --- /dev/null +++ b/cef1/include/capi/cef_dom_capi.h @@ -0,0 +1,441 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Structure to implement for visiting the DOM. The functions of this structure +// will be called on the UI 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 UI thread. +/// +typedef struct _cef_domdocument_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the document type. + /// + enum 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 start node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_selection_start_node)( + 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 end node. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_selection_end_node)( + 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 UI thread. +/// +typedef struct _cef_domnode_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the type for this node. + /// + enum 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 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); + + /// + // Add an event listener to this node for the specified event type. If + // |useCapture| is true (1) then this listener will be considered a capturing + // listener. Capturing listeners will recieve all events of the specified type + // before the events are dispatched to any other event targets beneath the + // current node in the tree. Events which are bubbling upwards through the + // tree will not trigger a capturing listener. Separate calls to this function + // can be used to register the same listener with and without capture. See + // WebCore/dom/EventNames.h for the list of supported event types. + /// + void (CEF_CALLBACK *add_event_listener)(struct _cef_domnode_t* self, + const cef_string_t* eventType, struct _cef_domevent_listener_t* listener, + int useCapture); + + + // 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; + + +/// +// Structure used to represent a DOM event. The functions of this structure +// should only be called on the UI thread. +/// +typedef struct _cef_domevent_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the event type. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_type)(struct _cef_domevent_t* self); + + /// + // Returns the event category. + /// + enum cef_dom_event_category_t (CEF_CALLBACK *get_category)( + struct _cef_domevent_t* self); + + /// + // Returns the event processing phase. + /// + enum cef_dom_event_phase_t (CEF_CALLBACK *get_phase)( + struct _cef_domevent_t* self); + + /// + // Returns true (1) if the event can bubble up the tree. + /// + int (CEF_CALLBACK *can_bubble)(struct _cef_domevent_t* self); + + /// + // Returns true (1) if the event can be canceled. + /// + int (CEF_CALLBACK *can_cancel)(struct _cef_domevent_t* self); + + /// + // Returns the document associated with this event. + /// + struct _cef_domdocument_t* (CEF_CALLBACK *get_document)( + struct _cef_domevent_t* self); + + /// + // Returns the target of the event. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_target)( + struct _cef_domevent_t* self); + + /// + // Returns the current target of the event. + /// + struct _cef_domnode_t* (CEF_CALLBACK *get_current_target)( + struct _cef_domevent_t* self); +} cef_domevent_t; + + +/// +// Structure to implement for handling DOM events. The functions of this +// structure will be called on the UI thread. +/// +typedef struct _cef_domevent_listener_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called when an event is received. The event object passed to this function + // contains 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 *handle_event)(struct _cef_domevent_listener_t* self, + struct _cef_domevent_t* event); +} cef_domevent_listener_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DOM_CAPI_H_ diff --git a/cef1/include/capi/cef_download_handler_capi.h b/cef1/include/capi/cef_download_handler_capi.h new file mode 100644 index 000000000..50f1f4bd1 --- /dev/null +++ b/cef1/include/capi/cef_download_handler_capi.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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Structure used to handle file downloads. The functions of this structure will +// always be called on the UI thread. +/// +typedef struct _cef_download_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // A portion of the file contents have been received. This function will be + // called multiple times until the download is complete. Return |true (1)| to + // continue receiving data and |false (0)| to cancel. + /// + int (CEF_CALLBACK *received_data)(struct _cef_download_handler_t* self, + void* data, int data_size); + + /// + // The download is complete. + /// + void (CEF_CALLBACK *complete)(struct _cef_download_handler_t* self); +} cef_download_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DOWNLOAD_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_drag_data_capi.h b/cef1/include/capi/cef_drag_data_capi.h new file mode 100644 index 000000000..054e30c4b --- /dev/null +++ b/cef1/include/capi/cef_drag_data_capi.h @@ -0,0 +1,136 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 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); + + /// + // 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); +} cef_drag_data_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_DRAG_DATA_CAPI_H_ diff --git a/cef1/include/capi/cef_drag_handler_capi.h b/cef1/include/capi/cef_drag_handler_capi.h new file mode 100644 index 000000000..8e74f3586 --- /dev/null +++ b/cef1/include/capi/cef_drag_handler_capi.h @@ -0,0 +1,84 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 the browser window initiates a drag event. |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_start)(struct _cef_drag_handler_t* self, + struct _cef_browser_t* browser, struct _cef_drag_data_t* dragData, + enum cef_drag_operations_mask_t mask); + + /// + // 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, + enum 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/cef1/include/capi/cef_find_handler_capi.h b/cef1/include/capi/cef_find_handler_capi.h new file mode 100644 index 000000000..b729bd1e3 --- /dev/null +++ b/cef1/include/capi/cef_find_handler_capi.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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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_t::find(). + // |identifer| is the identifier passed to cef_browser_t::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/cef1/include/capi/cef_focus_handler_capi.h b/cef1/include/capi/cef_focus_handler_capi.h new file mode 100644 index 000000000..17de32c64 --- /dev/null +++ b/cef1/include/capi/cef_focus_handler_capi.h @@ -0,0 +1,93 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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, enum cef_handler_focus_source_t source); + + /// + // 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_focus_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_domnode_t* node); +} cef_focus_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_FOCUS_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_frame_capi.h b/cef1/include/capi/cef_frame_capi.h new file mode 100644 index 000000000..4009ac63c --- /dev/null +++ b/cef1/include/capi/cef_frame_capi.h @@ -0,0 +1,217 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Structure used to represent a frame in the browser window. The functions of +// this structure may be called on any thread unless otherwise indicated in the +// comments. +/// +typedef struct _cef_frame_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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); + + /// + // Execute printing in the this frame. The user will be prompted with the + // print dialog appropriate to the operating system. + /// + void (CEF_CALLBACK *print)(struct _cef_frame_t* self); + + /// + // Save this frame's HTML source to a temporary file and open it in the + // default text viewing application. + /// + void (CEF_CALLBACK *view_source)(struct _cef_frame_t* self); + + /// + // Returns this frame's HTML source as a string. This function should only be + // called on the UI thread. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_source)(struct _cef_frame_t* self); + + /// + // Returns this frame's display text as a string. This function should only be + // called on the UI thread. + /// + // The resulting string must be freed by calling cef_string_userfree_free(). + cef_string_userfree_t (CEF_CALLBACK *get_text)(struct _cef_frame_t* self); + + /// + // 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 optional dummy target |url|. + /// + void (CEF_CALLBACK *load_string)(struct _cef_frame_t* self, + const cef_string_t* string_val, const cef_string_t* url); + + /// + // Load the contents of |stream| with the optional dummy target |url|. + /// + void (CEF_CALLBACK *load_stream)(struct _cef_frame_t* self, + struct _cef_stream_reader_t* stream, 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* jsCode, const cef_string_t* scriptUrl, + int startLine); + + /// + // 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. This function should only be + // called on the UI thread. + /// + 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. This function should only be called on the UI thread. + /// + 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); + + /// + // Visit the DOM document. + /// + void (CEF_CALLBACK *visit_dom)(struct _cef_frame_t* self, + struct _cef_domvisitor_t* visitor); + + /// + // Get the V8 context associated with the frame. This function should only be + // called on the UI thread. + /// + struct _cef_v8context_t* (CEF_CALLBACK *get_v8context)( + struct _cef_frame_t* self); +} cef_frame_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_FRAME_CAPI_H_ diff --git a/cef1/include/capi/cef_jsdialog_handler_capi.h b/cef1/include/capi/cef_jsdialog_handler_capi.h new file mode 100644 index 000000000..36ed63ef4 --- /dev/null +++ b/cef1/include/capi/cef_jsdialog_handler_capi.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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 alert message. Return false (0) to display the + // default alert or true (1) if you displayed a custom alert. + /// + int (CEF_CALLBACK *on_jsalert)(struct _cef_jsdialog_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* message); + + /// + // Called to run a JavaScript confirm request. Return false (0) to display the + // default alert or true (1) if you displayed a custom alert. If you handled + // the alert set |retval| to true (1) if the user accepted the confirmation. + /// + int (CEF_CALLBACK *on_jsconfirm)(struct _cef_jsdialog_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* message, int* retval); + + /// + // Called to run a JavaScript prompt request. Return false (0) to display the + // default prompt or true (1) if you displayed a custom prompt. If you handled + // the prompt set |retval| to true (1) if the user accepted the prompt and + // request and |result| to the resulting value. + /// + int (CEF_CALLBACK *on_jsprompt)(struct _cef_jsdialog_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const cef_string_t* message, const cef_string_t* defaultValue, + int* retval, cef_string_t* result); +} cef_jsdialog_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_JSDIALOG_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_keyboard_handler_capi.h b/cef1/include/capi/cef_keyboard_handler_capi.h new file mode 100644 index 000000000..ff96b3312 --- /dev/null +++ b/cef1/include/capi/cef_keyboard_handler_capi.h @@ -0,0 +1,82 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 when the browser component receives a keyboard event. This function + // is called both before the event is passed to the renderer and after + // JavaScript in the page has had a chance to handle the event. |type| is the + // type of keyboard event, |code| is the windows scan-code for the event, + // |modifiers| is a set of bit- flags describing any pressed modifier keys and + // |isSystemKey| is true (1) if Windows considers this a 'system key' message + // (see http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx). If + // |isAfterJavaScript| is true (1) then JavaScript in the page has had a + // chance to handle the event and has chosen not to. Only RAWKEYDOWN, KEYDOWN + // and CHAR events will be sent with |isAfterJavaScript| set to true (1). + // Return true (1) if the keyboard event was handled or false (0) to allow + // continued handling of the event by the renderer. + /// + int (CEF_CALLBACK *on_key_event)(struct _cef_keyboard_handler_t* self, + struct _cef_browser_t* browser, enum cef_handler_keyevent_type_t type, + int code, int modifiers, int isSystemKey, int isAfterJavaScript); +} cef_keyboard_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_KEYBOARD_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_life_span_handler_capi.h b/cef1/include/capi/cef_life_span_handler_capi.h new file mode 100644 index 000000000..be5fe1290 --- /dev/null +++ b/cef1/include/capi/cef_life_span_handler_capi.h @@ -0,0 +1,114 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle events related to browser life span. The +// functions of this structure will be called on the UI thread. +/// +typedef struct _cef_life_span_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called before a new popup window is created. The |parentBrowser| parameter + // will point to the parent browser window. The |popupFeatures| parameter will + // contain information about the style of popup window requested. Return false + // (0) to have the framework create the new popup window based on the + // parameters in |windowInfo|. Return true (1) to cancel creation of the popup + // window. By default, a newly created popup window will have the same client + // and settings as the parent window. To change the client for the new window + // modify the object that |client| points to. To change the settings for the + // new window modify the |settings| structure. + /// + int (CEF_CALLBACK *on_before_popup)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* parentBrowser, + const struct _cef_popup_features_t* popupFeatures, + struct _cef_window_info_t* windowInfo, const cef_string_t* url, + struct _cef_client_t** client, + struct _cef_browser_settings_t* settings); + + /// + // Called after a new window 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 window has recieved a request to close. Return false (0) to + // proceed with the window close or true (1) to cancel the window close. If + // this is a modal window and a custom modal loop implementation was provided + // in run_modal() this callback should be used to restore the opener window to + // a usable state. + /// + int (CEF_CALLBACK *do_close)(struct _cef_life_span_handler_t* self, + struct _cef_browser_t* browser); + + /// + // Called just before a window is closed. 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. + /// + 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/cef1/include/capi/cef_load_handler_capi.h b/cef1/include/capi/cef_load_handler_capi.h new file mode 100644 index 000000000..baea13038 --- /dev/null +++ b/cef1/include/capi/cef_load_handler_capi.h @@ -0,0 +1,99 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle events related to browser load status. The +// functions of this structure will be called on the UI thread. +/// +typedef struct _cef_load_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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. + /// + 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 browser fails to load a resource. |errorCode| is the error + // code number and |failedUrl| is the URL that failed to load. To provide + // custom error text assign the text to |errorText| and return true (1). + // Otherwise, return false (0) for the default error text. See + // net\base\net_error_list.h for complete descriptions of the error codes. + /// + int (CEF_CALLBACK *on_load_error)(struct _cef_load_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + enum cef_handler_errorcode_t errorCode, const cef_string_t* failedUrl, + cef_string_t* errorText); +} cef_load_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_LOAD_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_menu_handler_capi.h b/cef1/include/capi/cef_menu_handler_capi.h new file mode 100644 index 000000000..7cf2b9ad8 --- /dev/null +++ b/cef1/include/capi/cef_menu_handler_capi.h @@ -0,0 +1,88 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_MENU_HANDLER_CAPI_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle events related to browser context menus. +// The functions of this structure will be called on the UI thread. +/// +typedef struct _cef_menu_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called before a context menu is displayed. Return false (0) to display the + // default context menu or true (1) to cancel the display. + /// + int (CEF_CALLBACK *on_before_menu)(struct _cef_menu_handler_t* self, + struct _cef_browser_t* browser, + const struct _cef_menu_info_t* menuInfo); + + /// + // Called to optionally override the default text for a context menu item. + // |label| contains the default text and may be modified to substitute + // alternate text. + /// + void (CEF_CALLBACK *get_menu_label)(struct _cef_menu_handler_t* self, + struct _cef_browser_t* browser, enum cef_menu_id_t menuId, + cef_string_t* label); + + /// + // Called when an option is selected from the default context menu. Return + // false (0) to execute the default action or true (1) to cancel the action. + /// + int (CEF_CALLBACK *on_menu_action)(struct _cef_menu_handler_t* self, + struct _cef_browser_t* browser, enum cef_menu_id_t menuId); +} cef_menu_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_MENU_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_nplugin_capi.h b/cef1/include/capi/cef_nplugin_capi.h new file mode 100644 index 000000000..d6adf1bf0 --- /dev/null +++ b/cef1/include/capi/cef_nplugin_capi.h @@ -0,0 +1,49 @@ +// 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_CAPI_CEF_NPLUGIN_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_NPLUGIN_CAPI_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/internal/cef_nplugin_types.h" + +/// +// Register a plugin with the system. Returns true (1) on success. +/// +CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_NPLUGIN_CAPI_H_ diff --git a/cef1/include/capi/cef_origin_whitelist_capi.h b/cef1/include/capi/cef_origin_whitelist_capi.h new file mode 100644 index 000000000..917ec861e --- /dev/null +++ b/cef1/include/capi/cef_origin_whitelist_capi.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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.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 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| is non-NULL 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/cef1/include/capi/cef_permission_handler_capi.h b/cef1/include/capi/cef_permission_handler_capi.h new file mode 100644 index 000000000..13db70eb9 --- /dev/null +++ b/cef1/include/capi/cef_permission_handler_capi.h @@ -0,0 +1,72 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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_PERMISSION_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PERMISSION_HANDLER_CAPI_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle events related to browser permissions. The +// functions of this structure will be called on the UI thread. +/// +typedef struct _cef_permission_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called on the UI thread before a script extension is loaded. Return false + // (0) to let the extension load normally. + /// + int (CEF_CALLBACK *on_before_script_extension_load)( + struct _cef_permission_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, const cef_string_t* extensionName); +} cef_permission_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PERMISSION_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_print_handler_capi.h b/cef1/include/capi/cef_print_handler_capi.h new file mode 100644 index 000000000..be5cfc78e --- /dev/null +++ b/cef1/include/capi/cef_print_handler_capi.h @@ -0,0 +1,96 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle events related to printing. The functions +// of this structure will be called on the UI thread. +/// +typedef struct _cef_print_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to allow customization of standard print options before the print + // dialog is displayed. |printOptions| allows specification of paper size, + // orientation and margins. Note that the specified margins may be adjusted if + // they are outside the range supported by the printer. All units are in + // inches. Return false (0) to display the default print options or true (1) + // to display the modified |printOptions|. + /// + int (CEF_CALLBACK *get_print_options)(struct _cef_print_handler_t* self, + struct _cef_browser_t* browser, + struct _cef_print_options_t* printOptions); + + /// + // Called to format print headers and footers. |printInfo| contains platform- + // specific information about the printer context. |url| is the URL if the + // currently printing page, |title| is the title of the currently printing + // page, |currentPage| is the current page number and |maxPages| is the total + // number of pages. Six default header locations are provided by the + // implementation: top left, top center, top right, bottom left, bottom center + // and bottom right. To use one of these default locations just assign a + // string to the appropriate variable. To draw the header and footer yourself + // return true (1). Otherwise, populate the approprate variables and return + // false (0). + /// + int (CEF_CALLBACK *get_print_header_footer)(struct _cef_print_handler_t* self, + struct _cef_browser_t* browser, struct _cef_frame_t* frame, + const struct _cef_print_info_t* printInfo, const cef_string_t* url, + const cef_string_t* title, int currentPage, int maxPages, + cef_string_t* topLeft, cef_string_t* topCenter, cef_string_t* topRight, + cef_string_t* bottomLeft, cef_string_t* bottomCenter, + cef_string_t* bottomRight); +} cef_print_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PRINT_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_proxy_handler_capi.h b/cef1/include/capi/cef_proxy_handler_capi.h new file mode 100644 index 000000000..2628002d6 --- /dev/null +++ b/cef1/include/capi/cef_proxy_handler_capi.h @@ -0,0 +1,69 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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_PROXY_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_PROXY_HANDLER_CAPI_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle proxy resolution events. +/// +typedef struct _cef_proxy_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Called to retrieve proxy information for the specified |url|. + /// + void (CEF_CALLBACK *get_proxy_for_url)(struct _cef_proxy_handler_t* self, + const cef_string_t* url, struct _cef_proxy_info_t* proxy_info); +} cef_proxy_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_PROXY_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_render_handler_capi.h b/cef1/include/capi/cef_render_handler_capi.h new file mode 100644 index 000000000..53fc5d8e5 --- /dev/null +++ b/cef1/include/capi/cef_render_handler_capi.h @@ -0,0 +1,118 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 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 simulated screen rectangle. Return true (1) if the + // rectangle was provided. + /// + int (CEF_CALLBACK *get_screen_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 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. + /// + 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. |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 that need + // to be repainted. On Windows |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, enum cef_paint_element_type_t type, + size_t dirtyRectsCount, cef_rect_t const* dirtyRects, + const void* buffer); + + /// + // Called when the browser window's cursor has changed. + /// + void (CEF_CALLBACK *on_cursor_change)(struct _cef_render_handler_t* self, + struct _cef_browser_t* browser, cef_cursor_handle_t cursor); +} cef_render_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RENDER_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_request_capi.h b/cef1/include/capi/cef_request_capi.h new file mode 100644 index 000000000..f4650f6ec --- /dev/null +++ b/cef1/include/capi/cef_request_capi.h @@ -0,0 +1,261 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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; + + /// + // 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_web_urlrequest_t. + /// + enum cef_weburlrequest_flags_t (CEF_CALLBACK *get_flags)( + struct _cef_request_t* self); + + /// + // Set the flags used in combination with cef_web_urlrequest_t. + /// + void (CEF_CALLBACK *set_flags)(struct _cef_request_t* self, + enum cef_weburlrequest_flags_t flags); + + /// + // Set the URL to the first party for cookies used in combination with + // cef_web_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_web_urlrequest_t. + /// + void (CEF_CALLBACK *set_first_party_for_cookies)(struct _cef_request_t* self, + const cef_string_t* url); +} 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 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; + + /// + // 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. + /// + enum 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/cef1/include/capi/cef_request_handler_capi.h b/cef1/include/capi/cef_request_handler_capi.h new file mode 100644 index 000000000..3414001b9 --- /dev/null +++ b/cef1/include/capi/cef_request_handler_capi.h @@ -0,0 +1,159 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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. + /// + 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, enum cef_handler_navtype_t navType, + int isRedirect); + + /// + // Called on the IO thread before a resource is loaded. To allow the resource + // to load normally return false (0). To redirect the resource to a new url + // populate the |redirectUrl| value and return false (0). To specify data for + // the resource return a CefStream object in |resourceStream|, use the + // |response| object to set mime type, HTTP status code and optional header + // values, and return false (0). To cancel loading of the resource return true + // (1). Any modifications to |request| will be observed. If the URL in + // |request| is changed and |redirectUrl| is also set, the URL in |request| + // will be used. + /// + int (CEF_CALLBACK *on_before_resource_load)( + struct _cef_request_handler_t* self, struct _cef_browser_t* browser, + struct _cef_request_t* request, cef_string_t* redirectUrl, + struct _cef_stream_reader_t** resourceStream, + struct _cef_response_t* response, int loadFlags); + + /// + // 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, const cef_string_t* old_url, + cef_string_t* new_url); + + /// + // Called on the UI thread after a response to the resource request is + // received. Set |filter| if response content needs to be monitored and/or + // modified as it arrives. + /// + void (CEF_CALLBACK *on_resource_response)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* url, + struct _cef_response_t* response, + struct _cef_content_filter_t** filter); + + /// + // Called on the IO thread to handle requests for URLs with an unknown + // protocol component. Return true (1) to indicate that the request should + // succeed because it was handled externally. Set |allowOSExecution| to true + // (1) and return false (0) to attempt execution via the registered OS + // protocol handler, if any. If false (0) is returned and either + // |allow_os_execution| is false (0) or OS protocol handler execution fails + // then the request will fail with an error condition. SECURITY WARNING: YOU + // SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED ON SCHEME, HOST OR + // OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION. + /// + int (CEF_CALLBACK *on_protocol_execution)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* url, + int* allowOSExecution); + + /// + // Called on the UI thread when a server indicates via the 'Content- + // Disposition' header that a response represents a file to download. + // |mimeType| is the mime type for the download, |fileName| is the suggested + // target file name and |contentLength| is either the value of the 'Content- + // Size' header or -1 if no size was provided. Set |handler| to the + // cef_download_handler_t instance that will recieve the file contents. Return + // true (1) to download the file or false (0) to cancel the file download. + /// + int (CEF_CALLBACK *get_download_handler)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, const cef_string_t* mimeType, + const cef_string_t* fileName, int64 contentLength, + struct _cef_download_handler_t** handler); + + /// + // 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 number. Set |username| and |password| and return true (1) + // to handle the request. Return false (0) to cancel the request. + /// + int (CEF_CALLBACK *get_auth_credentials)(struct _cef_request_handler_t* self, + struct _cef_browser_t* browser, int isProxy, const cef_string_t* host, + int port, const cef_string_t* realm, const cef_string_t* scheme, + cef_string_t* username, cef_string_t* password); + + /// + // Called on the IO thread to retrieve the cookie manager. |main_url| is the + // URL of the top-level frame. Cookies managers can be unique per browser or + // shared across multiple browsers. 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_handler_t* self, struct _cef_browser_t* browser, + const cef_string_t* main_url); +} cef_request_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_REQUEST_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_resource_bundle_handler_capi.h b/cef1/include/capi/cef_resource_bundle_handler_capi.h new file mode 100644 index 000000000..2111fa7e2 --- /dev/null +++ b/cef1/include/capi/cef_resource_bundle_handler_capi.h @@ -0,0 +1,95 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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). + // + // WARNING: Be cautious when implementing this function. ID values are auto- + // generated when CEF is built and may change between versions. Existing ID + // values can be discovered by searching for *_strings.h in the + // "obj/global_intermediate" build output directory. + /// + 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. + // + // WARNING: Be cautious when implementing this function. ID values are auto- + // generated when CEF is built and may change between versions. Existing ID + // values can be discovered by searching for *_resources.h in the + // "obj/global_intermediate" build output directory. + /// + 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/cef1/include/capi/cef_response_capi.h b/cef1/include/capi/cef_response_capi.h new file mode 100644 index 000000000..e58180711 --- /dev/null +++ b/cef1/include/capi/cef_response_capi.h @@ -0,0 +1,119 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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; + + /// + // 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; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_RESPONSE_CAPI_H_ diff --git a/cef1/include/capi/cef_scheme_capi.h b/cef1/include/capi/cef_scheme_capi.h new file mode 100644 index 000000000..b3806580b --- /dev/null +++ b/cef1/include/capi/cef_scheme_capi.h @@ -0,0 +1,226 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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). +/// +CEF_EXPORT int cef_register_custom_scheme(const cef_string_t* scheme_name, + int is_standard, int is_local, int is_display_isolated); + +/// +// 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 the +// cef_register_custom_scheme() function should be called for that scheme. 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. +/// +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); + +/// +// Clear all registered scheme handler factories. Returns false (0) on error. +// This function may be called on any thread. +/// +CEF_EXPORT int cef_clear_scheme_handler_factories(); + +/// +// Structure that creates cef_scheme_handler_t instances. 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 scheme handler instance to handle the request. |browser| will + // be the browser window that initiated the request. If the request was + // initiated using the cef_web_urlrequest_t API |browser| will be NULL. The + // |request| object passed to this function will not contain cookie data. + /// + struct _cef_scheme_handler_t* (CEF_CALLBACK *create)( + struct _cef_scheme_handler_factory_t* self, + struct _cef_browser_t* browser, const cef_string_t* scheme_name, + struct _cef_request_t* request); +} cef_scheme_handler_factory_t; + + +/// +// Structure used to facilitate asynchronous responses to custom scheme handler +// requests. The functions of this structure may be called on any thread. +/// +typedef struct _cef_scheme_handler_callback_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Notify that header information is now available for retrieval. + /// + void (CEF_CALLBACK *headers_available)( + struct _cef_scheme_handler_callback_t* self); + + /// + // Notify that response data is now available for reading. + /// + void (CEF_CALLBACK *bytes_available)( + struct _cef_scheme_handler_callback_t* self); + + /// + // Cancel processing of the request. + /// + void (CEF_CALLBACK *cancel)(struct _cef_scheme_handler_callback_t* self); +} cef_scheme_handler_callback_t; + + +/// +// Structure used to implement a custom scheme handler structure. The functions +// of this structure will always be called on the IO thread. +/// +typedef struct _cef_scheme_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Begin processing the request. To handle the request return true (1) and + // call headers_available() once the response header information is available + // (headers_available() 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_scheme_handler_t* self, + struct _cef_request_t* request, + struct _cef_scheme_handler_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_scheme_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 bytes_available() when the data + // is available. To indicate response completion return false (0). + /// + int (CEF_CALLBACK *read_response)(struct _cef_scheme_handler_t* self, + void* data_out, int bytes_to_read, int* bytes_read, + struct _cef_scheme_handler_callback_t* callback); + + /// + // Request processing has been canceled. + /// + void (CEF_CALLBACK *cancel)(struct _cef_scheme_handler_t* self); +} cef_scheme_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_SCHEME_CAPI_H_ diff --git a/cef1/include/capi/cef_stream_capi.h b/cef1/include/capi/cef_stream_capi.h new file mode 100644 index 000000000..f73fa39c3 --- /dev/null +++ b/cef1/include/capi/cef_stream_capi.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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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); +} 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); +} 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); +} 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); +} 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/cef1/include/capi/cef_task_capi.h b/cef1/include/capi/cef_task_capi.h new file mode 100644 index 000000000..cca4fbd9c --- /dev/null +++ b/cef1/include/capi/cef_task_capi.h @@ -0,0 +1,96 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// CEF maintains multiple internal threads that are used for handling different +// types of tasks. The UI thread creates the browser window and is used for all +// interaction with the WebKit rendering engine and V8 JavaScript engine (The UI +// thread will be the same as the main application thread if cef_initialize() is +// called with a CefSettings.multi_threaded_message_loop value of false (0).) +// The IO thread is used for handling schema and network requests. The FILE +// thread is used for the application cache and other miscellaneous activities. +// This function will return true (1) if called on the specified thread. +/// +CEF_EXPORT int cef_currently_on(cef_thread_id_t threadId); + +/// +// Post a task for execution on the specified thread. This function may be +// called on any thread. +/// +CEF_EXPORT int cef_post_task(cef_thread_id_t threadId, + struct _cef_task_t* task); + +/// +// Post a task for delayed execution on the specified thread. This function may +// be called on any thread. +/// +CEF_EXPORT int cef_post_delayed_task(cef_thread_id_t threadId, + struct _cef_task_t* task, int64 delay_ms); + +/// +// Implement this structure for task execution. The functions of this structure +// may be called on any thread. +/// +typedef struct _cef_task_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Method that will be executed. |threadId| is the thread executing the call. + /// + void (CEF_CALLBACK *execute)(struct _cef_task_t* self, + cef_thread_id_t threadId); +} cef_task_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_TASK_CAPI_H_ diff --git a/cef1/include/capi/cef_url_capi.h b/cef1/include/capi/cef_url_capi.h new file mode 100644 index 000000000..757875b39 --- /dev/null +++ b/cef1/include/capi/cef_url_capi.h @@ -0,0 +1,67 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_URL_CAPI_H_ diff --git a/cef1/include/capi/cef_v8_capi.h b/cef1/include/capi/cef_v8_capi.h new file mode 100644 index 000000000..8c4c23db3 --- /dev/null +++ b/cef1/include/capi/cef_v8_capi.h @@ -0,0 +1,791 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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 +// be called on any 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, struct _cef_v8handler_t* handler); + +/// +// Structure that encapsulates a V8 context handle. The functions of this +// structure may only be called on the UI thread. +/// +typedef struct _cef_v8context_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Returns the browser for this context. + /// + struct _cef_browser_t* (CEF_CALLBACK *get_browser)( + struct _cef_v8context_t* self); + + /// + // Returns the frame for this context. + /// + 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 always be called on the UI thread. +/// +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 always be called on the UI thread. +/// +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. +/// +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. The functions of this structure may only +// be called on the UI thread. +/// +typedef struct _cef_v8value_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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, + enum 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, enum cef_v8_accesscontrol_t settings, + enum 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. The functions of this structure may +// only be called on the UI thread. +/// +typedef struct _cef_v8stack_trace_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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. The functions of this structure may +// only be called on the UI thread. +/// +typedef struct _cef_v8stack_frame_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_V8_CAPI_H_ diff --git a/cef1/include/capi/cef_v8context_handler_capi.h b/cef1/include/capi/cef_v8context_handler_capi.h new file mode 100644 index 000000000..fa00e419b --- /dev/null +++ b/cef1/include/capi/cef_v8context_handler_capi.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. +// +// --------------------------------------------------------------------------- +// +// 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_V8CONTEXT_HANDLER_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_V8CONTEXT_HANDLER_CAPI_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Implement this structure to handle V8 context events. The functions of this +// structure will be called on the UI thread. +/// +typedef struct _cef_v8context_handler_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // 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. + /// + void (CEF_CALLBACK *on_context_created)(struct _cef_v8context_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_v8context_handler_t* self, struct _cef_browser_t* browser, + struct _cef_frame_t* frame, struct _cef_v8context_t* context); +} cef_v8context_handler_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_V8CONTEXT_HANDLER_CAPI_H_ diff --git a/cef1/include/capi/cef_web_plugin_capi.h b/cef1/include/capi/cef_web_plugin_capi.h new file mode 100644 index 000000000..d5aab64bd --- /dev/null +++ b/cef1/include/capi/cef_web_plugin_capi.h @@ -0,0 +1,110 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Returns the number of installed web plugins. This function must be called on +// the UI thread. +/// +CEF_EXPORT size_t cef_get_web_plugin_count(); + +/// +// Returns information for web plugin at the specified zero-based index. This +// function must be called on the UI thread. +/// +CEF_EXPORT struct _cef_web_plugin_info_t* cef_get_web_plugin_info(int index); + +/// +// Returns information for web plugin with the specified name. This function +// must be called on the UI thread. +/// +CEF_EXPORT struct _cef_web_plugin_info_t* cef_get_web_plugin_info_byname( + const cef_string_t* name); + +/// +// 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; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_WEB_PLUGIN_CAPI_H_ diff --git a/cef1/include/capi/cef_web_urlrequest_capi.h b/cef1/include/capi/cef_web_urlrequest_capi.h new file mode 100644 index 000000000..3e2cbb12d --- /dev/null +++ b/cef1/include/capi/cef_web_urlrequest_capi.h @@ -0,0 +1,143 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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_URLREQUEST_CAPI_H_ +#define CEF_INCLUDE_CAPI_CEF_WEB_URLREQUEST_CAPI_H_ +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// Structure used to make a Web URL request. Web URL requests are not associated +// with a browser instance so no cef_client_t callbacks will be executed. The +// functions of this structure may be called on any thread. +/// +typedef struct _cef_web_urlrequest_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Cancels the request. + /// + void (CEF_CALLBACK *cancel)(struct _cef_web_urlrequest_t* self); + + /// + // Returns the current ready state of the request. + /// + enum cef_weburlrequest_state_t (CEF_CALLBACK *get_state)( + struct _cef_web_urlrequest_t* self); +} cef_web_urlrequest_t; + + +/// +// Create a new CefWebUrlRequest object. +/// +CEF_EXPORT cef_web_urlrequest_t* cef_web_urlrequest_create( + struct _cef_request_t* request, + struct _cef_web_urlrequest_client_t* client); + + +/// +// Structure that should be implemented by the cef_web_urlrequest_t client. The +// functions of this structure will always be called on the UI thread. +/// +typedef struct _cef_web_urlrequest_client_t { + /// + // Base structure. + /// + cef_base_t base; + + /// + // Notifies the client that the request state has changed. State change + // notifications will always be sent before the below notification functions + // are called. + /// + void (CEF_CALLBACK *on_state_change)( + struct _cef_web_urlrequest_client_t* self, + struct _cef_web_urlrequest_t* requester, + enum cef_weburlrequest_state_t state); + + /// + // Notifies the client that the request has been redirected and provides a + // chance to change the request parameters. + /// + void (CEF_CALLBACK *on_redirect)(struct _cef_web_urlrequest_client_t* self, + struct _cef_web_urlrequest_t* requester, struct _cef_request_t* request, + struct _cef_response_t* response); + + /// + // Notifies the client of the response data. + /// + void (CEF_CALLBACK *on_headers_received)( + struct _cef_web_urlrequest_client_t* self, + struct _cef_web_urlrequest_t* requester, + struct _cef_response_t* response); + + /// + // Notifies the client of the upload progress. + /// + void (CEF_CALLBACK *on_progress)(struct _cef_web_urlrequest_client_t* self, + struct _cef_web_urlrequest_t* requester, uint64 bytesSent, + uint64 totalBytesToBeSent); + + /// + // Notifies the client that content has been received. + /// + void (CEF_CALLBACK *on_data)(struct _cef_web_urlrequest_client_t* self, + struct _cef_web_urlrequest_t* requester, const void* data, + int dataLength); + + /// + // Notifies the client that the request ended with an error. + /// + void (CEF_CALLBACK *on_error)(struct _cef_web_urlrequest_client_t* self, + struct _cef_web_urlrequest_t* requester, + enum cef_handler_errorcode_t errorCode); +} cef_web_urlrequest_client_t; + + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_CAPI_CEF_WEB_URLREQUEST_CAPI_H_ diff --git a/cef1/include/capi/cef_xml_reader_capi.h b/cef1/include/capi/cef_xml_reader_capi.h new file mode 100644 index 000000000..c8585a53e --- /dev/null +++ b/cef1/include/capi/cef_xml_reader_capi.h @@ -0,0 +1,278 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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. + /// + enum 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, + enum 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/cef1/include/capi/cef_zip_reader_capi.h b/cef1/include/capi/cef_zip_reader_capi.h new file mode 100644 index 000000000..d7988afcb --- /dev/null +++ b/cef1/include/capi/cef_zip_reader_capi.h @@ -0,0 +1,148 @@ +// 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. +// +// --------------------------------------------------------------------------- +// +// 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + + +/// +// 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/cef1/include/cef_app.h b/cef1/include/cef_app.h new file mode 100644 index 000000000..028bd71d1 --- /dev/null +++ b/cef1/include/cef_app.h @@ -0,0 +1,123 @@ +// 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_APP_H_ +#define CEF_INCLUDE_CEF_APP_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_proxy_handler.h" +#include "include/cef_resource_bundle_handler.h" + +class CefApp; + +/// +// This function should be called on the main application thread to initialize +// CEF when the application is started. The |application| parameter may be +// empty. A return value of true indicates that it succeeded and false indicates +// that it failed. +/// +/*--cef(revision_check,optional_param=application)--*/ +bool CefInitialize(const CefSettings& settings, CefRefPtr application); + +/// +// This function should be called on the main application thread to shut down +// CEF 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(); + + +/// +// Implement this interface to provide handler implementations. Methods will be +// called on the thread indicated. +/// +/*--cef(source=client,no_debugct_check)--*/ +class CefApp : public virtual CefBase { + public: + /// + // 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 on multiple threads. + /// + /*--cef()--*/ + virtual CefRefPtr GetResourceBundleHandler() { + return NULL; + } + + /// + // Return the handler for proxy events. If not handler is returned the default + // system handler will be used. This method is called on the IO thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetProxyHandler() { + return NULL; + } +}; + +#endif // CEF_INCLUDE_CEF_APP_H_ diff --git a/cef1/include/cef_application_mac.h b/cef1/include/cef_application_mac.h new file mode 100644 index 000000000..33042478c --- /dev/null +++ b/cef1/include/cef_application_mac.h @@ -0,0 +1,120 @@ +// 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 CrAppProtocol definition. +#include "base/message_pump_mac.h" + +// Use the existing empty protocol definitions. +#import "base/mac/cocoa_protocols.h" + +#else // BUILDING_CEF_SHARED + +#import +#import + +// Copy of CrAppProtocol definition from base/message_pump_mac.h. +@protocol CrAppProtocol +// Must return true if -[NSApplication sendEvent:] is currently on the stack. +- (BOOL)isHandlingSendEvent; +@end + +// 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 + +// All CEF client applications must subclass NSApplication and implement this +// protocol. +@protocol CefAppProtocol +- (void)setHandlingSendEvent:(BOOL)handlingSendEvent; +@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/cef1/include/cef_base.h b/cef1/include/cef_base.h new file mode 100644 index 000000000..5fc964fa3 --- /dev/null +++ b/cef1/include/cef_base.h @@ -0,0 +1,154 @@ +// 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_BASE_H_ +#define CEF_INCLUDE_CEF_BASE_H_ +#pragma once + +#include "include/internal/cef_build.h" +#include "include/internal/cef_ptr.h" +#include "include/internal/cef_types_wrappers.h" + +// Bring in platform-specific definitions. +#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: + /// + // The AddRef method increments the reference count for the object. It should + // be called for every new copy of a pointer to a given object. The resulting + // reference count value is returned and should be used for diagnostic/testing + // purposes only. + /// + virtual int AddRef() =0; + + /// + // The Release method decrements the reference count for the object. If the + // reference count on the object falls to 0, then the object should free + // itself from memory. The resulting reference count value is returned and + // should be used for diagnostic/testing purposes only. + /// + virtual int Release() =0; + + /// + // Return the current number of references. + /// + virtual int GetRefCt() =0; + + protected: + virtual ~CefBase() {} +}; + + +/// +// Class that implements atomic reference counting. +/// +class CefRefCount { + public: + CefRefCount() : refct_(0) {} + + /// + // Atomic reference increment. + /// + int AddRef() { + return CefAtomicIncrement(&refct_); + } + + /// + // Atomic reference decrement. Delete the object when no references remain. + /// + int Release() { + return CefAtomicDecrement(&refct_); + } + + /// + // Return the current number of references. + /// + int GetRefCt() { return refct_; } + + private: + long refct_; // NOLINT(runtime/int) +}; + +/// +// Macro that provides a reference counting implementation for classes extending +// CefBase. +/// +#define IMPLEMENT_REFCOUNTING(ClassName) \ + public: \ + int AddRef() { return refct_.AddRef(); } \ + int Release() { \ + int retval = refct_.Release(); \ + if (retval == 0) \ + delete this; \ + return retval; \ + } \ + int GetRefCt() { return refct_.GetRefCt(); } \ + private: \ + CefRefCount refct_; + +/// +// 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. +/// +#define IMPLEMENT_LOCKING(ClassName) \ + public: \ + class AutoLock { \ + public: \ + explicit AutoLock(ClassName* base) : base_(base) { base_->Lock(); } \ + ~AutoLock() { base_->Unlock(); } \ + private: \ + ClassName* base_; \ + }; \ + void Lock() { critsec_.Lock(); } \ + void Unlock() { critsec_.Unlock(); } \ + private: \ + CefCriticalSection critsec_; + +#endif // CEF_INCLUDE_CEF_BASE_H_ diff --git a/cef1/include/cef_browser.h b/cef1/include/cef_browser.h new file mode 100644 index 000000000..b319bc1dd --- /dev/null +++ b/cef1/include/cef_browser.h @@ -0,0 +1,336 @@ +// 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_BROWSER_H_ +#define CEF_INCLUDE_CEF_BROWSER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_frame.h" +#include + +class CefClient; + +/// +// Class used to represent a browser window. The methods of this class may be +// called on any thread unless otherwise indicated in the comments. +/// +/*--cef(source=library)--*/ +class CefBrowser : public virtual CefBase { + public: + typedef cef_key_type_t KeyType; + 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. This method call will not block. + /// + /*--cef(optional_param=url)--*/ + static bool CreateBrowser(CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings); + + /// + // Create a new browser window using the window parameters specified by + // |windowInfo|. This method should only be called on the UI thread. + /// + /*--cef(optional_param=url)--*/ + static CefRefPtr CreateBrowserSync(CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings); + + /// + // Call this method before destroying a contained browser window. This method + // performs any internal cleanup that may be needed before the browser window + // is destroyed. + /// + /*--cef()--*/ + virtual void ParentWindowWillClose() =0; + + /// + // Closes this browser window. + /// + /*--cef()--*/ + virtual void CloseBrowser() =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; + /// + // 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; + + /// + // 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; + + /// + // 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 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 client for this browser. + /// + /*--cef()--*/ + virtual CefRefPtr GetClient() =0; + + /// + // Returns the main (top-level) frame for the browser window. + /// + /*--cef()--*/ + virtual CefRefPtr GetMainFrame() =0; + + /// + // Returns the focused frame for the browser window. This method should only + // be called on the UI thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetFocusedFrame() =0; + + /// + // Returns the frame with the specified name, or NULL if not found. This + // method should only be called on the UI thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetFrame(const CefString& name) =0; + + /// + // Returns the names of all existing frames. This method should only be called + // on the UI thread. + /// + /*--cef()--*/ + virtual void GetFrameNames(std::vector& names) =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. + /// + /*--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; + + /// + // Get the zoom level. + /// + /*--cef()--*/ + virtual double GetZoomLevel() =0; + + /// + // Change the zoom level to the specified value. + /// + /*--cef()--*/ + virtual void SetZoomLevel(double zoomLevel) =0; + + /// + // Clear the back/forward browsing history. + /// + /*--cef()--*/ + virtual void ClearHistory() =0; + + /// + // Open developer tools in its own window. + /// + /*--cef()--*/ + virtual void ShowDevTools() =0; + + /// + // Explicitly close the developer tools window if one exists for this browser + // instance. + /// + /*--cef()--*/ + virtual void CloseDevTools() =0; + + /// + // Returns true if window rendering is disabled. + /// + /*--cef()--*/ + virtual bool IsWindowRenderingDisabled() =0; + + /// + // Get the size of the specified element. This method should only be called on + // the UI thread. + /// + /*--cef()--*/ + virtual bool GetSize(PaintElementType type, int& width, int& height) =0; + + /// + // Set the size of the specified element. This method is only used when window + // rendering is disabled. + /// + /*--cef()--*/ + virtual void SetSize(PaintElementType type, int width, int height) =0; + + /// + // Returns true if a popup is currently visible. This method should only be + // called on the UI thread. + /// + /*--cef()--*/ + virtual bool IsPopupVisible() =0; + + /// + // Hide the currently visible popup, if any. + /// + /*--cef()--*/ + virtual void HidePopup() =0; + + /// + // Invalidate the |dirtyRect| region of the view. This method is only used + // when window rendering is disabled and will result in a call to + // HandlePaint(). + /// + /*--cef()--*/ + virtual void Invalidate(const CefRect& dirtyRect) =0; + + /// + // Get the raw image data contained in the specified element without + // performing validation. The specified |width| and |height| dimensions must + // match the current element size. On Windows |buffer| must be width*height*4 + // bytes in size and represents a BGRA image with an upper-left origin. This + // method should only be called on the UI thread. + /// + /*--cef()--*/ + virtual bool GetImage(PaintElementType type, int width, int height, + void* buffer) =0; + + /// + // Send a key event to the browser. + /// + /*--cef()--*/ + virtual void SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, + int modifiers) =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(int x, int y, 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(int x, int y, 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. + /// + /*--cef()--*/ + virtual void SendMouseWheelEvent(int x, int y, 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; +}; + +#endif // CEF_INCLUDE_CEF_BROWSER_H_ diff --git a/cef1/include/cef_client.h b/cef1/include/cef_client.h new file mode 100644 index 000000000..5e10971b8 --- /dev/null +++ b/cef1/include/cef_client.h @@ -0,0 +1,176 @@ +// 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_CLIENT_H_ +#define CEF_INCLUDE_CEF_CLIENT_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_display_handler.h" +#include "include/cef_drag_handler.h" +#include "include/cef_find_handler.h" +#include "include/cef_focus_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_menu_handler.h" +#include "include/cef_permission_handler.h" +#include "include/cef_print_handler.h" +#include "include/cef_render_handler.h" +#include "include/cef_request_handler.h" +#include "include/cef_v8context_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 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 browser request events. + /// + /*--cef()--*/ + virtual CefRefPtr GetRequestHandler() { + return NULL; + } + + /// + // Return the handler for browser display state events. + /// + /*--cef()--*/ + virtual CefRefPtr GetDisplayHandler() { + return NULL; + } + + /// + // Return the handler for focus events. + /// + /*--cef()--*/ + virtual CefRefPtr GetFocusHandler() { + return NULL; + } + + /// + // Return the handler for keyboard events. + /// + /*--cef()--*/ + virtual CefRefPtr GetKeyboardHandler() { + return NULL; + } + + /// + // Return the handler for context menu events. + /// + /*--cef()--*/ + virtual CefRefPtr GetMenuHandler() { + return NULL; + } + + /// + // Return the handler for browser permission events. + /// + /*--cef()--*/ + virtual CefRefPtr GetPermissionHandler() { + return NULL; + } + + /// + // Return the handler for printing events. + /// + /*--cef()--*/ + virtual CefRefPtr GetPrintHandler() { + return NULL; + } + + /// + // Return the handler for find result events. + /// + /*--cef()--*/ + virtual CefRefPtr GetFindHandler() { + return NULL; + } + + /// + // Return the handler for JavaScript dialog events. + /// + /*--cef()--*/ + virtual CefRefPtr GetJSDialogHandler() { + return NULL; + } + + /// + // Return the handler for V8 context events. + /// + /*--cef()--*/ + virtual CefRefPtr GetV8ContextHandler() { + return NULL; + } + + /// + // Return the handler for off-screen rendering events. + /// + /*--cef()--*/ + virtual CefRefPtr GetRenderHandler() { + return NULL; + } + + /// + // Return the handler for drag events. + /// + /*--cef()--*/ + virtual CefRefPtr GetDragHandler() { + return NULL; + } +}; + +#endif // CEF_INCLUDE_CEF_CLIENT_H_ diff --git a/cef1/include/cef_command_line.h b/cef1/include/cef_command_line.h new file mode 100644 index 000000000..a698187ee --- /dev/null +++ b/cef1/include/cef_command_line.h @@ -0,0 +1,160 @@ +// 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_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(revision_check)--*/ + static CefRefPtr CreateCommandLine(); + + /// + // 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; + + /// + // 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; +}; + +#endif // CEF_INCLUDE_CEF_COMMAND_LINE_H_ diff --git a/cef1/include/cef_content_filter.h b/cef1/include/cef_content_filter.h new file mode 100644 index 000000000..af5cf1755 --- /dev/null +++ b/cef1/include/cef_content_filter.h @@ -0,0 +1,68 @@ +// 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_CONTENT_FILTER_H_ +#define CEF_INCLUDE_CEF_CONTENT_FILTER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_stream.h" + +/// +// Interface to implement for filtering response content. The methods of this +// class will always be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefContentFilter : public virtual CefBase { + public: + /// + // Set |substitute_data| to the replacement for the data in |data| if data + // should be modified. + /// + /*--cef()--*/ + virtual void ProcessData(const void* data, int data_size, + CefRefPtr& substitute_data) {} + + /// + // Called when there is no more data to be processed. It is expected that + // whatever data was retained in the last ProcessData() call, it should be + // returned now by setting |remainder| if appropriate. + /// + /*--cef()--*/ + virtual void Drain(CefRefPtr& remainder) {} +}; + +#endif // CEF_INCLUDE_CEF_CONTENT_FILTER_H_ diff --git a/cef1/include/cef_cookie.h b/cef1/include/cef_cookie.h new file mode 100644 index 000000000..d24325c39 --- /dev/null +++ b/cef1/include/cef_cookie.h @@ -0,0 +1,147 @@ +// 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 + +class CefCookieVisitor; + + +/// +// Class used for managing cookies. The methods of this class may be called on +// any thread unless otherwise indicated. +/// +/*--cef(source=library)--*/ +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. Returns NULL if creation fails. + /// + /*--cef(optional_param=path)--*/ + static CefRefPtr CreateManager(const CefString& path); + + /// + // 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. Returns false if + // cookies cannot be accessed. + /// + /*--cef(optional_param=path)--*/ + virtual bool SetStoragePath(const CefString& path) =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/cef1/include/cef_display_handler.h b/cef1/include/cef_display_handler.h new file mode 100644 index 000000000..2c55445d8 --- /dev/null +++ b/cef1/include/cef_display_handler.h @@ -0,0 +1,117 @@ +// 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_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: + typedef cef_handler_statustype_t StatusType; + + /// + // Called when the navigation state has changed. + /// + /*--cef()--*/ + virtual void OnNavStateChange(CefRefPtr browser, + bool canGoBack, + bool canGoForward) {} + + /// + // Called when a frame's address has changed. + /// + /*--cef()--*/ + virtual void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) {} + + /// + // Called when the size of the content area has changed. + /// + /*--cef()--*/ + virtual void OnContentsSizeChange(CefRefPtr browser, + CefRefPtr frame, + int width, + int height) {} + + /// + // Called when the page title changes. + /// + /*--cef(optional_param=title)--*/ + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) {} + + /// + // 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. + /// + /*--cef(optional_param=text)--*/ + virtual bool OnTooltip(CefRefPtr browser, + CefString& text) { return false; } + + /// + // Called when the browser receives a status message. |text| contains the text + // that will be displayed in the status message and |type| indicates the + // status message type. + /// + /*--cef(optional_param=value)--*/ + virtual void OnStatusMessage(CefRefPtr browser, + const CefString& value, + StatusType type) {} + + /// + // 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/cef1/include/cef_dom.h b/cef1/include/cef_dom.h new file mode 100644 index 000000000..b56050d87 --- /dev/null +++ b/cef1/include/cef_dom.h @@ -0,0 +1,429 @@ +// 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_DOM_H_ +#define CEF_INCLUDE_CEF_DOM_H_ +#pragma once + +#include "include/cef_base.h" +#include + +class CefDOMDocument; +class CefDOMEventListener; +class CefDOMNode; + +/// +// Interface to implement for visiting the DOM. The methods of this class will +// be called on the UI 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 UI 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 start node. + /// + /*--cef()--*/ + virtual CefRefPtr GetSelectionStartNode() =0; + + /// + // Returns the selection offset within the start node. + /// + /*--cef()--*/ + virtual int GetSelectionStartOffset() =0; + + /// + // Returns the selection end node. + /// + /*--cef()--*/ + virtual CefRefPtr GetSelectionEndNode() =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 UI 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 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; + + /// + // Add an event listener to this node for the specified event type. If + // |useCapture| is true then this listener will be considered a capturing + // listener. Capturing listeners will recieve all events of the specified + // type before the events are dispatched to any other event targets beneath + // the current node in the tree. Events which are bubbling upwards through + // the tree will not trigger a capturing listener. Separate calls to this + // method can be used to register the same listener with and without capture. + // See WebCore/dom/EventNames.h for the list of supported event types. + /// + /*--cef()--*/ + virtual void AddEventListener(const CefString& eventType, + CefRefPtr listener, + bool useCapture) =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; +}; + + +/// +// Class used to represent a DOM event. The methods of this class should only +// be called on the UI thread. +/// +/*--cef(source=library)--*/ +class CefDOMEvent : public virtual CefBase { + public: + typedef cef_dom_event_category_t Category; + typedef cef_dom_event_phase_t Phase; + + /// + // Returns the event type. + /// + /*--cef()--*/ + virtual CefString GetType() =0; + + /// + // Returns the event category. + /// + /*--cef(default_retval=DOM_EVENT_CATEGORY_UNKNOWN)--*/ + virtual Category GetCategory() =0; + + /// + // Returns the event processing phase. + /// + /*--cef(default_retval=DOM_EVENT_PHASE_UNKNOWN)--*/ + virtual Phase GetPhase() =0; + + /// + // Returns true if the event can bubble up the tree. + /// + /*--cef()--*/ + virtual bool CanBubble() =0; + + /// + // Returns true if the event can be canceled. + /// + /*--cef()--*/ + virtual bool CanCancel() =0; + + /// + // Returns the document associated with this event. + /// + /*--cef()--*/ + virtual CefRefPtr GetDocument() =0; + + /// + // Returns the target of the event. + /// + /*--cef()--*/ + virtual CefRefPtr GetTarget() =0; + + /// + // Returns the current target of the event. + /// + /*--cef()--*/ + virtual CefRefPtr GetCurrentTarget() =0; +}; + + +/// +// Interface to implement for handling DOM events. The methods of this class +// will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefDOMEventListener : public virtual CefBase { + public: + /// + // Called when an event is received. The event object passed to this method + // contains 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 HandleEvent(CefRefPtr event) =0; +}; + +#endif // CEF_INCLUDE_CEF_DOM_H_ diff --git a/cef1/include/cef_download_handler.h b/cef1/include/cef_download_handler.h new file mode 100644 index 000000000..8fd209447 --- /dev/null +++ b/cef1/include/cef_download_handler.h @@ -0,0 +1,65 @@ +// 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_DOWNLOAD_HANDLER_H_ +#define CEF_INCLUDE_CEF_DOWNLOAD_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Class used to handle file downloads. The methods of this class will always be +// called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefDownloadHandler : public virtual CefBase { + public: + /// + // A portion of the file contents have been received. This method will be + // called multiple times until the download is complete. Return |true| to + // continue receiving data and |false| to cancel. + /// + /*--cef()--*/ + virtual bool ReceivedData(void* data, int data_size) =0; + + /// + // The download is complete. + /// + /*--cef()--*/ + virtual void Complete() =0; +}; + +#endif // CEF_INCLUDE_CEF_DOWNLOAD_HANDLER_H_ diff --git a/cef1/include/cef_drag_data.h b/cef1/include/cef_drag_data.h new file mode 100644 index 000000000..54400cdd8 --- /dev/null +++ b/cef1/include/cef_drag_data.h @@ -0,0 +1,120 @@ +// 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_DRAG_DATA_H_ +#define CEF_INCLUDE_CEF_DRAG_DATA_H_ +#pragma once + +#include "include/cef_base.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: + /// + // 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; + + /// + // Retrieve the list of file names that are being dragged into the browser + // window. + /// + /*--cef()--*/ + virtual bool GetFileNames(std::vector& names) =0; +}; + +#endif // CEF_INCLUDE_CEF_DRAG_DATA_H_ diff --git a/cef1/include/cef_drag_handler.h b/cef1/include/cef_drag_handler.h new file mode 100644 index 000000000..79d90e57e --- /dev/null +++ b/cef1/include/cef_drag_handler.h @@ -0,0 +1,77 @@ +// 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_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 the browser window initiates a drag event. |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 OnDragStart(CefRefPtr browser, + CefRefPtr dragData, + DragOperationsMask mask) { return false; } + + /// + // 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/cef1/include/cef_find_handler.h b/cef1/include/cef_find_handler.h new file mode 100644 index 000000000..bead6feeb --- /dev/null +++ b/cef1/include/cef_find_handler.h @@ -0,0 +1,68 @@ +// 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_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 CefBrowser::Find(). |identifer| + // is the identifier passed to CefBrowser::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/cef1/include/cef_focus_handler.h b/cef1/include/cef_focus_handler.h new file mode 100644 index 000000000..a45b6f52e --- /dev/null +++ b/cef1/include/cef_focus_handler.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. +// +// --------------------------------------------------------------------------- +// +// 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_handler_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 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) {} +}; + +#endif // CEF_INCLUDE_CEF_FOCUS_HANDLER_H_ diff --git a/cef1/include/cef_frame.h b/cef1/include/cef_frame.h new file mode 100644 index 000000000..f0ac6ef7a --- /dev/null +++ b/cef1/include/cef_frame.h @@ -0,0 +1,220 @@ +// 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_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" + +class CefBrowser; +class CefV8Context; + +/// +// Class used to represent a frame in the browser window. The methods of this +// class may be called on any thread unless otherwise indicated in the comments. +/// +/*--cef(source=library)--*/ +class CefFrame : public virtual CefBase { + public: + /// + // 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; + + /// + // Execute printing in the this frame. The user will be prompted with the + // print dialog appropriate to the operating system. + /// + /*--cef()--*/ + virtual void Print() =0; + + /// + // Save this frame's HTML source to a temporary file and open it in the + // default text viewing application. + /// + /*--cef()--*/ + virtual void ViewSource() =0; + + /// + // Returns this frame's HTML source as a string. This method should only be + // called on the UI thread. + /// + /*--cef()--*/ + virtual CefString GetSource() =0; + + /// + // Returns this frame's display text as a string. This method should only be + // called on the UI thread. + /// + /*--cef()--*/ + virtual CefString GetText() =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 optional dummy target |url|. + /// + /*--cef()--*/ + virtual void LoadString(const CefString& string_val, + const CefString& url) =0; + + /// + // Load the contents of |stream| with the optional dummy target |url|. + /// + /*--cef()--*/ + virtual void LoadStream(CefRefPtr stream, + 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=scriptUrl)--*/ + virtual void ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, + int startLine) =0; + + /// + // Returns true if this is the main (top-level) frame. + /// + /*--cef()--*/ + virtual bool IsMain() =0; + + /// + // Returns true if this is the focused frame. This method should only be + // called on the UI thread. + /// + /*--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. This method should only be called on the UI thread. + /// + /*--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; + + /// + // Visit the DOM document. + /// + /*--cef()--*/ + virtual void VisitDOM(CefRefPtr visitor) =0; + + /// + // Get the V8 context associated with the frame. This method should only be + // called on the UI thread. + /// + /*--cef()--*/ + virtual CefRefPtr GetV8Context() =0; +}; + +#endif // CEF_INCLUDE_CEF_FRAME_H_ diff --git a/cef1/include/cef_jsdialog_handler.h b/cef1/include/cef_jsdialog_handler.h new file mode 100644 index 000000000..d3067f3c0 --- /dev/null +++ b/cef1/include/cef_jsdialog_handler.h @@ -0,0 +1,87 @@ +// 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_JSDIALOG_HANDLER_H_ +#define CEF_INCLUDE_CEF_JSDIALOG_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 JavaScript dialogs. The +// methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefJSDialogHandler : public virtual CefBase { + public: + /// + // Called to run a JavaScript alert message. Return false to display the + // default alert or true if you displayed a custom alert. + /// + /*--cef(optional_param=message)--*/ + virtual bool OnJSAlert(CefRefPtr browser, + CefRefPtr frame, + const CefString& message) { return false; } + + /// + // Called to run a JavaScript confirm request. Return false to display the + // default alert or true if you displayed a custom alert. If you handled the + // alert set |retval| to true if the user accepted the confirmation. + /// + /*--cef(optional_param=message)--*/ + virtual bool OnJSConfirm(CefRefPtr browser, + CefRefPtr frame, + const CefString& message, + bool& retval) { return false; } + + /// + // Called to run a JavaScript prompt request. Return false to display the + // default prompt or true if you displayed a custom prompt. If you handled + // the prompt set |retval| to true if the user accepted the prompt and request + // and |result| to the resulting value. + /// + /*--cef(optional_param=message,optional_param=defaultValue)--*/ + virtual bool OnJSPrompt(CefRefPtr browser, + CefRefPtr frame, + const CefString& message, + const CefString& defaultValue, + bool& retval, + CefString& result) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_JSDIALOG_HANDLER_H_ diff --git a/cef1/include/cef_keyboard_handler.h b/cef1/include/cef_keyboard_handler.h new file mode 100644 index 000000000..a8133e91f --- /dev/null +++ b/cef1/include/cef_keyboard_handler.h @@ -0,0 +1,76 @@ +// 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_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: + typedef cef_handler_keyevent_type_t KeyEventType; + + /// + // Called when the browser component receives a keyboard event. This method + // is called both before the event is passed to the renderer and after + // JavaScript in the page has had a chance to handle the event. |type| is the + // type of keyboard event, |code| is the windows scan-code for the event, + // |modifiers| is a set of bit- flags describing any pressed modifier keys and + // |isSystemKey| is true if Windows considers this a 'system key' message (see + // http://msdn.microsoft.com/en-us/library/ms646286(VS.85).aspx). If + // |isAfterJavaScript| is true then JavaScript in the page has had a chance + // to handle the event and has chosen not to. Only RAWKEYDOWN, KEYDOWN and + // CHAR events will be sent with |isAfterJavaScript| set to true. Return + // true if the keyboard event was handled or false to allow continued handling + // of the event by the renderer. + /// + /*--cef()--*/ + virtual bool OnKeyEvent(CefRefPtr browser, + KeyEventType type, + int code, + int modifiers, + bool isSystemKey, + bool isAfterJavaScript) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_KEYBOARD_HANDLER_H_ diff --git a/cef1/include/cef_life_span_handler.h b/cef1/include/cef_life_span_handler.h new file mode 100644 index 000000000..907d755a8 --- /dev/null +++ b/cef1/include/cef_life_span_handler.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. +// +// --------------------------------------------------------------------------- +// +// 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. +/// +/*--cef(source=client)--*/ +class CefLifeSpanHandler : public virtual CefBase { + public: + /// + // Called before a new popup window is created. The |parentBrowser| parameter + // will point to the parent browser window. The |popupFeatures| parameter will + // contain information about the style of popup window requested. Return false + // to have the framework create the new popup window based on the parameters + // in |windowInfo|. Return true to cancel creation of the popup window. By + // default, a newly created popup window will have the same client and + // settings as the parent window. To change the client for the new window + // modify the object that |client| points to. To change the settings for the + // new window modify the |settings| structure. + /// + /*--cef(optional_param=url)--*/ + virtual bool OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) { return false; } + + /// + // Called after a new window 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 window has recieved a request to close. Return false to + // proceed with the window close or true to cancel the window close. If this + // is a modal window and a custom modal loop implementation was provided in + // RunModal() this callback should be used to restore the opener window to a + // usable state. + /// + /*--cef()--*/ + virtual bool DoClose(CefRefPtr browser) { return false; } + + /// + // Called just before a window is closed. 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. + /// + /*--cef()--*/ + virtual void OnBeforeClose(CefRefPtr browser) {} +}; + +#endif // CEF_INCLUDE_CEF_LIFE_SPAN_HANDLER_H_ diff --git a/cef1/include/cef_load_handler.h b/cef1/include/cef_load_handler.h new file mode 100644 index 000000000..bfa01df25 --- /dev/null +++ b/cef1/include/cef_load_handler.h @@ -0,0 +1,94 @@ +// 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_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 UI thread. +/// +/*--cef(source=client)--*/ +class CefLoadHandler : public virtual CefBase { + public: + typedef cef_handler_errorcode_t ErrorCode; + + /// + // 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. + /// + /*--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 browser fails to load a resource. |errorCode| is the error + // code number and |failedUrl| is the URL that failed to load. To provide + // custom error text assign the text to |errorText| and return true. + // Otherwise, return false for the default error text. See + // net\base\net_error_list.h for complete descriptions of the error codes. + /// + /*--cef()--*/ + virtual bool OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& failedUrl, + CefString& errorText) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_LOAD_HANDLER_H_ diff --git a/cef1/include/cef_menu_handler.h b/cef1/include/cef_menu_handler.h new file mode 100644 index 000000000..81fe115b1 --- /dev/null +++ b/cef1/include/cef_menu_handler.h @@ -0,0 +1,80 @@ +// 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_MENU_HANDLER_H_ +#define CEF_INCLUDE_CEF_MENU_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" + +/// +// Implement this interface to handle events related to browser context menus. +// The methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefMenuHandler : public virtual CefBase { + public: + typedef cef_menu_id_t MenuId; + + /// + // Called before a context menu is displayed. Return false to display the + // default context menu or true to cancel the display. + /// + /*--cef()--*/ + virtual bool OnBeforeMenu(CefRefPtr browser, + const CefMenuInfo& menuInfo) { return false; } + + /// + // Called to optionally override the default text for a context menu item. + // |label| contains the default text and may be modified to substitute + // alternate text. + /// + /*--cef()--*/ + virtual void GetMenuLabel(CefRefPtr browser, + MenuId menuId, + CefString& label) {} + + /// + // Called when an option is selected from the default context menu. Return + // false to execute the default action or true to cancel the action. + /// + /*--cef()--*/ + virtual bool OnMenuAction(CefRefPtr browser, + MenuId menuId) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_MENU_HANDLER_H_ diff --git a/cef1/include/cef_nplugin.h b/cef1/include/cef_nplugin.h new file mode 100644 index 000000000..4b16fe91f --- /dev/null +++ b/cef1/include/cef_nplugin.h @@ -0,0 +1,119 @@ +// 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_NPLUGIN_H_ +#define CEF_INCLUDE_CEF_NPLUGIN_H_ +#pragma once + +#include "internal/cef_nplugin_types.h" + +/// +// Netscape plugins are normally built at separate DLLs that are loaded by the +// browser when needed. This interface supports the creation of plugins that +// are an embedded component of the application. Embedded plugins built using +// this interface use the same Netscape Plugin API as DLL-based plugins. +// See https://developer.mozilla.org/En/Gecko_Plugin_API_Reference for complete +// documentation on how to use the Netscape Plugin API. +// +// This class provides attribute information and entry point functions for a +// plugin. +/// +class CefPluginInfo : public cef_plugin_info_t { + public: + CefPluginInfo() { + Init(); + } + virtual ~CefPluginInfo() { + Reset(); + } + + CefPluginInfo(const CefPluginInfo& r) { // NOLINT(runtime/explicit) + Init(); + *this = r; + } + CefPluginInfo(const cef_plugin_info_t& r) { // NOLINT(runtime/explicit) + Init(); + *this = r; + } + + void Reset() { + cef_string_clear(&unique_name); + cef_string_clear(&display_name); + cef_string_clear(&version); + cef_string_clear(&description); + cef_string_clear(&mime_types); + cef_string_clear(&file_extensions); + cef_string_clear(&type_descriptions); + Init(); + } + + void Attach(const cef_plugin_info_t& r) { + Reset(); + *static_cast(this) = r; + } + + void Detach() { + Init(); + } + + CefPluginInfo& operator=(const CefPluginInfo& r) { + return operator=(static_cast(r)); + } + + CefPluginInfo& operator=(const cef_plugin_info_t& r) { + cef_string_copy(r.unique_name.str, r.unique_name.length, &unique_name); + cef_string_copy(r.display_name.str, r.display_name.length, &display_name); + cef_string_copy(r.version.str, r.version.length, &version); + cef_string_copy(r.description.str, r.description.length, &description); + cef_string_copy(r.mime_types.str, r.mime_types.length, &mime_types); + cef_string_copy(r.file_extensions.str, r.file_extensions.length, + &file_extensions); + cef_string_copy(r.type_descriptions.str, r.type_descriptions.length, + &type_descriptions); +#if !defined(OS_POSIX) || defined(OS_MACOSX) + np_getentrypoints = r.np_getentrypoints; +#endif + np_initialize = r.np_initialize; + np_shutdown = r.np_shutdown; + return *this; + } + + protected: + void Init() { + memset(static_cast(this), 0, sizeof(cef_plugin_info_t)); + } +}; + +/// +// Register a plugin with the system. +/// +bool CefRegisterPlugin(const CefPluginInfo& plugin_info); + +#endif // CEF_INCLUDE_CEF_NPLUGIN_H_ diff --git a/cef1/include/cef_origin_whitelist.h b/cef1/include/cef_origin_whitelist.h new file mode 100644 index 000000000..fd434460e --- /dev/null +++ b/cef1/include/cef_origin_whitelist.h @@ -0,0 +1,102 @@ +// 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_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| is non-empty 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/cef1/include/cef_permission_handler.h b/cef1/include/cef_permission_handler.h new file mode 100644 index 000000000..aea8e46bb --- /dev/null +++ b/cef1/include/cef_permission_handler.h @@ -0,0 +1,64 @@ +// 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_PERMISSION_HANDLER_H_ +#define CEF_INCLUDE_CEF_PERMISSION_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 permissions. +// The methods of this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefPermissionHandler : public virtual CefBase { + public: + /// + // Called on the UI thread before a script extension is loaded. + // Return false to let the extension load normally. + /// + /*--cef()--*/ + virtual bool OnBeforeScriptExtensionLoad(CefRefPtr browser, + CefRefPtr frame, + const CefString& extensionName) { + return false; + } +}; + +#endif // CEF_INCLUDE_CEF_PERMISSION_HANDLER_H_ diff --git a/cef1/include/cef_print_handler.h b/cef1/include/cef_print_handler.h new file mode 100644 index 000000000..d47fbf632 --- /dev/null +++ b/cef1/include/cef_print_handler.h @@ -0,0 +1,91 @@ +// 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_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_frame.h" + +/// +// Implement this interface to handle events related to printing. The methods of +// this class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefPrintHandler : public virtual CefBase { + public: + /// + // Called to allow customization of standard print options before the print + // dialog is displayed. |printOptions| allows specification of paper size, + // orientation and margins. Note that the specified margins may be adjusted if + // they are outside the range supported by the printer. All units are in + // inches. Return false to display the default print options or true to + // display the modified |printOptions|. + /// + /*--cef()--*/ + virtual bool GetPrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions) { return false; } + + /// + // Called to format print headers and footers. |printInfo| contains platform- + // specific information about the printer context. |url| is the URL if the + // currently printing page, |title| is the title of the currently printing + // page, |currentPage| is the current page number and |maxPages| is the total + // number of pages. Six default header locations are provided by the + // implementation: top left, top center, top right, bottom left, bottom center + // and bottom right. To use one of these default locations just assign a + // string to the appropriate variable. To draw the header and footer yourself + // return true. Otherwise, populate the approprate variables and return false. + /// + /*--cef()--*/ + virtual bool GetPrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, + const CefPrintInfo& printInfo, + const CefString& url, + const CefString& title, + int currentPage, + int maxPages, + CefString& topLeft, + CefString& topCenter, + CefString& topRight, + CefString& bottomLeft, + CefString& bottomCenter, + CefString& bottomRight) { return false; } +}; + +#endif // CEF_INCLUDE_CEF_PRINT_HANDLER_H_ diff --git a/cef1/include/cef_proxy_handler.h b/cef1/include/cef_proxy_handler.h new file mode 100644 index 000000000..d40c67d7c --- /dev/null +++ b/cef1/include/cef_proxy_handler.h @@ -0,0 +1,57 @@ +// 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_PROXY_HANDLER_H_ +#define CEF_INCLUDE_CEF_PROXY_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" + +/// +// Implement this interface to handle proxy resolution events. +/// +/*--cef(source=client)--*/ +class CefProxyHandler : public virtual CefBase { + public: + /// + // Called to retrieve proxy information for the specified |url|. + /// + /*--cef()--*/ + virtual void GetProxyForUrl(const CefString& url, + CefProxyInfo& proxy_info) {} +}; + +#endif // CEF_INCLUDE_CEF_PROXY_HANDLER_H_ diff --git a/cef1/include/cef_render_handler.h b/cef1/include/cef_render_handler.h new file mode 100644 index 000000000..9bb9f68af --- /dev/null +++ b/cef1/include/cef_render_handler.h @@ -0,0 +1,119 @@ +// 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_RENDER_HANDLER_H_ +#define CEF_INCLUDE_CEF_RENDER_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.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_paint_element_type_t PaintElementType; + typedef std::vector RectList; + + /// + // 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) { return false; } + + /// + // Called to retrieve the simulated screen rectangle. Return true if the + // rectangle was provided. + /// + /*--cef()--*/ + virtual bool GetScreenRect(CefRefPtr browser, + CefRect& rect) { return false; } + + /// + // 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 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. + /// + /*--cef()--*/ + virtual void OnPopupSize(CefRefPtr browser, + const CefRect& rect) {} + + /// + // Called when an element should be painted. |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 that need + // to be repainted. On Windows |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) {} + + /// + // Called when the browser window's cursor has changed. + /// + /*--cef()--*/ + virtual void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor) {} +}; + +#endif // CEF_INCLUDE_CEF_RENDER_HANDLER_H_ diff --git a/cef1/include/cef_request.h b/cef1/include/cef_request.h new file mode 100644 index 000000000..95ade79b1 --- /dev/null +++ b/cef1/include/cef_request.h @@ -0,0 +1,255 @@ +// 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_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)--*/ +class CefRequest : public virtual CefBase { + public: + typedef std::multimap HeaderMap; + typedef cef_weburlrequest_flags_t RequestFlags; + + /// + // Create a new CefRequest object. + /// + /*--cef()--*/ + static CefRefPtr CreateRequest(); + + /// + // 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 CefWebURLRequest. + /// + /*--cef(default_retval=WUR_FLAG_NONE)--*/ + virtual RequestFlags GetFlags() =0; + /// + // Set the flags used in combination with CefWebURLRequest. + /// + /*--cef()--*/ + virtual void SetFlags(RequestFlags flags) =0; + + /// + // Set the URL to the first party for cookies used in combination with + // CefWebURLRequest. + /// + /*--cef()--*/ + virtual CefString GetFirstPartyForCookies() =0; + /// + // Get the URL to the first party for cookies used in combination with + // CefWebURLRequest. + /// + /*--cef()--*/ + virtual void SetFirstPartyForCookies(const CefString& url) =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)--*/ +class CefPostData : public virtual CefBase { + public: + typedef std::vector > ElementVector; + + /// + // Create a new CefPostData object. + /// + /*--cef()--*/ + static CefRefPtr CreatePostData(); + + /// + // 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)--*/ +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 CreatePostDataElement(); + + /// + // 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/cef1/include/cef_request_handler.h b/cef1/include/cef_request_handler.h new file mode 100644 index 000000000..0ee758f07 --- /dev/null +++ b/cef1/include/cef_request_handler.h @@ -0,0 +1,171 @@ +// 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_base.h" +#include "include/cef_browser.h" +#include "include/cef_cookie.h" +#include "include/cef_download_handler.h" +#include "include/cef_frame.h" +#include "include/cef_content_filter.h" +#include "include/cef_response.h" +#include "include/cef_request.h" +#include "include/cef_stream.h" + +/// +// 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_handler_navtype_t NavType; + + /// + // Called on the UI thread before browser navigation. Return true to cancel + // the navigation or false to allow the navigation to proceed. + /// + /*--cef()--*/ + virtual bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, + bool isRedirect) { return false; } + + /// + // Called on the IO thread before a resource is loaded. To allow the resource + // to load normally return false. To redirect the resource to a new url + // populate the |redirectUrl| value and return false. To specify data for the + // resource return a CefStream object in |resourceStream|, use the |response| + // object to set mime type, HTTP status code and optional header values, and + // return false. To cancel loading of the resource return true. Any + // modifications to |request| will be observed. If the URL in |request| is + // changed and |redirectUrl| is also set, the URL in |request| will be used. + /// + /*--cef()--*/ + virtual bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) { return false; } + + /// + // 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, + const CefString& old_url, + CefString& new_url) {} + + /// + // Called on the UI thread after a response to the resource request is + // received. Set |filter| if response content needs to be monitored and/or + // modified as it arrives. + /// + /*--cef()--*/ + virtual void OnResourceResponse(CefRefPtr browser, + const CefString& url, + CefRefPtr response, + CefRefPtr& filter) {} + + /// + // Called on the IO thread to handle requests for URLs with an unknown + // protocol component. Return true to indicate that the request should + // succeed because it was handled externally. Set |allowOSExecution| to true + // and return false to attempt execution via the registered OS protocol + // handler, if any. If false is returned and either |allow_os_execution| + // is false or OS protocol handler execution fails then the request will fail + // with an error condition. + // SECURITY WARNING: YOU SHOULD USE THIS METHOD TO ENFORCE RESTRICTIONS BASED + // ON SCHEME, HOST OR OTHER URL ANALYSIS BEFORE ALLOWING OS EXECUTION. + /// + /*--cef()--*/ + virtual bool OnProtocolExecution(CefRefPtr browser, + const CefString& url, + bool& allowOSExecution) { return false; } + + /// + // Called on the UI thread when a server indicates via the + // 'Content-Disposition' header that a response represents a file to download. + // |mimeType| is the mime type for the download, |fileName| is the suggested + // target file name and |contentLength| is either the value of the + // 'Content-Size' header or -1 if no size was provided. Set |handler| to the + // CefDownloadHandler instance that will recieve the file contents. Return + // true to download the file or false to cancel the file download. + /// + /*--cef()--*/ + virtual bool GetDownloadHandler(CefRefPtr browser, + const CefString& mimeType, + const CefString& fileName, + int64 contentLength, + CefRefPtr& handler) + { return false; } + + /// + // 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 number. Set |username| and |password| and return + // true to handle the request. Return false to cancel the request. + /// + /*--cef(optional_param=realm)--*/ + virtual bool GetAuthCredentials(CefRefPtr browser, + bool isProxy, + const CefString& host, + int port, + const CefString& realm, + const CefString& scheme, + CefString& username, + CefString& password) { return false; } + + /// + // Called on the IO thread to retrieve the cookie manager. |main_url| is the + // URL of the top-level frame. Cookies managers can be unique per browser or + // shared across multiple browsers. The global cookie manager will be used if + // this method returns NULL. + /// + /*--cef()--*/ + virtual CefRefPtr GetCookieManager( + CefRefPtr browser, + const CefString& main_url) { return NULL; } +}; + +#endif // CEF_INCLUDE_CEF_REQUEST_HANDLER_H_ diff --git a/cef1/include/cef_resource_bundle_handler.h b/cef1/include/cef_resource_bundle_handler.h new file mode 100644 index 000000000..e7a37d1b5 --- /dev/null +++ b/cef1/include/cef_resource_bundle_handler.h @@ -0,0 +1,82 @@ +// 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. + // + // WARNING: Be cautious when implementing this method. ID values are auto- + // generated when CEF is built and may change between versions. Existing ID + // values can be discovered by searching for *_strings.h in the + // "obj/global_intermediate" build output directory. + /// + /*--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. + // + // WARNING: Be cautious when implementing this method. ID values are auto- + // generated when CEF is built and may change between versions. Existing ID + // values can be discovered by searching for *_resources.h in the + // "obj/global_intermediate" build output directory. + /// + /*--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/cef1/include/cef_response.h b/cef1/include/cef_response.h new file mode 100644 index 000000000..5448cd71c --- /dev/null +++ b/cef1/include/cef_response.h @@ -0,0 +1,104 @@ +// 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_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)--*/ +class CefResponse : public virtual CefBase { + public: + typedef std::multimap HeaderMap; + + /// + // 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/cef1/include/cef_runnable.h b/cef1/include/cef_runnable.h new file mode 100644 index 000000000..826ddaa46 --- /dev/null +++ b/cef1/include/cef_runnable.h @@ -0,0 +1,346 @@ +// Copyright (c) 2011 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 + +#include "include/cef_base.h" +#include "include/cef_task.h" +#ifdef BUILDING_CEF_SHARED +#include "base/tuple.h" +#else +#include "internal/cef_tuple.h" +#endif + +// 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(CefThreadId threadId) { + 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(CefThreadId threadId) { + 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/cef1/include/cef_scheme.h b/cef1/include/cef_scheme.h new file mode 100644 index 000000000..1bd9a39b2 --- /dev/null +++ b/cef1/include/cef_scheme.h @@ -0,0 +1,222 @@ +// 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_SCHEME_H_ +#define CEF_INCLUDE_CEF_SCHEME_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_response.h" +#include "include/cef_request.h" + +class CefSchemeHandler; +class CefSchemeHandlerFactory; + +/// +// 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()--*/ +bool CefRegisterCustomScheme(const CefString& scheme_name, + bool is_standard, + bool is_local, + bool is_display_isolated); + +/// +// 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 the +// CefRegisterCustomScheme() function should be called for that scheme. +// 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. +/// +/*--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. +/// +/*--cef()--*/ +bool CefClearSchemeHandlerFactories(); + + +/// +// Class that creates CefSchemeHandler instances. 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 scheme handler instance to handle the request. |browser| will + // be the browser window that initiated the request. If the request was + // initiated using the CefWebURLRequest API |browser| will be NULL. The + // |request| object passed to this method will not contain cookie data. + /// + /*--cef()--*/ + virtual CefRefPtr Create(CefRefPtr browser, + const CefString& scheme_name, + CefRefPtr request) =0; +}; + +/// +// Class used to facilitate asynchronous responses to custom scheme handler +// requests. The methods of this class may be called on any thread. +/// +/*--cef(source=library)--*/ +class CefSchemeHandlerCallback : public virtual CefBase { + public: + /// + // Notify that header information is now available for retrieval. + /// + /*--cef()--*/ + virtual void HeadersAvailable() =0; + + /// + // Notify that response data is now available for reading. + /// + /*--cef()--*/ + virtual void BytesAvailable() =0; + + /// + // Cancel processing of the request. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +/// +// Class used to implement a custom scheme handler interface. The methods of +// this class will always be called on the IO thread. +/// +/*--cef(source=client)--*/ +class CefSchemeHandler : public virtual CefBase { + public: + /// + // Begin processing the request. To handle the request return true and call + // HeadersAvailable() once the response header information is available + // (HeadersAvailable() 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 BytesAvailable() 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; + + /// + // Request processing has been canceled. + /// + /*--cef()--*/ + virtual void Cancel() =0; +}; + +#endif // CEF_INCLUDE_CEF_SCHEME_H_ diff --git a/cef1/include/cef_stream.h b/cef1/include/cef_stream.h new file mode 100644 index 000000000..8daae1708 --- /dev/null +++ b/cef1/include/cef_stream.h @@ -0,0 +1,210 @@ +// 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_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; +}; + + +/// +// 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; +}; + + +/// +// 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; +}; + + +/// +// 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; +}; + +#endif // CEF_INCLUDE_CEF_STREAM_H_ diff --git a/cef1/include/cef_task.h b/cef1/include/cef_task.h new file mode 100644 index 000000000..86550f6a0 --- /dev/null +++ b/cef1/include/cef_task.h @@ -0,0 +1,89 @@ +// 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_TASK_H_ +#define CEF_INCLUDE_CEF_TASK_H_ + +#include "include/cef_base.h" + +class CefTask; + +typedef cef_thread_id_t CefThreadId; + +/// +// CEF maintains multiple internal threads that are used for handling different +// types of tasks. The UI thread creates the browser window and is used for all +// interaction with the WebKit rendering engine and V8 JavaScript engine (The +// UI thread will be the same as the main application thread if CefInitialize() +// is called with a CefSettings.multi_threaded_message_loop value of false.) The +// IO thread is used for handling schema and network requests. The FILE thread +// is used for the application cache and other miscellaneous activities. This +// function will return true if called on the specified thread. +/// +/*--cef()--*/ +bool CefCurrentlyOn(CefThreadId threadId); + +/// +// Post a task for execution on the specified thread. This function may be +// called on any thread. +/// +/*--cef()--*/ +bool CefPostTask(CefThreadId threadId, CefRefPtr task); + +/// +// Post a task for delayed execution on the specified thread. This function may +// be called on any thread. +/// +/*--cef()--*/ +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, + int64 delay_ms); + + +/// +// Implement this interface for task execution. The methods of this class may +// be called on any thread. +/// +/*--cef(source=client)--*/ +class CefTask : public virtual CefBase { + public: + /// + // Method that will be executed. |threadId| is the thread executing the call. + /// + /*--cef()--*/ + virtual void Execute(CefThreadId threadId) =0; +}; + +#endif // CEF_INCLUDE_CEF_TASK_H_ diff --git a/cef1/include/cef_url.h b/cef1/include/cef_url.h new file mode 100644 index 000000000..6caa1e229 --- /dev/null +++ b/cef1/include/cef_url.h @@ -0,0 +1,60 @@ +// 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_URL_H_ +#define CEF_INCLUDE_CEF_URL_H_ +#pragma once + +#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); + +#endif // CEF_INCLUDE_CEF_URL_H_ diff --git a/cef1/include/cef_v8.h b/cef1/include/cef_v8.h new file mode 100644 index 000000000..70dd729f6 --- /dev/null +++ b/cef1/include/cef_v8.h @@ -0,0 +1,823 @@ +// 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_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 + +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 +// be called on any 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 that encapsulates a V8 context handle. The methods of this class may +// only be called on the UI thread. +/// +/*--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 browser for this context. + /// + /*--cef()--*/ + virtual CefRefPtr GetBrowser() =0; + + /// + // Returns the frame for this context. + /// + /*--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 always be called on the UI thread. +/// +/*--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 always be called on the UI thread. +/// +/*--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. +/// +/*--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. The methods of this class may only be called +// on the UI thread. +/// +/*--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); + + /// + // 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)--*/ + 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)--*/ + 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)--*/ + 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)--*/ + 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)--*/ + 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. The methods of this class may only be +// called on the UI thread. +/// +/*--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 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. The methods of this class may only be +// called on the UI thread. +/// +/*--cef(source=library)--*/ +class CefV8StackFrame : public virtual CefBase { + public: + /// + // 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/cef1/include/cef_v8context_handler.h b/cef1/include/cef_v8context_handler.h new file mode 100644 index 000000000..5fd82da03 --- /dev/null +++ b/cef1/include/cef_v8context_handler.h @@ -0,0 +1,73 @@ +// 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_V8CONTEXT_HANDLER_H_ +#define CEF_INCLUDE_CEF_V8CONTEXT_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_v8.h" + +/// +// Implement this interface to handle V8 context events. The methods of this +// class will be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefV8ContextHandler : public virtual CefBase { + public: + /// + // Called immediately after the V8 context for a frame has been created. To + // retrieve the JavaScript 'window' object use the CefV8Context::GetGlobal() + // 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) {} +}; + +#endif // CEF_INCLUDE_CEF_V8CONTEXT_HANDLER_H_ diff --git a/cef1/include/cef_web_plugin.h b/cef1/include/cef_web_plugin.h new file mode 100644 index 000000000..e00b2349b --- /dev/null +++ b/cef1/include/cef_web_plugin.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_WEB_PLUGIN_H_ +#define CEF_INCLUDE_CEF_WEB_PLUGIN_H_ + +#include "include/cef_base.h" + +class CefWebPluginInfo; + +/// +// Returns the number of installed web plugins. This method must be called on +// the UI thread. +/// +/*--cef()--*/ +size_t CefGetWebPluginCount(); + +/// +// Returns information for web plugin at the specified zero-based index. This +// method must be called on the UI thread. +/// +/*--cef()--*/ +CefRefPtr CefGetWebPluginInfo(int index); + +/// +// Returns information for web plugin with the specified name. This method must +// be called on the UI thread. +/// +/*--cef(capi_name=cef_get_web_plugin_info_byname)--*/ +CefRefPtr CefGetWebPluginInfo(const CefString& name); + + +/// +// 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; +}; + +#endif // CEF_INCLUDE_CEF_WEB_PLUGIN_H_ diff --git a/cef1/include/cef_web_urlrequest.h b/cef1/include/cef_web_urlrequest.h new file mode 100644 index 000000000..c5f471f9a --- /dev/null +++ b/cef1/include/cef_web_urlrequest.h @@ -0,0 +1,135 @@ +// 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_WEB_URLREQUEST_H_ +#define CEF_INCLUDE_CEF_WEB_URLREQUEST_H_ +#pragma once + +#include "include/cef_base.h" +#include "include/cef_request.h" +#include "include/cef_response.h" + +class CefWebURLRequestClient; + +/// +// Class used to make a Web URL request. Web URL requests are not associated +// with a browser instance so no CefClient callbacks will be executed. The +// methods of this class may be called on any thread. +/// +/*--cef(source=library)--*/ +class CefWebURLRequest : public virtual CefBase { + public: + typedef cef_weburlrequest_state_t RequestState; + + /// + // Create a new CefWebUrlRequest object. + /// + /*--cef()--*/ + static CefRefPtr CreateWebURLRequest( + CefRefPtr request, + CefRefPtr client); + + /// + // Cancels the request. + /// + /*--cef()--*/ + virtual void Cancel() =0; + + /// + // Returns the current ready state of the request. + /// + /*--cef(default_retval=WUR_STATE_UNSENT)--*/ + virtual RequestState GetState() =0; +}; + +/// +// Interface that should be implemented by the CefWebURLRequest client. The +// methods of this class will always be called on the UI thread. +/// +/*--cef(source=client)--*/ +class CefWebURLRequestClient : public virtual CefBase { + public: + typedef cef_weburlrequest_state_t RequestState; + typedef cef_handler_errorcode_t ErrorCode; + + /// + // Notifies the client that the request state has changed. State change + // notifications will always be sent before the below notification methods + // are called. + /// + /*--cef()--*/ + virtual void OnStateChange(CefRefPtr requester, + RequestState state) =0; + + /// + // Notifies the client that the request has been redirected and provides a + // chance to change the request parameters. + /// + /*--cef()--*/ + virtual void OnRedirect(CefRefPtr requester, + CefRefPtr request, + CefRefPtr response) =0; + + /// + // Notifies the client of the response data. + /// + /*--cef()--*/ + virtual void OnHeadersReceived(CefRefPtr requester, + CefRefPtr response) =0; + + /// + // Notifies the client of the upload progress. + /// + /*--cef()--*/ + virtual void OnProgress(CefRefPtr requester, + uint64 bytesSent, uint64 totalBytesToBeSent) =0; + + /// + // Notifies the client that content has been received. + /// + /*--cef()--*/ + virtual void OnData(CefRefPtr requester, + const void* data, int dataLength) =0; + + /// + // Notifies the client that the request ended with an error. + /// + /*--cef()--*/ + virtual void OnError(CefRefPtr requester, + ErrorCode errorCode) =0; +}; + +#endif // CEF_INCLUDE_CEF_WEB_URLREQUEST_H_ diff --git a/cef1/include/cef_xml_reader.h b/cef1/include/cef_xml_reader.h new file mode 100644 index 000000000..e457e0d8d --- /dev/null +++ b/cef1/include/cef_xml_reader.h @@ -0,0 +1,268 @@ +// 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_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/cef1/include/cef_zip_reader.h b/cef1/include/cef_zip_reader.h new file mode 100644 index 000000000..9498f06ed --- /dev/null +++ b/cef1/include/cef_zip_reader.h @@ -0,0 +1,141 @@ +// 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_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/cef1/include/internal/cef_build.h b/cef1/include/internal/cef_build.h new file mode 100644 index 000000000..4b8c54546 --- /dev/null +++ b/cef1/include/internal/cef_build.h @@ -0,0 +1,129 @@ +// 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_BUILD_H_ +#define CEF_INCLUDE_INTERNAL_CEF_BUILD_H_ +#pragma once + +#if defined(BUILDING_CEF_SHARED) + +#include "base/compiler_specific.h" + +#else // !BUILDING_CEF_SHARED + +#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 + +// 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(COMPILER_MSVC) +#define OVERRIDE override +#elif defined(__clang__) +#define OVERRIDE override +#else +#define OVERRIDE +#endif +#endif + +#ifndef 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 + +#endif // !BUILDING_CEF_SHARED + +#endif // CEF_INCLUDE_INTERNAL_CEF_BUILD_H_ diff --git a/cef1/include/internal/cef_export.h b/cef1/include/internal/cef_export.h new file mode 100644 index 000000000..d333a5db8 --- /dev/null +++ b/cef1/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/internal/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/cef1/include/internal/cef_linux.h b/cef1/include/internal/cef_linux.h new file mode 100644 index 000000000..0c9003b06 --- /dev/null +++ b/cef1/include/internal/cef_linux.h @@ -0,0 +1,149 @@ +// 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 + +#if defined(OS_LINUX) +#include +#include "include/internal/cef_types_linux.h" +#include "include/internal/cef_types_wrappers.h" + +/// +// Atomic increment and decrement. +/// +inline long CefAtomicIncrement(long volatile *pDest) { // NOLINT(runtime/int) + return __sync_add_and_fetch(pDest, 1); +} +inline long CefAtomicDecrement(long volatile *pDest) { // NOLINT(runtime/int) + return __sync_sub_and_fetch(pDest, 1); +} + +/// +// Critical section wrapper. +/// +class CefCriticalSection { + public: + CefCriticalSection() { + pthread_mutexattr_init(&attr_); + pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&lock_, &attr_); + } + virtual ~CefCriticalSection() { + pthread_mutex_destroy(&lock_); + pthread_mutexattr_destroy(&attr_); + } + void Lock() { + pthread_mutex_lock(&lock_); + } + void Unlock() { + pthread_mutex_unlock(&lock_); + } + + pthread_mutex_t lock_; + pthread_mutexattr_t attr_; +}; + +/// +// Handle types. +/// +#define CefWindowHandle cef_window_handle_t +#define CefCursorHandle cef_cursor_handle_t + + +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->m_Widget = src->m_Widget; + target->m_ParentWidget = src->m_ParentWidget; + } +}; + +/// +// 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) {} + + void SetAsChild(CefWindowHandle ParentWidget) { + m_ParentWidget = ParentWidget; + } +}; + + +struct CefPrintInfoTraits { + typedef cef_print_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->m_Scale = src->m_Scale; + } +}; + +/// +// Class representing print context information. +/// +typedef CefStructBase CefPrintInfo; + + +struct CefKeyInfoTraits { + typedef cef_key_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->key = src->key; + } +}; + +/// +// Class representing key information. +/// +typedef CefStructBase CefKeyInfo; + +#endif // OS_LINUX + +#endif // CEF_INCLUDE_INTERNAL_CEF_LINUX_H_ diff --git a/cef1/include/internal/cef_mac.h b/cef1/include/internal/cef_mac.h new file mode 100644 index 000000000..d979e80fe --- /dev/null +++ b/cef1/include/internal/cef_mac.h @@ -0,0 +1,178 @@ +// 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 + +#if defined(OS_MACOSX) +#include +#include "include/internal/cef_types_mac.h" +#include "include/internal/cef_types_wrappers.h" + +/// +// Atomic increment and decrement. +/// +inline long CefAtomicIncrement(long volatile *pDest) { // NOLINT(runtime/int) + return __sync_add_and_fetch(pDest, 1); +} +inline long CefAtomicDecrement(long volatile *pDest) { // NOLINT(runtime/int) + return __sync_sub_and_fetch(pDest, 1); +} + +/// +// Handle types. +/// +#define CefWindowHandle cef_window_handle_t +#define CefCursorHandle cef_cursor_handle_t + +/// +// Critical section wrapper. +/// +class CefCriticalSection { + public: + CefCriticalSection() { + pthread_mutexattr_init(&attr_); + pthread_mutexattr_settype(&attr_, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&lock_, &attr_); + } + virtual ~CefCriticalSection() { + pthread_mutex_destroy(&lock_); + pthread_mutexattr_destroy(&attr_); + } + void Lock() { + pthread_mutex_lock(&lock_); + } + void Unlock() { + pthread_mutex_unlock(&lock_); + } + + pthread_mutex_t lock_; + pthread_mutexattr_t attr_; +}; + + +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->m_windowName); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->m_View = src->m_View; + target->m_ParentView = src->m_ParentView; + cef_string_set(src->m_windowName.str, src->m_windowName.length, + &target->m_windowName, copy); + target->m_x = src->m_x; + target->m_y = src->m_y; + target->m_nWidth = src->m_nWidth; + target->m_nHeight = src->m_nHeight; + target->m_bHidden = src->m_bHidden; + target->m_bWindowRenderingDisabled = src->m_bWindowRenderingDisabled; + target->m_bTransparentPainting = src->m_bTransparentPainting; + } +}; + +/// +// 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) {} + + void SetAsChild(CefWindowHandle ParentView, int x, int y, int width, + int height) { + m_ParentView = ParentView; + m_x = x; + m_y = y; + m_nWidth = width; + m_nHeight = height; + m_bHidden = false; + } + + void SetAsOffScreen(NSView* parent) { + m_bWindowRenderingDisabled = true; + m_ParentView = parent; + } + + void SetTransparentPainting(int transparentPainting) { + m_bTransparentPainting = transparentPainting; + } +}; + + +struct CefPrintInfoTraits { + typedef cef_print_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->m_Scale = src->m_Scale; + } +}; + +/// +// Class representing print context information. +/// +typedef CefStructBase CefPrintInfo; + +struct CefKeyInfoTraits { + typedef cef_key_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->keyCode = src->keyCode; + target->character = src->character; + target->characterNoModifiers = src->characterNoModifiers; + } +}; + +/// +// Class representing key information. +/// +typedef CefStructBase CefKeyInfo; + + +#endif // OS_MACOSX + +#endif // CEF_INCLUDE_INTERNAL_CEF_MAC_H_ diff --git a/cef1/include/internal/cef_nplugin_types.h b/cef1/include/internal/cef_nplugin_types.h new file mode 100644 index 000000000..0113f72fb --- /dev/null +++ b/cef1/include/internal/cef_nplugin_types.h @@ -0,0 +1,90 @@ +// 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_NPLUGIN_TYPES_H_ +#define CEF_INCLUDE_INTERNAL_CEF_NPLUGIN_TYPES_H_ +#pragma once + +#include "include/internal/cef_export.h" +#include "include/internal/cef_string.h" +#include "third_party/npapi/bindings/npapi.h" +#include "third_party/npapi/bindings/nphostapi.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Netscape plugins are normally built at separate DLLs that are loaded by the +// browser when needed. This interface supports the creation of plugins that +// are an embedded component of the application. Embedded plugins built using +// this interface use the same Netscape Plugin API as DLL-based plugins. +// See https://developer.mozilla.org/En/Gecko_Plugin_API_Reference for complete +// documentation on how to use the Netscape Plugin API. + +// This structure provides attribute information and entry point functions for +// a plugin. +typedef struct _cef_plugin_info_t { + // The unique name that identifies the plugin. + cef_string_t unique_name; + + // The friendly display name of the plugin. + cef_string_t display_name; + + // The version string of the plugin. + cef_string_t version; + + // A description of the plugin. + cef_string_t description; + + // A pipe (|) delimited list of mime type values that the plugin supports. + cef_string_t mime_types; + + // A pipe (|) delimited list of extension values. Each value is associated + // with the mime type value at the same position. Multiple file extensions + // for the same mime type may be delimited with commas (,). + cef_string_t file_extensions; + + // A pipe (|) delimited list of description values. Each value is associated + // with the mime type value at the same position. + cef_string_t type_descriptions; + + // Entry point function pointers. +#if !defined(OS_POSIX) || defined(OS_MACOSX) + NP_GetEntryPointsFunc np_getentrypoints; +#endif + NP_InitializeFunc np_initialize; + NP_ShutdownFunc np_shutdown; +} cef_plugin_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_NPLUGIN_TYPES_H_ diff --git a/cef1/include/internal/cef_ptr.h b/cef1/include/internal/cef_ptr.h new file mode 100644 index 000000000..fcbe69e5c --- /dev/null +++ b/cef1/include/internal/cef_ptr.h @@ -0,0 +1,199 @@ +// Copyright (c) 2008 Marshall A. Greenblatt. Portions Copyright (c) +// 2006-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. + + +#ifndef CEF_INCLUDE_INTERNAL_CEF_PTR_H_ +#define CEF_INCLUDE_INTERNAL_CEF_PTR_H_ +#pragma once + +#include + +/// +// Smart pointer implementation borrowed from base/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: + CefRefPtr() : ptr_(NULL) { + } + + CefRefPtr(T* p) : ptr_(p) { // NOLINT(runtime/explicit) + if (ptr_) + ptr_->AddRef(); + } + + CefRefPtr(const CefRefPtr& r) : ptr_(r.ptr_) { + if (ptr_) + ptr_->AddRef(); + } + + ~CefRefPtr() { + if (ptr_) + ptr_->Release(); + } + + T* get() const { return ptr_; } + operator T*() const { return ptr_; } + T* operator->() const { return ptr_; } + + CefRefPtr& operator=(T* p) { + // AddRef first so that self assignment should work + if (p) + p->AddRef(); + if (ptr_ ) + ptr_ ->Release(); + ptr_ = p; + return *this; + } + + CefRefPtr& operator=(const CefRefPtr& r) { + return *this = r.ptr_; + } + + void swap(T** pp) { + T* p = ptr_; + ptr_ = *pp; + *pp = p; + } + + void swap(CefRefPtr& r) { + swap(&r.ptr_); // NOLINT(build/include_what_you_use) + } + + private: + T* ptr_; +}; + +#endif // CEF_INCLUDE_INTERNAL_CEF_PTR_H_ diff --git a/cef1/include/internal/cef_string.h b/cef1/include/internal/cef_string.h new file mode 100644 index 000000000..a7876fe56 --- /dev/null +++ b/cef1/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/cef1/include/internal/cef_string_list.h b/cef1/include/internal/cef_string_list.h new file mode 100644 index 000000000..52a0abf2f --- /dev/null +++ b/cef1/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/cef1/include/internal/cef_string_map.h b/cef1/include/internal/cef_string_map.h new file mode 100644 index 000000000..93eea2a55 --- /dev/null +++ b/cef1/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/cef1/include/internal/cef_string_multimap.h b/cef1/include/internal/cef_string_multimap.h new file mode 100644 index 000000000..cd3904244 --- /dev/null +++ b/cef1/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/cef1/include/internal/cef_string_types.h b/cef1/include/internal/cef_string_types.h new file mode 100644 index 000000000..7ab6671cb --- /dev/null +++ b/cef1/include/internal/cef_string_types.h @@ -0,0 +1,204 @@ +// 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. + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/internal/cef_build.h" +#include "include/internal/cef_export.h" +#include + +// 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/cef1/include/internal/cef_string_wrappers.h b/cef1/include/internal/cef_string_wrappers.h new file mode 100644 index 000000000..c0507c1cc --- /dev/null +++ b/cef1/include/internal/cef_string_wrappers.h @@ -0,0 +1,708 @@ +// 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/internal/cef_string_types.h" + +#ifdef BUILDING_CEF_SHARED +#include "base/string16.h" +#endif + + +/// +// 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(BUILDING_CEF_SHARED) +#if defined(WCHAR_T_IS_UTF32) + static inline 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); + string16 str; + if (cstr.length > 0) + str = string16(cstr.str, cstr.length); + cef_string_utf16_clear(&cstr); + return str; + } + static inline bool from_string16(const 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 string16 to_string16(const struct_type *s) { + return string16(s->str, s->length); + } + static inline bool from_string16(const string16& str, struct_type *s) { + return cef_string_wide_set(str.c_str(), str.length(), s, true) ? + true : false; + } +#endif // WCHAR_T_IS_UTF32 +#endif // BUILDING_CEF_SHARED +}; + +/// +// 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; + } +#if defined(BUILDING_CEF_SHARED) + static inline 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); + string16 str; + if (cstr.length > 0) + str = string16(cstr.str, cstr.length); + cef_string_utf16_clear(&cstr); + return str; + } + static inline bool from_string16(const string16& str, struct_type* s) { + return cef_string_utf16_to_utf8(str.c_str(), str.length(), s) ? + true : false; + } +#endif // BUILDING_CEF_SHARED +}; + +/// +// 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 +#if defined(BUILDING_CEF_SHARED) + static inline string16 to_string16(const struct_type* s) { + return string16(s->str, s->length); + } + static inline bool from_string16(const string16& str, struct_type* s) { + return cef_string_utf16_set(str.c_str(), str.length(), s, true) ? + true : false; + } +#endif // BUILDING_CEF_SHARED +}; + +/// +// 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) { + 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) { + FromWString(std::wstring(src)); + } + +#if (defined(BUILDING_CEF_SHARED) && 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 string16& src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + FromString16(src); + } + CefStringBase(const char16* src) // NOLINT(runtime/explicit) + : string_(NULL), owner_(false) { + FromString16(string16(src)); + } +#endif // BUILDING_CEF_SHARED && 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) { + 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_); + } + + + // 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_); + } +#if defined(BUILDING_CEF_SHARED) + /// + // Return this string's data as a string16. Translation will occur if + // necessary based on the underlying string type. + /// + string16 ToString16() const { + if (empty()) + return 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 string16& str) { + if (str.empty()) { + clear(); + return true; + } + AllocIfNeeded(); + return traits::from_string16(str, string_); + } +#endif // BUILDING_CEF_SHARED + + /// + // 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(BUILDING_CEF_SHARED) && defined(WCHAR_T_IS_UTF32)) + operator string16() const { + return ToString16(); + } + CefStringBase& operator=(const string16& str) { + FromString16(str); + return *this; + } + CefStringBase& operator=(const char16* str) { + FromString16(string16(str)); + return *this; + } +#endif // BUILDING_CEF_SHARED && 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/cef1/include/internal/cef_time.h b/cef1/include/internal/cef_time.h new file mode 100644 index 000000000..ccaf19320 --- /dev/null +++ b/cef1/include/internal/cef_time.h @@ -0,0 +1,76 @@ +// 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); + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_TIME_H_ diff --git a/cef1/include/internal/cef_tuple.h b/cef1/include/internal/cef_tuple.h new file mode 100644 index 000000000..d9a1a2c96 --- /dev/null +++ b/cef1/include/internal/cef_tuple.h @@ -0,0 +1,1082 @@ +// 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 identical to base/tuple.h + +// 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_INTERNAL_CEF_TUPLE_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TUPLE_H_ +#pragma once + +#if defined(OS_CHROMEOS) +// To troubleshoot crosbug.com/7327. +#include "base/logging.h" +#endif +// 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)(arg); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1& arg) { +#if defined(OS_CHROMEOS) + // To troubleshoot crosbug.com/7327. + CHECK(obj); + CHECK(&arg); + CHECK(method); +#endif + (obj->*method)(arg.a); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple2& arg) { + (obj->*method)(arg.a, arg.b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& arg) { + (obj->*method)(arg.a, arg.b, arg.c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& arg) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& arg) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& arg) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple7& arg) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f, arg.g); +} + +// 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)(arg.a); +} + +template +inline void DispatchToFunction(Function function, const Tuple2& arg) { + (*function)(arg.a, arg.b); +} + +template +inline void DispatchToFunction(Function function, const Tuple3& arg) { + (*function)(arg.a, arg.b, arg.c); +} + +template +inline void DispatchToFunction(Function function, + const Tuple4& arg) { + (*function)(arg.a, arg.b, arg.c, arg.d); +} + +template +inline void DispatchToFunction(Function function, + const Tuple5& arg) { + (*function)(arg.a, arg.b, arg.c, arg.d, arg.e); +} + +template +inline void DispatchToFunction(Function function, + const Tuple6& arg) { + (*function)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f); +} + +template +inline void DispatchToFunction(Function function, + const Tuple7& arg) { + (*function)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f, arg.g); +} + +template +inline void DispatchToFunction(Function function, + const Tuple8& arg) { + (*function)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f, arg.g, 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)(arg); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple1& arg, Tuple0*) { + (obj->*method)(arg.a); +} + +template +inline void DispatchToMethod(ObjT* obj, + Method method, + const Tuple2& arg, Tuple0*) { + (obj->*method)(arg.a, arg.b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& arg, Tuple0*) { + (obj->*method)(arg.a, arg.b, arg.c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& arg, Tuple0*) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& arg, Tuple0*) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& arg, Tuple0*) { + (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e, 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)(in.a, &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple1* out) { + (obj->*method)(in.a, in.b, &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple1* out) { + (obj->*method)(in.a, in.b, in.c, &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple1* out) { + (obj->*method)(in.a, in.b, in.c, in.d, &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple1* out) { + (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple1* out) { + (obj->*method)(in.a, in.b, in.c, in.d, in.e, 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)(in.a, &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple2* out) { + (obj->*method)(in.a, in.b, &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple2* out) { + (obj->*method)(in.a, in.b, in.c, &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple2* out) { + (obj->*method)(in.a, in.b, in.c, in.d, &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple2* out) { + (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a, &out->b); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple2* out) { + (obj->*method)(in.a, in.b, in.c, in.d, in.e, 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)(in.a, &out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple2& in, + Tuple3* out) { + (obj->*method)(in.a, in.b, &out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple3& in, + Tuple3* out) { + (obj->*method)(in.a, in.b, in.c, &out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple4& in, + Tuple3* out) { + (obj->*method)(in.a, in.b, in.c, in.d, &out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple5& in, + Tuple3* out) { + (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a, &out->b, &out->c); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple6& in, + Tuple3* out) { + (obj->*method)(in.a, in.b, in.c, in.d, in.e, 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)(in, &out->a, &out->b, &out->c, &out->d); +} + +template +inline void DispatchToMethod(ObjT* obj, Method method, + const Tuple1& in, + Tuple4* out) { + (obj->*method)(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)(in.a, 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)(in.a, in.b, 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)(in.a, in.b, in.c, 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)(in.a, in.b, in.c, in.d, 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)(in.a, in.b, in.c, in.d, in.e, 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)(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)(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)(in.a, 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)(in.a, in.b, 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)(in.a, in.b, in.c, 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)(in.a, in.b, in.c, in.d, 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)(in.a, in.b, in.c, in.d, in.e, in.f, + &out->a, &out->b, &out->c, &out->d, &out->e); +} + +#endif // CEF_INCLUDE_INTERNAL_CEF_TUPLE_H_ diff --git a/cef1/include/internal/cef_types.h b/cef1/include/internal/cef_types.h new file mode 100644 index 000000000..f2ee43852 --- /dev/null +++ b/cef1/include/internal/cef_types.h @@ -0,0 +1,1105 @@ +// 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_TYPES_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_H_ +#pragma once + +#include "include/internal/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 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 + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Log severity levels. +/// +enum cef_log_severity_t { + LOGSEVERITY_VERBOSE = -1, + LOGSEVERITY_INFO, + LOGSEVERITY_WARNING, + LOGSEVERITY_ERROR, + LOGSEVERITY_ERROR_REPORT, + // Disables logging completely. + LOGSEVERITY_DISABLE = 99 +}; + +/// +// Initialization settings. Specify NULL or 0 to get the recommended default +// values. +/// +typedef struct _cef_settings_t { + /// + // Size of this structure. + /// + size_t size; + + /// + // Set to true (1) to have the message loop run in a separate thread. If + // false (0) than the CefDoMessageLoopWork() function must be called from + // your application message loop. + /// + bool multi_threaded_message_loop; + + /// + // The location where cache data will be stored on disk. If empty an + // in-memory cache will be used. HTML5 databases such as localStorage will + // only persist across sessions if a cache path is specified. + /// + cef_string_t cache_path; + + /// + // Value that will be returned as the User-Agent HTTP header. If empty the + // default User-Agent string will be used. + /// + 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. + /// + 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. + /// + cef_string_t locale; + + /// + // List of fully qualified paths to plugins (including plugin name) that will + // be loaded in addition to any plugins found in the default search paths. + /// + cef_string_list_t extra_plugin_paths; + + /// + // 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. + /// + cef_string_t log_file; + + /// + // The log severity. Only messages of this severity level or higher will be + // logged. + /// + cef_log_severity_t log_severity; + + /// + // The graphics implementation that CEF will use for rendering GPU accelerated + // content like WebGL, accelerated layers and 3D CSS. + /// + cef_graphics_implementation_t graphics_implementation; + + /// + // Quota limit for localStorage data across all origins. Default size is 5MB. + /// + unsigned int local_storage_quota; + + /// + // Quota limit for sessionStorage data per namespace. Default size is 5MB. + /// + unsigned int session_storage_quota; + + /// + // Custom flags that will be used when initializing the V8 JavaScript engine. + // The consequences of using custom flags may not be well tested. + /// + cef_string_t javascript_flags; + +#if defined(OS_WIN) + /// + // Set to true (1) to use the system proxy resolver on Windows when + // "Automatically detect settings" is checked. This setting is disabled + // by default for performance reasons. + /// + bool auto_detect_proxy_settings_enabled; +#endif + + /// + // The fully qualified path for the cef.pak file. If this value is empty + // the cef.pak file 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 + // resource directory. + /// + cef_string_t pack_file_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 resource directory. + /// + 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 renderer + // processes via CefApp::GetResourceBundleHandler() if loading of pack files + // is disabled. + /// + bool pack_loading_disabled; +} 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. +/// +typedef struct _cef_browser_settings_t { + /// + // Size of this structure. + /// + size_t size; + + /// + // Disable drag & drop of URLs from other windows. + /// + bool drag_drop_disabled; + + /// + // Disable default navigation resulting from drag & drop of URLs. + /// + bool load_drops_disabled; + + /// + // Disable history back/forward navigation. + /// + bool history_disabled; + + // 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; + + /// + // Set to true (1) to disable loading of fonts from remote sources. + /// + bool remote_fonts_disabled; + + /// + // Default encoding for Web content. If empty "ISO-8859-1" will be used. + /// + cef_string_t default_encoding; + + /// + // Set to true (1) to attempt automatic detection of content encoding. + /// + bool encoding_detector_enabled; + + /// + // Set to true (1) to disable JavaScript. + /// + bool javascript_disabled; + + /// + // Set to true (1) to disallow JavaScript from opening windows. + /// + bool javascript_open_windows_disallowed; + + /// + // Set to true (1) to disallow JavaScript from closing windows. + /// + bool javascript_close_windows_disallowed; + + /// + // Set to true (1) to disallow JavaScript from accessing the clipboard. + /// + bool javascript_access_clipboard_disallowed; + + /// + // Set to true (1) to disable DOM pasting in the editor. DOM pasting also + // depends on |javascript_cannot_access_clipboard| being false (0). + /// + bool dom_paste_disabled; + + /// + // Set to true (1) to enable drawing of the caret position. + /// + bool caret_browsing_enabled; + + /// + // Set to true (1) to disable Java. + /// + bool java_disabled; + + /// + // Set to true (1) to disable plugins. + /// + bool plugins_disabled; + + /// + // Set to true (1) to allow access to all URLs from file URLs. + /// + bool universal_access_from_file_urls_allowed; + + /// + // Set to true (1) to allow access to file URLs from other file URLs. + /// + bool file_access_from_file_urls_allowed; + + /// + // Set to true (1) to allow risky security behavior such as cross-site + // scripting (XSS). Use with extreme care. + /// + bool web_security_disabled; + + /// + // Set to true (1) to enable console warnings about XSS attempts. + /// + bool xss_auditor_enabled; + + /// + // Set to true (1) to suppress the network load of image URLs. A cached + // image will still be rendered if requested. + /// + bool image_load_disabled; + + /// + // Set to true (1) to shrink standalone images to fit the page. + /// + bool shrink_standalone_images_to_fit; + + /// + // Set to true (1) to disable browser backwards compatibility features. + /// + bool site_specific_quirks_disabled; + + /// + // Set to true (1) to disable resize of text areas. + /// + bool text_area_resize_disabled; + + /// + // Set to true (1) to disable use of the page cache. + /// + bool page_cache_disabled; + + /// + // Set to true (1) to not have the tab key advance focus to links. + /// + bool tab_to_links_disabled; + + /// + // Set to true (1) to disable hyperlink pings ( and window.sendPing). + /// + bool hyperlink_auditing_disabled; + + /// + // Set to true (1) to enable the user style sheet for all pages. + /// + bool user_style_sheet_enabled; + + /// + // Location of the user style sheet. This must be a data URL of the form + // "data:text/css;charset=utf-8;base64,csscontent" where "csscontent" is the + // base64 encoded contents of the CSS file. + /// + cef_string_t user_style_sheet_location; + + /// + // Set to true (1) to disable style sheets. + /// + bool author_and_user_styles_disabled; + + /// + // Set to true (1) to disable local storage. + /// + bool local_storage_disabled; + + /// + // Set to true (1) to disable databases. + /// + bool databases_disabled; + + /// + // Set to true (1) to disable application cache. + /// + bool application_cache_disabled; + + /// + // Set to true (1) to disable WebGL. + /// + bool webgl_disabled; + + /// + // Set to true (1) to enable accelerated compositing. This is turned off by + // default because the current in-process GPU implementation does not + // support it correctly. + /// + bool accelerated_compositing_enabled; + + /// + // Set to true (1) to disable accelerated layers. This affects features like + // 3D CSS transforms. + /// + bool accelerated_layers_disabled; + + /// + // Set to true (1) to disable accelerated video. + /// + bool accelerated_video_disabled; + + /// + // Set to true (1) to disable accelerated 2d canvas. + /// + bool accelerated_2d_canvas_disabled; + + /// + // Set to true (1) to disable accelerated painting. + /// + bool accelerated_painting_disabled; + + /// + // Set to true (1) to disable accelerated filters. + /// + bool accelerated_filters_disabled; + + /// + // Set to true (1) to disable accelerated plugins. + /// + bool accelerated_plugins_disabled; + + /// + // Set to true (1) to disable developer tools (WebKit inspector). + /// + bool developer_tools_disabled; + + /// + // Set to true (1) to enable fullscreen mode. + /// + bool fullscreen_enabled; +} 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; + + /// + // 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. + /// + bool secure; + + /// + // If |httponly| is true the cookie will only be sent for HTTP requests. + /// + bool 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. + /// + bool has_expires; + cef_time_t expires; +} cef_cookie_t; + +/// +// Storage types. +/// +enum cef_storage_type_t { + ST_LOCALSTORAGE = 0, + ST_SESSIONSTORAGE, +}; + +/// +// Mouse button types. +/// +enum cef_mouse_button_type_t { + MBT_LEFT = 0, + MBT_MIDDLE, + MBT_RIGHT, +}; + +/// +// Key types. +/// +enum cef_key_type_t { + KT_KEYUP = 0, + KT_KEYDOWN, + KT_CHAR, +}; + +/// +// Various browser navigation types supported by chrome. +/// +enum cef_handler_navtype_t { + NAVTYPE_LINKCLICKED = 0, + NAVTYPE_FORMSUBMITTED, + NAVTYPE_BACKFORWARD, + NAVTYPE_RELOAD, + NAVTYPE_FORMRESUBMITTED, + NAVTYPE_OTHER, + NAVTYPE_LINKDROPPED, +}; + +/// +// Supported error code values. See net\base\net_error_list.h for complete +// descriptions of the error codes. +/// +enum cef_handler_errorcode_t { + 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, +}; + +/// +// "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. +/// +enum cef_drag_operations_mask_t { + 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 +}; + +/// +// V8 access control values. +/// +enum cef_v8_accesscontrol_t { + 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 +}; + +/// +// V8 property attribute values. +/// +enum cef_v8_propertyattribute_t { + 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 +}; + +/// +// Structure representing menu information. +/// +typedef struct _cef_menu_info_t { + /// + // Values from the cef_handler_menutypebits_t enumeration. + /// + int typeFlags; + + /// + // If window rendering is enabled |x| and |y| will be in screen coordinates. + // Otherwise, |x| and |y| will be in view coordinates. + /// + int x; + int y; + + cef_string_t linkUrl; + cef_string_t imageUrl; + cef_string_t pageUrl; + cef_string_t frameUrl; + cef_string_t selectionText; + cef_string_t misspelledWord; + + /// + // Values from the cef_handler_menucapabilitybits_t enumeration. + /// + int editFlags; + + cef_string_t securityInfo; +} cef_menu_info_t; + +/// +// The cef_menu_info_t typeFlags value will be a combination of the +// following values. +/// +enum cef_menu_typebits_t { + /// + // No node is selected + /// + MENUTYPE_NONE = 0x0, + /// + // The top page is selected + /// + MENUTYPE_PAGE = 0x1, + /// + // A subframe page is selected + /// + MENUTYPE_FRAME = 0x2, + /// + // A link is selected + /// + MENUTYPE_LINK = 0x4, + /// + // An image is selected + /// + MENUTYPE_IMAGE = 0x8, + /// + // There is a textual or mixed selection that is selected + /// + MENUTYPE_SELECTION = 0x10, + /// + // An editable element is selected + /// + MENUTYPE_EDITABLE = 0x20, + /// + // A misspelled word is selected + /// + MENUTYPE_MISSPELLED_WORD = 0x40, + /// + // A video node is selected + /// + MENUTYPE_VIDEO = 0x80, + /// + // A video node is selected + /// + MENUTYPE_AUDIO = 0x100, +}; + +/// +// The cef_menu_info_t editFlags value will be a combination of the +// following values. +/// +enum cef_menu_capabilitybits_t { + // Values from WebContextMenuData::EditFlags in WebContextMenuData.h + MENU_CAN_DO_NONE = 0x0, + MENU_CAN_UNDO = 0x1, + MENU_CAN_REDO = 0x2, + MENU_CAN_CUT = 0x4, + MENU_CAN_COPY = 0x8, + MENU_CAN_PASTE = 0x10, + MENU_CAN_DELETE = 0x20, + MENU_CAN_SELECT_ALL = 0x40, + MENU_CAN_TRANSLATE = 0x80, + // Values unique to CEF + MENU_CAN_GO_FORWARD = 0x10000000, + MENU_CAN_GO_BACK = 0x20000000, +}; + +/// +// Supported menu ID values. +/// +enum cef_menu_id_t { + MENU_ID_NAV_BACK = 10, + MENU_ID_NAV_FORWARD = 11, + MENU_ID_NAV_RELOAD = 12, + MENU_ID_NAV_RELOAD_NOCACHE = 13, + MENU_ID_NAV_STOP = 14, + MENU_ID_UNDO = 20, + MENU_ID_REDO = 21, + MENU_ID_CUT = 22, + MENU_ID_COPY = 23, + MENU_ID_PASTE = 24, + MENU_ID_DELETE = 25, + MENU_ID_SELECTALL = 26, + MENU_ID_PRINT = 30, + MENU_ID_VIEWSOURCE = 31, +}; + +enum cef_paint_element_type_t { + PET_VIEW = 0, + PET_POPUP, +}; + +/// +// Post data elements may represent either bytes or files. +/// +enum cef_postdataelement_type_t { + PDE_TYPE_EMPTY = 0, + PDE_TYPE_BYTES, + PDE_TYPE_FILE, +}; + +enum cef_weburlrequest_flags_t { + WUR_FLAG_NONE = 0, + WUR_FLAG_SKIP_CACHE = 0x1, + WUR_FLAG_ALLOW_CACHED_CREDENTIALS = 0x2, + WUR_FLAG_ALLOW_COOKIES = 0x4, + WUR_FLAG_REPORT_UPLOAD_PROGRESS = 0x8, + WUR_FLAG_REPORT_LOAD_TIMING = 0x10, + WUR_FLAG_REPORT_RAW_HEADERS = 0x20 +}; + +enum cef_weburlrequest_state_t { + WUR_STATE_UNSENT = 0, + WUR_STATE_STARTED = 1, + WUR_STATE_HEADERS_RECEIVED = 2, + WUR_STATE_LOADING = 3, + WUR_STATE_DONE = 4, + WUR_STATE_ERROR = 5, + WUR_STATE_ABORT = 6, +}; + +/// +// Focus sources. +/// +enum cef_handler_focus_source_t { + /// + // 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, + /// + // The source is a child widget of the browser window requesting focus. + /// + FOCUS_SOURCE_WIDGET, +}; + +/// +// Key event types. +/// +enum cef_handler_keyevent_type_t { + KEYEVENT_RAWKEYDOWN = 0, + KEYEVENT_KEYDOWN, + KEYEVENT_KEYUP, + KEYEVENT_CHAR +}; + +/// +// Key event modifiers. +/// +enum cef_handler_keyevent_modifiers_t { + KEY_SHIFT = 1 << 0, + KEY_CTRL = 1 << 1, + KEY_ALT = 1 << 2, + KEY_META = 1 << 3, + KEY_KEYPAD = 1 << 4, // Only used on Mac OS-X +}; + +/// +// Structure representing a rectangle. +/// +typedef struct _cef_rect_t { + int x; + int y; + int width; + int height; +} cef_rect_t; + +/// +// Existing thread IDs. +/// +enum cef_thread_id_t { + TID_UI = 0, + TID_IO = 1, + TID_FILE = 2, +}; + +/// +// Paper type for printing. +/// +enum cef_paper_type_t { + PT_LETTER = 0, + PT_LEGAL, + PT_EXECUTIVE, + PT_A3, + PT_A4, + PT_CUSTOM +}; + +/// +// Paper metric information for printing. +/// +struct cef_paper_metrics { + enum cef_paper_type_t paper_type; + // Length and width needed if paper_type is custom_size + // Units are in inches. + double length; + double width; +}; + +/// +// Paper print margins. +/// +struct cef_print_margins { + // Margin size in inches for left/right/top/bottom (this is content margins). + double left; + double right; + double top; + double bottom; + // Margin size (top/bottom) in inches for header/footer. + double header; + double footer; +}; + +/// +// Page orientation for printing. +/// +enum cef_page_orientation { + PORTRAIT = 0, + LANDSCAPE +}; + +/// +// Printing options. +/// +typedef struct _cef_print_options_t { + enum cef_page_orientation page_orientation; + struct cef_paper_metrics paper_metrics; + struct cef_print_margins paper_margins; +} cef_print_options_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. +/// +enum cef_xml_encoding_type_t { + XML_ENCODING_NONE = 0, + XML_ENCODING_UTF8, + XML_ENCODING_UTF16LE, + XML_ENCODING_UTF16BE, + XML_ENCODING_ASCII, +}; + +/// +// XML node types. +/// +enum cef_xml_node_type_t { + 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, +}; + +/// +// Status message types. +/// +enum cef_handler_statustype_t { + STATUSTYPE_TEXT = 0, + STATUSTYPE_MOUSEOVER_URL, + STATUSTYPE_KEYBOARD_FOCUS_URL, +}; + +/// +// Popup window features. +/// +typedef struct _cef_popup_features_t { + int x; + bool xSet; + int y; + bool ySet; + int width; + bool widthSet; + int height; + bool heightSet; + + bool menuBarVisible; + bool statusBarVisible; + bool toolBarVisible; + bool locationBarVisible; + bool scrollbarsVisible; + bool resizable; + + bool fullscreen; + bool dialog; + cef_string_list_t additionalFeatures; +} cef_popup_features_t; + +/// +// DOM document types. +/// +enum cef_dom_document_type_t { + DOM_DOCUMENT_TYPE_UNKNOWN = 0, + DOM_DOCUMENT_TYPE_HTML, + DOM_DOCUMENT_TYPE_XHTML, + DOM_DOCUMENT_TYPE_PLUGIN, +}; + +/// +// DOM event category flags. +/// +enum cef_dom_event_category_t { + 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, + DOM_EVENT_CATEGORY_WEBKIT_ANIMATION = 0x10000, + DOM_EVENT_CATEGORY_WEBKIT_TRANSITION = 0x20000, + DOM_EVENT_CATEGORY_BEFORE_LOAD = 0x40000, +}; + +/// +// DOM event processing phases. +/// +enum cef_dom_event_phase_t { + DOM_EVENT_PHASE_UNKNOWN = 0, + DOM_EVENT_PHASE_CAPTURING, + DOM_EVENT_PHASE_AT_TARGET, + DOM_EVENT_PHASE_BUBBLING, +}; + +/// +// DOM node types. +/// +enum cef_dom_node_type_t { + 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_ENTITY_REFERENCE, + DOM_NODE_TYPE_ENTITY, + DOM_NODE_TYPE_PROCESSING_INSTRUCTIONS, + DOM_NODE_TYPE_COMMENT, + DOM_NODE_TYPE_DOCUMENT, + DOM_NODE_TYPE_DOCUMENT_TYPE, + DOM_NODE_TYPE_DOCUMENT_FRAGMENT, + DOM_NODE_TYPE_NOTATION, + DOM_NODE_TYPE_XPATH_NAMESPACE, +}; + +/// +// Proxy types. +/// +enum cef_proxy_type_t { + PROXY_TYPE_DIRECT = 0, + PROXY_TYPE_NAMED, + PROXY_TYPE_PAC_STRING, +}; + +/// +// Proxy information. +/// +typedef struct _cef_proxy_info_t { + enum cef_proxy_type_t proxyType; + cef_string_t proxyList; +} cef_proxy_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_H_ diff --git a/cef1/include/internal/cef_types_linux.h b/cef1/include/internal/cef_types_linux.h new file mode 100644 index 000000000..15966907e --- /dev/null +++ b/cef1/include/internal/cef_types_linux.h @@ -0,0 +1,88 @@ +// 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_TYPES_LINUX_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_LINUX_H_ +#pragma once + +#include "include/internal/cef_build.h" + +#if defined(OS_LINUX) +#include +#include "include/internal/cef_string.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Window handle. +#define cef_window_handle_t GtkWidget* +#define cef_cursor_handle_t void* + +/// +// Supported graphics implementations. +/// +enum cef_graphics_implementation_t { + DESKTOP_IN_PROCESS = 0, + DESKTOP_IN_PROCESS_COMMAND_BUFFER, +}; + +/// +// Class representing window information. +/// +typedef struct _cef_window_info_t { + // Pointer for the parent GtkBox widget. + cef_window_handle_t m_ParentWidget; + + // Pointer for the new browser widget. + cef_window_handle_t m_Widget; +} cef_window_info_t; + +/// +// Class representing print context information. +/// +typedef struct _cef_print_info_t { + double m_Scale; +} cef_print_info_t; + +/// +// Class representing key information. +/// +typedef struct _cef_key_info_t { + int key; +} cef_key_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // OS_LINUX + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_LINUX_H_ diff --git a/cef1/include/internal/cef_types_mac.h b/cef1/include/internal/cef_types_mac.h new file mode 100644 index 000000000..a10c54016 --- /dev/null +++ b/cef1/include/internal/cef_types_mac.h @@ -0,0 +1,116 @@ +// 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_TYPES_MAC_H_ +#define CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_ +#pragma once + +#include "include/internal/cef_build.h" + +#if defined(OS_MACOSX) +#include "include/internal/cef_string.h" + +// Window handle. +#ifdef __cplusplus +#ifdef __OBJC__ +@class NSCursor; +@class NSView; +#else +class NSCursor; +struct NSView; +#endif +#define cef_window_handle_t NSView* +#define cef_cursor_handle_t NSCursor* +#else +#define cef_window_handle_t void* +#define cef_cursor_handle_t void* +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/// +// Supported graphics implementations. +/// +enum cef_graphics_implementation_t { + DESKTOP_IN_PROCESS = 0, + DESKTOP_IN_PROCESS_COMMAND_BUFFER, +}; + +/// +// Class representing window information. +/// +typedef struct _cef_window_info_t { + cef_string_t m_windowName; + int m_x; + int m_y; + int m_nWidth; + int m_nHeight; + int m_bHidden; + + // NSView pointer for the parent view. + cef_window_handle_t m_ParentView; + + // If window rendering is disabled no browser window will be created. Set + // |m_ParentView| to the window that will act as the parent for popup menus, + // dialog boxes, etc. + int m_bWindowRenderingDisabled; + + // Set to true to enable transparent painting. + int m_bTransparentPainting; + + // NSView pointer for the new browser view. + cef_window_handle_t m_View; +} cef_window_info_t; + +/// +// Class representing print context information. +/// +typedef struct _cef_print_info_t { + double m_Scale; +} cef_print_info_t; + +/// +// Class representing key information. +/// +typedef struct _cef_key_info_t { + int keyCode; + int character; + int characterNoModifiers; +} cef_key_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // OS_MACOSX + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_MAC_H_ diff --git a/cef1/include/internal/cef_types_win.h b/cef1/include/internal/cef_types_win.h new file mode 100644 index 000000000..9b5e48e59 --- /dev/null +++ b/cef1/include/internal/cef_types_win.h @@ -0,0 +1,110 @@ +// 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/internal/cef_build.h" + +#if defined(OS_WIN) +#include +#include "include/internal/cef_string.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Window handle. +#define cef_window_handle_t HWND +#define cef_cursor_handle_t HCURSOR + +/// +// Supported graphics implementations. +/// +enum cef_graphics_implementation_t { + ANGLE_IN_PROCESS = 0, + ANGLE_IN_PROCESS_COMMAND_BUFFER, + DESKTOP_IN_PROCESS, + DESKTOP_IN_PROCESS_COMMAND_BUFFER, +}; + +/// +// Class representing window information. +/// +typedef struct _cef_window_info_t { + // Standard parameters required by CreateWindowEx() + DWORD m_dwExStyle; + cef_string_t m_windowName; + DWORD m_dwStyle; + int m_x; + int m_y; + int m_nWidth; + int m_nHeight; + cef_window_handle_t m_hWndParent; + HMENU m_hMenu; + + // If window rendering is disabled no browser window will be created. Set + // |m_hWndParent| to the window that will act as the parent for popup menus, + // dialog boxes, etc. + BOOL m_bWindowRenderingDisabled; + + // Set to true to enable transparent painting. + BOOL m_bTransparentPainting; + + // Handle for the new browser window. + cef_window_handle_t m_hWnd; +} cef_window_info_t; + +/// +// Class representing print context information. +/// +typedef struct _cef_print_info_t { + HDC m_hDC; + RECT m_Rect; + double m_Scale; +} cef_print_info_t; + +/// +// Class representing key information. +/// +typedef struct _cef_key_info_t { + int key; + BOOL sysChar; + BOOL imeChar; +} cef_key_info_t; + +#ifdef __cplusplus +} +#endif + +#endif // OS_WIN + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_WIN_H_ diff --git a/cef1/include/internal/cef_types_wrappers.h b/cef1/include/internal/cef_types_wrappers.h new file mode 100644 index 000000000..10e37346e --- /dev/null +++ b/cef1/include/internal/cef_types_wrappers.h @@ -0,0 +1,641 @@ +// 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_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 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 CefPrintOptionsTraits { + typedef cef_print_options_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 print options. +/// +typedef CefStructBase CefPrintOptions; + + + +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->cache_path); + cef_string_clear(&s->user_agent); + cef_string_clear(&s->product_version); + cef_string_clear(&s->locale); + if (s->extra_plugin_paths) + cef_string_list_free(s->extra_plugin_paths); + cef_string_clear(&s->log_file); + cef_string_clear(&s->javascript_flags); + cef_string_clear(&s->pack_file_path); + cef_string_clear(&s->locales_dir_path); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->multi_threaded_message_loop = src->multi_threaded_message_loop; + + cef_string_set(src->cache_path.str, src->cache_path.length, + &target->cache_path, copy); + 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); + + if (target->extra_plugin_paths) + cef_string_list_free(target->extra_plugin_paths); + target->extra_plugin_paths = src->extra_plugin_paths ? + cef_string_list_copy(src->extra_plugin_paths) : NULL; + + cef_string_set(src->log_file.str, src->log_file.length, &target->log_file, + copy); + target->log_severity = src->log_severity; + target->graphics_implementation = src->graphics_implementation; + target->local_storage_quota = src->local_storage_quota; + target->session_storage_quota = src->session_storage_quota; + cef_string_set(src->javascript_flags.str, src->javascript_flags.length, + &target->javascript_flags, copy); + +#if defined(OS_WIN) + target->auto_detect_proxy_settings_enabled = + src->auto_detect_proxy_settings_enabled; +#endif + + cef_string_set(src->pack_file_path.str, src->pack_file_path.length, + &target->pack_file_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; + } +}; + +/// +// 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); + cef_string_clear(&s->user_style_sheet_location); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->drag_drop_disabled = src->drag_drop_disabled; + target->load_drops_disabled = src->load_drops_disabled; + target->history_disabled = src->history_disabled; + + 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; + target->remote_fonts_disabled = src->remote_fonts_disabled; + + cef_string_set(src->default_encoding.str, src->default_encoding.length, + &target->default_encoding, copy); + + target->encoding_detector_enabled = src->encoding_detector_enabled; + target->javascript_disabled = src->javascript_disabled; + target->javascript_open_windows_disallowed = + src->javascript_open_windows_disallowed; + target->javascript_close_windows_disallowed = + src->javascript_close_windows_disallowed; + target->javascript_access_clipboard_disallowed = + src->javascript_access_clipboard_disallowed; + target->dom_paste_disabled = src->dom_paste_disabled; + target->caret_browsing_enabled = src->caret_browsing_enabled; + target->java_disabled = src->java_disabled; + target->plugins_disabled = src->plugins_disabled; + target->universal_access_from_file_urls_allowed = + src->universal_access_from_file_urls_allowed; + target->file_access_from_file_urls_allowed = + src->file_access_from_file_urls_allowed; + target->web_security_disabled = src->web_security_disabled; + target->xss_auditor_enabled = src->xss_auditor_enabled; + target->image_load_disabled = src->image_load_disabled; + target->shrink_standalone_images_to_fit = + src->shrink_standalone_images_to_fit; + target->site_specific_quirks_disabled = src->site_specific_quirks_disabled; + target->text_area_resize_disabled = src->text_area_resize_disabled; + target->page_cache_disabled = src->page_cache_disabled; + target->tab_to_links_disabled = src->tab_to_links_disabled; + target->hyperlink_auditing_disabled = src->hyperlink_auditing_disabled; + target->user_style_sheet_enabled = src->user_style_sheet_enabled; + + cef_string_set(src->user_style_sheet_location.str, + src->user_style_sheet_location.length, + &target->user_style_sheet_location, copy); + + target->author_and_user_styles_disabled = + src->author_and_user_styles_disabled; + target->local_storage_disabled = src->local_storage_disabled; + target->databases_disabled = src->databases_disabled; + target->application_cache_disabled = src->application_cache_disabled; + target->webgl_disabled = src->webgl_disabled; + target->accelerated_compositing_enabled = + src->accelerated_compositing_enabled; + target->accelerated_layers_disabled = src->accelerated_layers_disabled; + target->accelerated_video_disabled = src->accelerated_video_disabled; + target->accelerated_2d_canvas_disabled = + src->accelerated_2d_canvas_disabled; + target->accelerated_painting_disabled = src->accelerated_painting_disabled; + target->accelerated_filters_disabled = src->accelerated_filters_disabled; + target->accelerated_plugins_disabled = src->accelerated_plugins_disabled; + target->developer_tools_disabled = src->developer_tools_disabled; + target->fullscreen_enabled = src->fullscreen_enabled; + } +}; + +/// +// 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->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->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; + } +}; + + +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 CefMenuInfoTraits { + typedef cef_menu_info_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->linkUrl); + cef_string_clear(&s->imageUrl); + cef_string_clear(&s->pageUrl); + cef_string_clear(&s->frameUrl); + cef_string_clear(&s->selectionText); + cef_string_clear(&s->misspelledWord); + cef_string_clear(&s->securityInfo); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->typeFlags = src->typeFlags; + target->x = src->x; + target->y = src->y; + + cef_string_set(src->linkUrl.str, src->linkUrl.length, + &target->linkUrl, copy); + cef_string_set(src->imageUrl.str, src->imageUrl.length, + &target->imageUrl, copy); + cef_string_set(src->pageUrl.str, src->pageUrl.length, + &target->pageUrl, copy); + cef_string_set(src->frameUrl.str, src->frameUrl.length, + &target->frameUrl, copy); + cef_string_set(src->selectionText.str, src->selectionText.length, + &target->selectionText, copy); + cef_string_set(src->misspelledWord.str, src->misspelledWord.length, + &target->misspelledWord, copy); + cef_string_set(src->securityInfo.str, src->securityInfo.length, + &target->securityInfo, copy); + + target->editFlags = src->editFlags; + } +}; + +/// +// Class representing menu info. +/// +typedef CefStructBase CefMenuInfo; + + +struct CefProxyInfoTraits { + typedef cef_proxy_info_t struct_type; + + static inline void init(struct_type* s) {} + + static inline void clear(struct_type* s) { + cef_string_clear(&s->proxyList); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->proxyType = src->proxyType; + cef_string_set(src->proxyList.str, src->proxyList.length, + &target->proxyList, copy); + } +}; + +/// +// Class representing the results of proxy resolution. +/// +class CefProxyInfo : public CefStructBase { + public: + /// + // Use a direction connection instead of a proxy. + /// + void UseDirect() { + proxyType = PROXY_TYPE_DIRECT; + } + + /// + // Use one or more named proxy servers specified in WinHTTP format. Each proxy + // server is of the form: + // + // ["://"][":"] + // + // Multiple values may be separated by semicolons or whitespace. For example, + // "foo1:80;foo2:80". + /// + void UseNamedProxy(const CefString& proxy_uri_list) { + proxyType = PROXY_TYPE_NAMED; + (CefString(&proxyList)) = proxy_uri_list; + } + + /// + // Use one or more named proxy servers specified in PAC script format. For + // example, "PROXY foobar:99; SOCKS fml:2; DIRECT". + /// + void UsePacString(const CefString& pac_string) { + proxyType = PROXY_TYPE_PAC_STRING; + (CefString(&proxyList)) = pac_string; + } + + bool IsDirect() const { return proxyType == PROXY_TYPE_DIRECT; } + bool IsNamedProxy() const { return proxyType == PROXY_TYPE_NAMED; } + bool IsPacString() const { return proxyType == PROXY_TYPE_PAC_STRING; } + + CefString ProxyList() const { return CefString(&proxyList); } +}; + +#endif // CEF_INCLUDE_INTERNAL_CEF_TYPES_WRAPPERS_H_ diff --git a/cef1/include/internal/cef_win.h b/cef1/include/internal/cef_win.h new file mode 100644 index 000000000..68d91dced --- /dev/null +++ b/cef1/include/internal/cef_win.h @@ -0,0 +1,186 @@ +// 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 + +#if defined(OS_WIN) +#include +#include "include/internal/cef_types_win.h" +#include "include/internal/cef_types_wrappers.h" + +/// +// Atomic increment and decrement. +/// +#define CefAtomicIncrement(p) InterlockedIncrement(p) +#define CefAtomicDecrement(p) InterlockedDecrement(p) + +/// +// Critical section wrapper. +/// +class CefCriticalSection { + public: + CefCriticalSection() { + memset(&m_sec, 0, sizeof(CRITICAL_SECTION)); + InitializeCriticalSection(&m_sec); + } + virtual ~CefCriticalSection() { + DeleteCriticalSection(&m_sec); + } + void Lock() { + EnterCriticalSection(&m_sec); + } + void Unlock() { + LeaveCriticalSection(&m_sec); + } + + CRITICAL_SECTION m_sec; +}; + +/// +// Handle types. +/// +#define CefWindowHandle cef_window_handle_t +#define CefCursorHandle cef_cursor_handle_t + +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->m_windowName); + } + + static inline void set(const struct_type* src, struct_type* target, + bool copy) { + target->m_dwExStyle = src->m_dwExStyle; + cef_string_set(src->m_windowName.str, src->m_windowName.length, + &target->m_windowName, copy); + target->m_dwStyle = src->m_dwStyle; + target->m_x = src->m_x; + target->m_y = src->m_y; + target->m_nWidth = src->m_nWidth; + target->m_nHeight = src->m_nHeight; + target->m_hWndParent = src->m_hWndParent; + target->m_hMenu = src->m_hMenu; + target->m_bWindowRenderingDisabled = src->m_bWindowRenderingDisabled; + target->m_bTransparentPainting = src->m_bTransparentPainting; + target->m_hWnd = src->m_hWnd; + } +}; + +/// +// 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) {} + + void SetAsChild(HWND hWndParent, RECT windowRect) { + m_dwStyle = WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_TABSTOP | + WS_VISIBLE; + m_hWndParent = hWndParent; + m_x = windowRect.left; + m_y = windowRect.top; + m_nWidth = windowRect.right - windowRect.left; + m_nHeight = windowRect.bottom - windowRect.top; + } + + void SetAsPopup(HWND hWndParent, const CefString& windowName) { + m_dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | + WS_VISIBLE; + m_hWndParent = hWndParent; + m_x = CW_USEDEFAULT; + m_y = CW_USEDEFAULT; + m_nWidth = CW_USEDEFAULT; + m_nHeight = CW_USEDEFAULT; + + cef_string_copy(windowName.c_str(), windowName.length(), &m_windowName); + } + + void SetAsOffScreen(HWND hWndParent) { + m_bWindowRenderingDisabled = TRUE; + m_hWndParent = hWndParent; + } + + void SetTransparentPainting(BOOL transparentPainting) { + m_bTransparentPainting = transparentPainting; + } +}; + + +struct CefPrintInfoTraits { + typedef cef_print_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->m_hDC = src->m_hDC; + target->m_Rect = src->m_Rect; + target->m_Scale = src->m_Scale; + } +}; + +/// +// Class representing print context information. +/// +typedef CefStructBase CefPrintInfo; + + +struct CefKeyInfoTraits { + typedef cef_key_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->key = src->key; + target->sysChar = src->sysChar; + target->imeChar = src->imeChar; + } +}; + +/// +// Class representing key information. +/// +typedef CefStructBase CefKeyInfo; + +#endif // OS_WIN + +#endif // CEF_INCLUDE_INTERNAL_CEF_WIN_H_ diff --git a/cef1/include/wrapper/cef_byte_read_handler.h b/cef1/include/wrapper/cef_byte_read_handler.h new file mode 100644 index 000000000..f7ca7a15a --- /dev/null +++ b/cef1/include/wrapper/cef_byte_read_handler.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. +// +// --------------------------------------------------------------------------- +// +// 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/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); + + /// + // Read raw binary data. + /// + virtual size_t Read(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. + /// + virtual int Seek(int64 offset, int whence); + + /// + // Return the current offset position. + /// + virtual int64 Tell(); + + /// + // Return non-zero if at end of file. + /// + virtual int Eof(); + + private: + const unsigned char* bytes_; + int64 size_; + int64 offset_; + CefRefPtr source_; + + IMPLEMENT_REFCOUNTING(CefByteReadHandler); + IMPLEMENT_LOCKING(CefByteReadHandler); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_BYTE_READ_HANDLER_H_ diff --git a/cef1/include/wrapper/cef_xml_object.h b/cef1/include/wrapper/cef_xml_object.h new file mode 100644 index 000000000..d9f706fde --- /dev/null +++ b/cef1/include/wrapper/cef_xml_object.h @@ -0,0 +1,188 @@ +// 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/cef_base.h" +#include "include/cef_xml_reader.h" +#include +#include + +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 CefBase { + 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); + virtual ~CefXmlObject(); + + /// + // 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: + void SetParent(CefXmlObject* parent); + + CefString name_; + CefXmlObject* parent_; + CefString value_; + AttributeMap attributes_; + ObjectVector children_; + + IMPLEMENT_REFCOUNTING(CefXmlObject); + IMPLEMENT_LOCKING(CefXmlObject); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_XML_OBJECT_H_ diff --git a/cef1/include/wrapper/cef_zip_archive.h b/cef1/include/wrapper/cef_zip_archive.h new file mode 100644 index 000000000..b58dbca01 --- /dev/null +++ b/cef1/include/wrapper/cef_zip_archive.h @@ -0,0 +1,132 @@ +// 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/cef_base.h" +#include + +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) Password-protected files are not supported. +// (2) All file names are stored and compared in lower case. +// (3) 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 CefBase { + 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() =0; + + /// + // Returns the size of the data in the file. + /// + virtual size_t GetDataSize() =0; + + /// + // Returns a CefStreamReader object for streaming the contents of the file. + /// + virtual CefRefPtr GetStreamReader() =0; + }; + typedef std::map > FileMap; + + /// + // Create a new object. + /// + CefZipArchive(); + virtual ~CefZipArchive(); + + /// + // Load the contents of the specified zip archive stream into this object. + // 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, bool overwriteExisting); + + /// + // Clears the contents of this object. + /// + void Clear(); + + /// + // Returns the number of files in the archive. + /// + size_t GetFileCount(); + + /// + // Returns true if the specified file exists and has contents. + /// + bool HasFile(const CefString& fileName); + + /// + // Returns the specified file. + /// + CefRefPtr GetFile(const CefString& fileName); + + /// + // Removes the specified file. + /// + bool RemoveFile(const CefString& fileName); + + /// + // Returns the map of all files. + /// + size_t GetFiles(FileMap& map); + + private: + FileMap contents_; + + IMPLEMENT_REFCOUNTING(CefZipArchive); + IMPLEMENT_LOCKING(CefZipArchive); +}; + +#endif // CEF_INCLUDE_WRAPPER_CEF_ZIP_ARCHIVE_H_ diff --git a/cef1/libcef/browser_appcache_system.cc b/cef1/libcef/browser_appcache_system.cc new file mode 100644 index 000000000..5d39cf6d0 --- /dev/null +++ b/cef1/libcef/browser_appcache_system.cc @@ -0,0 +1,460 @@ +// 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_appcache_system.h" +#include "libcef/browser_resource_loader_bridge.h" + +#include +#include + +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/callback.h" +#include "base/synchronization/waitable_event.h" +#include "webkit/appcache/appcache_interceptor.h" +#include "webkit/appcache/web_application_cache_host_impl.h" + +using WebKit::WebApplicationCacheHost; +using WebKit::WebApplicationCacheHostClient; +using appcache::WebApplicationCacheHostImpl; +using appcache::AppCacheBackendImpl; +using appcache::AppCacheInterceptor; + +// BrowserFrontendProxy -------------------------------------------------------- +// Proxies method calls from the backend IO thread to the frontend UI thread. + +class BrowserFrontendProxy + : public base::RefCountedThreadSafe, + public appcache::AppCacheFrontend { + public: + explicit BrowserFrontendProxy(BrowserAppCacheSystem* appcache_system) + : system_(appcache_system) { + } + + void clear_appcache_system() { system_ = NULL; } + + virtual void OnCacheSelected(int host_id, + const appcache::AppCacheInfo& info) { + if (!system_) + return; + if (system_->is_io_thread()) { + system_->ui_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserFrontendProxy::OnCacheSelected, this, host_id, + info)); + } else if (system_->is_ui_thread()) { + system_->frontend_impl_.OnCacheSelected(host_id, info); + } else { + NOTREACHED(); + } + } + + virtual void OnStatusChanged(const std::vector& host_ids, + appcache::Status status) { + if (!system_) + return; + if (system_->is_io_thread()) + system_->ui_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserFrontendProxy::OnStatusChanged, this, host_ids, + status)); + else if (system_->is_ui_thread()) + system_->frontend_impl_.OnStatusChanged(host_ids, status); + else + NOTREACHED(); + } + + virtual void OnEventRaised(const std::vector& host_ids, + appcache::EventID event_id) { + if (!system_) + return; + if (system_->is_io_thread()) + system_->ui_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserFrontendProxy::OnEventRaised, this, host_ids, + event_id)); + else if (system_->is_ui_thread()) + system_->frontend_impl_.OnEventRaised(host_ids, event_id); + else + NOTREACHED(); + } + + virtual void OnProgressEventRaised(const std::vector& host_ids, + const GURL& url, + int num_total, int num_complete) { + if (!system_) + return; + if (system_->is_io_thread()) + system_->ui_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserFrontendProxy::OnProgressEventRaised, this, + host_ids, url, num_total, num_complete)); + else if (system_->is_ui_thread()) + system_->frontend_impl_.OnProgressEventRaised( + host_ids, url, num_total, num_complete); + else + NOTREACHED(); + } + + virtual void OnErrorEventRaised(const std::vector& host_ids, + const std::string& message) { + if (!system_) + return; + if (system_->is_io_thread()) + system_->ui_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserFrontendProxy::OnErrorEventRaised, this, host_ids, + message)); + else if (system_->is_ui_thread()) + system_->frontend_impl_.OnErrorEventRaised( + host_ids, message); + else + NOTREACHED(); + } + + virtual void OnLogMessage(int host_id, + appcache::LogLevel log_level, + const std::string& message) { + if (!system_) + return; + if (system_->is_io_thread()) + system_->ui_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserFrontendProxy::OnLogMessage, this, host_id, + log_level, message)); + else if (system_->is_ui_thread()) + system_->frontend_impl_.OnLogMessage( + host_id, log_level, message); + else + NOTREACHED(); + } + + virtual void OnContentBlocked(int host_id, const GURL& manifest_url) {} + + private: + friend class base::RefCountedThreadSafe; + + ~BrowserFrontendProxy() {} + + BrowserAppCacheSystem* system_; +}; + + +// BrowserBackendProxy -------------------------------------------------------- +// Proxies method calls from the frontend UI thread to the backend IO thread. + +class BrowserBackendProxy + : public base::RefCountedThreadSafe, + public appcache::AppCacheBackend { + public: + explicit BrowserBackendProxy(BrowserAppCacheSystem* appcache_system) + : system_(appcache_system), event_(true, false) { + get_status_callback_ = + base::Bind(&BrowserBackendProxy::GetStatusCallback, + base::Unretained(this)); + start_update_callback_ = + base::Bind(&BrowserBackendProxy::StartUpdateCallback, + base::Unretained(this)); + swap_cache_callback_= + base::Bind(&BrowserBackendProxy::SwapCacheCallback, + base::Unretained(this)); + } + + virtual void RegisterHost(int host_id) { + if (system_->is_ui_thread()) { + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserBackendProxy::RegisterHost, this, host_id)); + } else if (system_->is_io_thread()) { + system_->backend_impl_->RegisterHost(host_id); + } else { + NOTREACHED(); + } + } + + virtual void UnregisterHost(int host_id) { + if (system_->is_ui_thread()) { + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserBackendProxy::UnregisterHost, this, host_id)); + } else if (system_->is_io_thread()) { + system_->backend_impl_->UnregisterHost(host_id); + } else { + NOTREACHED(); + } + } + + virtual void SetSpawningHostId(int host_id, int spawning_host_id) { + if (system_->is_ui_thread()) { + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserBackendProxy::SetSpawningHostId, this, host_id, + spawning_host_id)); + } else if (system_->is_io_thread()) { + system_->backend_impl_->SetSpawningHostId(host_id, spawning_host_id); + } else { + NOTREACHED(); + } + } + + virtual void SelectCache(int host_id, + const GURL& document_url, + const int64 cache_document_was_loaded_from, + const GURL& manifest_url) { + if (system_->is_ui_thread()) { + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserBackendProxy::SelectCache, this, host_id, + document_url, cache_document_was_loaded_from, + manifest_url)); + } else if (system_->is_io_thread()) { + system_->backend_impl_->SelectCache(host_id, document_url, + cache_document_was_loaded_from, + manifest_url); + } else { + NOTREACHED(); + } + } + + virtual void GetResourceList( + int host_id, + std::vector* resource_infos) { + if (system_->is_ui_thread()) { + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserBackendProxy::GetResourceList, this, host_id, + resource_infos)); + } else if (system_->is_io_thread()) { + system_->backend_impl_->GetResourceList(host_id, resource_infos); + } else { + NOTREACHED(); + } + } + + virtual void SelectCacheForWorker( + int host_id, + int parent_process_id, + int parent_host_id) { + NOTIMPLEMENTED(); // Workers are not supported in test_shell. + } + + virtual void SelectCacheForSharedWorker( + int host_id, + int64 appcache_id) { + NOTIMPLEMENTED(); // Workers are not supported in test_shell. + } + + virtual void MarkAsForeignEntry(int host_id, const GURL& document_url, + int64 cache_document_was_loaded_from) { + if (system_->is_ui_thread()) { + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserBackendProxy::MarkAsForeignEntry, this, host_id, + document_url, cache_document_was_loaded_from)); + } else if (system_->is_io_thread()) { + system_->backend_impl_->MarkAsForeignEntry( + host_id, document_url, + cache_document_was_loaded_from); + } else { + NOTREACHED(); + } + } + + virtual appcache::Status GetStatus(int host_id) { + if (system_->is_ui_thread()) { + status_result_ = appcache::UNCACHED; + event_.Reset(); + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(base::IgnoreResult(&BrowserBackendProxy::GetStatus), + this, host_id)); + event_.Wait(); + } else if (system_->is_io_thread()) { + system_->backend_impl_->GetStatusWithCallback( + host_id, get_status_callback_, NULL); + } else { + NOTREACHED(); + } + return status_result_; + } + + virtual bool StartUpdate(int host_id) { + if (system_->is_ui_thread()) { + bool_result_ = false; + event_.Reset(); + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(base::IgnoreResult(&BrowserBackendProxy::StartUpdate), + this, host_id)); + event_.Wait(); + } else if (system_->is_io_thread()) { + system_->backend_impl_->StartUpdateWithCallback( + host_id, start_update_callback_, NULL); + } else { + NOTREACHED(); + } + return bool_result_; + } + + virtual bool SwapCache(int host_id) { + if (system_->is_ui_thread()) { + bool_result_ = false; + event_.Reset(); + system_->io_message_loop()->PostTask( + FROM_HERE, + base::Bind(base::IgnoreResult(&BrowserBackendProxy::SwapCache), + this, host_id)); + event_.Wait(); + } else if (system_->is_io_thread()) { + system_->backend_impl_->SwapCacheWithCallback( + host_id, swap_cache_callback_, NULL); + } else { + NOTREACHED(); + } + return bool_result_; + } + + void GetStatusCallback(appcache::Status status, void* param) { + status_result_ = status; + event_.Signal(); + } + + void StartUpdateCallback(bool result, void* param) { + bool_result_ = result; + event_.Signal(); + } + + void SwapCacheCallback(bool result, void* param) { + bool_result_ = result; + event_.Signal(); + } + + void SignalEvent() { + event_.Signal(); + } + + private: + friend class base::RefCountedThreadSafe; + + ~BrowserBackendProxy() {} + + BrowserAppCacheSystem* system_; + base::WaitableEvent event_; + bool bool_result_; + appcache::Status status_result_; + appcache::GetStatusCallback get_status_callback_; + appcache::StartUpdateCallback start_update_callback_; + appcache::SwapCacheCallback swap_cache_callback_; +}; + + +// BrowserAppCacheSystem ------------------------------------------------------- + +// This class only works for a single process browser. +static const int kSingleProcessId = 1; + +// A not so thread safe singleton, but should work for test_shell. +BrowserAppCacheSystem* BrowserAppCacheSystem::instance_ = NULL; + +BrowserAppCacheSystem::BrowserAppCacheSystem() + : io_message_loop_(NULL), ui_message_loop_(NULL), + ALLOW_THIS_IN_INITIALIZER_LIST( + backend_proxy_(new BrowserBackendProxy(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + frontend_proxy_(new BrowserFrontendProxy(this))), + backend_impl_(NULL), service_(NULL), db_thread_("AppCacheDBThread") { + DCHECK(!instance_); + instance_ = this; +} + +static void SignalEvent(base::WaitableEvent* event) { + event->Signal(); +} + +BrowserAppCacheSystem::~BrowserAppCacheSystem() { + DCHECK(!io_message_loop_ && !backend_impl_ && !service_); + frontend_proxy_->clear_appcache_system(); // in case a task is in transit + instance_ = NULL; + + if (db_thread_.IsRunning()) { + // We pump a task thru the db thread to ensure any tasks previously + // scheduled on that thread have been performed prior to return. + base::WaitableEvent event(false, false); + db_thread_.message_loop()->PostTask( + FROM_HERE, base::Bind(&SignalEvent, &event)); + event.Wait(); + } +} + +void BrowserAppCacheSystem::InitOnUIThread(const FilePath& cache_directory) { + DCHECK(!ui_message_loop_); + ui_message_loop_ = MessageLoop::current(); + cache_directory_ = cache_directory; +} + +void BrowserAppCacheSystem::InitOnIOThread( + net::URLRequestContext* request_context) { + if (!is_initailized_on_ui_thread()) + return; + + DCHECK(!io_message_loop_); + io_message_loop_ = MessageLoop::current(); + + if (!db_thread_.IsRunning()) + db_thread_.Start(); + + // Recreate and initialize per each IO thread. + service_ = new appcache::AppCacheService(NULL); + backend_impl_ = new appcache::AppCacheBackendImpl(); + service_->Initialize(cache_directory_, + db_thread_.message_loop_proxy(), + BrowserResourceLoaderBridge::GetCacheThread()); + service_->set_request_context(request_context); + backend_impl_->Initialize(service_, frontend_proxy_.get(), kSingleProcessId); + + AppCacheInterceptor::EnsureRegistered(); +} + +void BrowserAppCacheSystem::CleanupIOThread() { + DCHECK(is_io_thread()); + + delete backend_impl_; + delete service_; + backend_impl_ = NULL; + service_ = NULL; + io_message_loop_ = NULL; + + // Just in case the main thread is waiting on it. + backend_proxy_->SignalEvent(); +} + +WebApplicationCacheHost* BrowserAppCacheSystem::CreateCacheHostForWebKit( + WebApplicationCacheHostClient* client) { + if (!is_initailized_on_ui_thread()) + return NULL; + + DCHECK(is_ui_thread()); + + if (!is_initialized()) + return NULL; + return new WebApplicationCacheHostImpl(client, backend_proxy_.get()); +} + +void BrowserAppCacheSystem::SetExtraRequestBits( + net::URLRequest* request, int host_id, ResourceType::Type resource_type) { + if (is_initialized()) { + DCHECK(is_io_thread()); + AppCacheInterceptor::SetExtraRequestInfo( + request, service_, kSingleProcessId, host_id, resource_type); + } +} + +void BrowserAppCacheSystem::GetExtraResponseBits( + net::URLRequest* request, int64* cache_id, GURL* manifest_url) { + if (is_initialized()) { + DCHECK(is_io_thread()); + AppCacheInterceptor::GetExtraResponseInfo( + request, cache_id, manifest_url); + } +} diff --git a/cef1/libcef/browser_appcache_system.h b/cef1/libcef/browser_appcache_system.h new file mode 100644 index 000000000..cf2cbac04 --- /dev/null +++ b/cef1/libcef/browser_appcache_system.h @@ -0,0 +1,133 @@ +// 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_APPCACHE_SYSTEM_H_ +#define CEF_LIBCEF_BROWSER_APPCACHE_SYSTEM_H_ +#pragma once + +#include "base/file_path.h" +#include "base/message_loop.h" +#include "base/threading/thread.h" +#include "webkit/appcache/appcache_backend_impl.h" +#include "webkit/appcache/appcache_frontend_impl.h" +#include "webkit/appcache/appcache_service.h" +#include "webkit/glue/resource_type.h" + +namespace WebKit { +class WebApplicationCacheHost; +class WebApplicationCacheHostClient; +} +class BrowserBackendProxy; +class BrowserFrontendProxy; + +namespace net { +class URLRequest; +class URLRequestContext; +} // namespace net + +// A class that composes the constituent parts of an appcache system +// together for use in a single process with two relavant threads, +// a UI thread on which webkit runs and an IO thread on which URLRequests +// are handled. This class conspires with BrowserResourceLoaderBridge to +// retrieve resources from the appcache. +class BrowserAppCacheSystem { + public: + // Should be instanced somewhere in main(). If not instanced, the public + // static methods are all safe no-ops. + BrowserAppCacheSystem(); + virtual ~BrowserAppCacheSystem(); + + // One-time main UI thread initialization. + static void InitializeOnUIThread(const FilePath& cache_directory) { + if (instance_) + instance_->InitOnUIThread(cache_directory); + } + + // Called by BrowserResourceLoaderBridge's IOThread class. + // Per IO thread initialization. Only one IO thread can exist + // at a time, but after IO thread termination a new one can be + // started on which this method should be called. The instance + // is assumed to outlive the IO thread. + static void InitializeOnIOThread(net::URLRequestContext* request_context) { + if (instance_) + instance_->InitOnIOThread(request_context); + } + + static void CleanupOnIOThread() { + if (instance_) + instance_->CleanupIOThread(); + } + + // Called by TestShellWebKitInit to manufacture a 'host' for webcore. + static WebKit::WebApplicationCacheHost* CreateApplicationCacheHost( + WebKit::WebApplicationCacheHostClient* client) { + return instance_ ? instance_->CreateCacheHostForWebKit(client) : NULL; + } + + // Called by BrowserResourceLoaderBridge to hook into resource loads. + static void SetExtraRequestInfo(net::URLRequest* request, + int host_id, + ResourceType::Type resource_type) { + if (instance_) + instance_->SetExtraRequestBits(request, host_id, resource_type); + } + + // Called by BrowserResourceLoaderBridge extract extra response bits. + static void GetExtraResponseInfo(net::URLRequest* request, + int64* cache_id, + GURL* manifest_url) { + if (instance_) + instance_->GetExtraResponseBits(request, cache_id, manifest_url); + } + + private: + friend class BrowserBackendProxy; + friend class BrowserFrontendProxy; + + // Instance methods called by our static public methods + void InitOnUIThread(const FilePath& cache_directory); + void InitOnIOThread(net::URLRequestContext* request_context); + void CleanupIOThread(); + WebKit::WebApplicationCacheHost* CreateCacheHostForWebKit( + WebKit::WebApplicationCacheHostClient* client); + void SetExtraRequestBits(net::URLRequest* request, + int host_id, + ResourceType::Type resource_type); + void GetExtraResponseBits(net::URLRequest* request, + int64* cache_id, + GURL* manifest_url); + + // Helpers + MessageLoop* io_message_loop() { return io_message_loop_; } + MessageLoop* ui_message_loop() { return ui_message_loop_; } + bool is_io_thread() { return MessageLoop::current() == io_message_loop_; } + bool is_ui_thread() { return MessageLoop::current() == ui_message_loop_; } + bool is_initialized() { + return io_message_loop_ && is_initailized_on_ui_thread(); + } + bool is_initailized_on_ui_thread() { + return ui_message_loop_ ? true : false; + } + + FilePath cache_directory_; + MessageLoop* io_message_loop_; + MessageLoop* ui_message_loop_; + scoped_refptr backend_proxy_; + scoped_refptr frontend_proxy_; + appcache::AppCacheFrontendImpl frontend_impl_; + + // Created and used only on the IO thread, these do + // not survive IO thread termination. If a new IO thread + // is started new instances will be created. + appcache::AppCacheBackendImpl* backend_impl_; + appcache::AppCacheService* service_; + + // We start a thread for use as the DB thread. + base::Thread db_thread_; + + // A low-tech singleton. + static BrowserAppCacheSystem* instance_; +}; + +#endif // CEF_LIBCEF_BROWSER_APPCACHE_SYSTEM_H_ diff --git a/cef1/libcef/browser_database_system.cc b/cef1/libcef/browser_database_system.cc new file mode 100644 index 000000000..634627a3c --- /dev/null +++ b/cef1/libcef/browser_database_system.cc @@ -0,0 +1,313 @@ +// 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_database_system.h" + +#include "base/auto_reset.h" +#include "base/bind.h" +#include "base/bind_helpers.h" +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" +#include "base/synchronization/waitable_event.h" +#include "base/threading/platform_thread.h" +#include "base/utf_string_conversions.h" +#include "third_party/sqlite/sqlite3.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDatabase.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "webkit/database/database_util.h" +#include "webkit/database/vfs_backend.h" + +using webkit_database::DatabaseTracker; +using webkit_database::DatabaseUtil; +using webkit_database::OriginInfo; +using webkit_database::VfsBackend; + +BrowserDatabaseSystem* BrowserDatabaseSystem::instance_ = NULL; + +BrowserDatabaseSystem* BrowserDatabaseSystem::GetInstance() { + DCHECK(instance_); + return instance_; +} + +BrowserDatabaseSystem::BrowserDatabaseSystem() + : db_thread_("BrowserDBThread"), + quota_per_origin_(5 * 1024 * 1024), + open_connections_(new webkit_database::DatabaseConnectionsWrapper) { + DCHECK(!instance_); + instance_ = this; + CHECK(temp_dir_.CreateUniqueTempDir()); + db_tracker_ = + new DatabaseTracker(temp_dir_.path(), false, NULL, NULL, NULL); + db_tracker_->AddObserver(this); + db_thread_.Start(); + db_thread_proxy_ = db_thread_.message_loop_proxy(); +} + +BrowserDatabaseSystem::~BrowserDatabaseSystem() { + base::WaitableEvent done_event(false, false); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::ThreadCleanup, + base::Unretained(this), &done_event)); + done_event.Wait(); + instance_ = NULL; +} + +void BrowserDatabaseSystem::databaseOpened( + const WebKit::WebDatabase& database) { + string16 origin_identifier = database.securityOrigin().databaseIdentifier(); + string16 database_name = database.name(); + open_connections_->AddOpenConnection(origin_identifier, database_name); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::DatabaseOpened, + base::Unretained(this), + origin_identifier, + database_name, database.displayName(), + database.estimatedSize())); +} + +void BrowserDatabaseSystem::databaseModified( + const WebKit::WebDatabase& database) { + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::DatabaseModified, + base::Unretained(this), + database.securityOrigin().databaseIdentifier(), + database.name())); +} + +void BrowserDatabaseSystem::databaseClosed( + const WebKit::WebDatabase& database) { + string16 origin_identifier = database.securityOrigin().databaseIdentifier(); + string16 database_name = database.name(); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::DatabaseClosed, + base::Unretained(this), origin_identifier, database_name)); +} + +base::PlatformFile BrowserDatabaseSystem::OpenFile( + const string16& vfs_file_name, int desired_flags) { + base::PlatformFile result = base::kInvalidPlatformFileValue; + base::WaitableEvent done_event(false, false); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::VfsOpenFile, + base::Unretained(this), + vfs_file_name, desired_flags, + &result, &done_event)); + done_event.Wait(); + return result; +} + +int BrowserDatabaseSystem::DeleteFile( + const string16& vfs_file_name, bool sync_dir) { + int result = SQLITE_OK; + base::WaitableEvent done_event(false, false); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::VfsDeleteFile, + base::Unretained(this), + vfs_file_name, sync_dir, + &result, &done_event)); + done_event.Wait(); + return result; +} + +uint32 BrowserDatabaseSystem::GetFileAttributes(const string16& vfs_file_name) { + uint32 result = 0; + base::WaitableEvent done_event(false, false); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::VfsGetFileAttributes, + base::Unretained(this), vfs_file_name, &result, &done_event)); + done_event.Wait(); + return result; +} + +int64 BrowserDatabaseSystem::GetFileSize(const string16& vfs_file_name) { + int64 result = 0; + base::WaitableEvent done_event(false, false); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::VfsGetFileSize, + base::Unretained(this), vfs_file_name, &result, &done_event)); + done_event.Wait(); + return result; +} + +int64 BrowserDatabaseSystem::GetSpaceAvailable( + const string16& origin_identifier) { + int64 result = 0; + base::WaitableEvent done_event(false, false); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::VfsGetSpaceAvailable, + base::Unretained(this), origin_identifier, + &result, &done_event)); + done_event.Wait(); + return result; +} + +void BrowserDatabaseSystem::ClearAllDatabases() { + open_connections_->WaitForAllDatabasesToClose(); + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::ResetTracker, base::Unretained(this))); +} + +void BrowserDatabaseSystem::SetDatabaseQuota(int64 quota) { + if (!db_thread_proxy_->BelongsToCurrentThread()) { + db_thread_proxy_->PostTask( + FROM_HERE, + base::Bind(&BrowserDatabaseSystem::SetDatabaseQuota, + base::Unretained(this), quota)); + return; + } + quota_per_origin_ = quota; +} + +void BrowserDatabaseSystem::DatabaseOpened(const string16& origin_identifier, + const string16& database_name, + const string16& description, + int64 estimated_size) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + int64 database_size = 0; + db_tracker_->DatabaseOpened( + origin_identifier, database_name, description, + estimated_size, &database_size); + OnDatabaseSizeChanged(origin_identifier, database_name, + database_size); +} + +void BrowserDatabaseSystem::DatabaseModified(const string16& origin_identifier, + const string16& database_name) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + db_tracker_->DatabaseModified(origin_identifier, database_name); +} + +void BrowserDatabaseSystem::DatabaseClosed(const string16& origin_identifier, + const string16& database_name) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + db_tracker_->DatabaseClosed(origin_identifier, database_name); + open_connections_->RemoveOpenConnection(origin_identifier, database_name); +} + +void BrowserDatabaseSystem::OnDatabaseSizeChanged( + const string16& origin_identifier, + const string16& database_name, + int64 database_size) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + // We intentionally call into webkit on our background db_thread_ + // to better emulate what happens in chrome where this method is + // invoked on the background ipc thread. + WebKit::WebDatabase::updateDatabaseSize( + origin_identifier, database_name, database_size); +} + +void BrowserDatabaseSystem::OnDatabaseScheduledForDeletion( + const string16& origin_identifier, + const string16& database_name) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + // We intentionally call into webkit on our background db_thread_ + // to better emulate what happens in chrome where this method is + // invoked on the background ipc thread. + WebKit::WebDatabase::closeDatabaseImmediately( + origin_identifier, database_name); +} + +void BrowserDatabaseSystem::VfsOpenFile( + const string16& vfs_file_name, int desired_flags, + base::PlatformFile* file_handle, base::WaitableEvent* done_event ) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + FilePath file_name = GetFullFilePathForVfsFile(vfs_file_name); + if (file_name.empty()) { + VfsBackend::OpenTempFileInDirectory( + db_tracker_->DatabaseDirectory(), desired_flags, file_handle); + } else { + VfsBackend::OpenFile(file_name, desired_flags, file_handle); + } + done_event->Signal(); +} + +void BrowserDatabaseSystem::VfsDeleteFile( + const string16& vfs_file_name, bool sync_dir, + int* result, base::WaitableEvent* done_event) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + // We try to delete the file multiple times, because that's what the default + // VFS does (apparently deleting a file can sometimes fail on Windows). + // We sleep for 10ms between retries for the same reason. + const int kNumDeleteRetries = 3; + int num_retries = 0; + *result = SQLITE_OK; + FilePath file_name = GetFullFilePathForVfsFile(vfs_file_name); + do { + *result = VfsBackend::DeleteFile(file_name, sync_dir); + } while ((++num_retries < kNumDeleteRetries) && + (*result == SQLITE_IOERR_DELETE) && + (base::PlatformThread::Sleep( + base::TimeDelta::FromMilliseconds(10)), + 1)); + + done_event->Signal(); +} + +void BrowserDatabaseSystem::VfsGetFileAttributes( + const string16& vfs_file_name, + uint32* result, base::WaitableEvent* done_event) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + *result = VfsBackend::GetFileAttributes( + GetFullFilePathForVfsFile(vfs_file_name)); + done_event->Signal(); +} + +void BrowserDatabaseSystem::VfsGetFileSize( + const string16& vfs_file_name, + int64* result, base::WaitableEvent* done_event) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + *result = VfsBackend::GetFileSize(GetFullFilePathForVfsFile(vfs_file_name)); + done_event->Signal(); +} + +void BrowserDatabaseSystem::VfsGetSpaceAvailable( + const string16& origin_identifier, + int64* result, base::WaitableEvent* done_event) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + // This method isn't actually part of the "vfs" interface, but it is + // used from within webcore and handled here in the same fashion. + OriginInfo info; + if (db_tracker_->GetOriginInfo(origin_identifier, &info)) { + int64 space_available = quota_per_origin_ - info.TotalSize(); + *result = space_available < 0 ? 0 : space_available; + } else { + NOTREACHED(); + *result = 0; + } + done_event->Signal(); +} + +FilePath BrowserDatabaseSystem::GetFullFilePathForVfsFile( + const string16& vfs_file_name) { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + if (vfs_file_name.empty()) // temp file, used for vacuuming + return FilePath(); + return DatabaseUtil::GetFullFilePathForVfsFile( + db_tracker_.get(), vfs_file_name); +} + +void BrowserDatabaseSystem::ResetTracker() { + DCHECK(db_thread_proxy_->BelongsToCurrentThread()); + db_tracker_->CloseTrackerDatabaseAndClearCaches(); + file_util::Delete(db_tracker_->DatabaseDirectory(), true); +} + +void BrowserDatabaseSystem::ThreadCleanup(base::WaitableEvent* done_event) { + ResetTracker(); + db_tracker_->RemoveObserver(this); + db_tracker_ = NULL; + done_event->Signal(); +} + diff --git a/cef1/libcef/browser_database_system.h b/cef1/libcef/browser_database_system.h new file mode 100644 index 000000000..c2af46f69 --- /dev/null +++ b/cef1/libcef/browser_database_system.h @@ -0,0 +1,105 @@ +// 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_DATABASE_SYSTEM_H_ +#define CEF_LIBCEF_BROWSER_DATABASE_SYSTEM_H_ +#pragma once + +#include "base/file_path.h" +#include "base/hash_tables.h" +#include "base/memory/ref_counted.h" +#include "base/platform_file.h" +#include "base/scoped_temp_dir.h" +#include "base/string16.h" +#include "base/synchronization/lock.h" +#include "base/threading/thread.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDatabaseObserver.h" +#include "webkit/database/database_connections.h" +#include "webkit/database/database_tracker.h" + +namespace base { +class MessageLoopProxy; +class WaitableEvent; +} + +class BrowserDatabaseSystem : public webkit_database::DatabaseTracker::Observer, + public WebKit::WebDatabaseObserver { + public: + static BrowserDatabaseSystem* GetInstance(); + + BrowserDatabaseSystem(); + virtual ~BrowserDatabaseSystem(); + + // WebDatabaseObserver implementation, these are called on the script + // execution context thread on which the database is opened. This may be + // the main thread or background WebWorker threads. + virtual void databaseOpened(const WebKit::WebDatabase& database); + virtual void databaseModified(const WebKit::WebDatabase& database); + virtual void databaseClosed(const WebKit::WebDatabase& database); + + // SQLite VFS related methods, these are called on webcore's + // background database threads via the WebKitPlatformSupport impl. + base::PlatformFile OpenFile(const string16& vfs_file_name, int desired_flags); + int DeleteFile(const string16& vfs_file_name, bool sync_dir); + uint32 GetFileAttributes(const string16& vfs_file_name); + int64 GetFileSize(const string16& vfs_file_name); + int64 GetSpaceAvailable(const string16& origin_identifier); + + // For use by LayoutTestController, called on the main thread. + void ClearAllDatabases(); + void SetDatabaseQuota(int64 quota); + + private: + // Used by our WebDatabaseObserver impl, only called on the db_thread + void DatabaseOpened(const string16& origin_identifier, + const string16& database_name, + const string16& description, + int64 estimated_size); + void DatabaseModified(const string16& origin_identifier, + const string16& database_name); + void DatabaseClosed(const string16& origin_identifier, + const string16& database_name); + + // DatabaseTracker::Observer implementation + virtual void OnDatabaseSizeChanged(const string16& origin_identifier, + const string16& database_name, + int64 database_size) OVERRIDE; + virtual void OnDatabaseScheduledForDeletion( + const string16& origin_identifier, + const string16& database_name) OVERRIDE; + + // Used by our public SQLite VFS methods, only called on the db_thread. + void VfsOpenFile(const string16& vfs_file_name, int desired_flags, + base::PlatformFile* result, base::WaitableEvent* done_event); + void VfsDeleteFile(const string16& vfs_file_name, bool sync_dir, + int* result, base::WaitableEvent* done_event); + void VfsGetFileAttributes(const string16& vfs_file_name, + uint32* result, base::WaitableEvent* done_event); + void VfsGetFileSize(const string16& vfs_file_name, + int64* result, base::WaitableEvent* done_event); + void VfsGetSpaceAvailable(const string16& origin_identifier, + int64* result, base::WaitableEvent* done_event); + + FilePath GetFullFilePathForVfsFile(const string16& vfs_file_name); + + void ResetTracker(); + void ThreadCleanup(base::WaitableEvent* done_event); + + // Where the tracker database file and per origin database files reside. + ScopedTempDir temp_dir_; + + // All access to the db_tracker (except for its construction) and + // vfs operations are serialized on a background thread. + base::Thread db_thread_; + scoped_refptr db_thread_proxy_; + scoped_refptr db_tracker_; + int64 quota_per_origin_; + + // Data members to support waiting for all connections to be closed. + scoped_refptr open_connections_; + + static BrowserDatabaseSystem* instance_; +}; + +#endif // CEF_LIBCEF_BROWSER_DATABASE_SYSTEM_H_ diff --git a/cef1/libcef/browser_devtools_agent.cc b/cef1/libcef/browser_devtools_agent.cc new file mode 100644 index 000000000..68a0c20e2 --- /dev/null +++ b/cef1/libcef/browser_devtools_agent.cc @@ -0,0 +1,126 @@ +// 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_devtools_agent.h" +#include "libcef/browser_devtools_callargs.h" +#include "libcef/browser_devtools_client.h" + +#include "base/bind.h" +#include "base/message_loop.h" +#include "grit/webkit_chromium_resources.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDevToolsAgent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webkit_glue.h" + +using WebKit::WebCString; +using WebKit::WebDevToolsAgent; +using WebKit::WebDevToolsMessageData; +using WebKit::WebString; +using WebKit::WebView; + +namespace { + +class WebKitClientMessageLoopImpl + : public WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop { + public: + WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { } + virtual ~WebKitClientMessageLoopImpl() { + message_loop_ = NULL; + } + virtual void run() { + bool old_state = message_loop_->NestableTasksAllowed(); + message_loop_->SetNestableTasksAllowed(true); + message_loop_->Run(); + message_loop_->SetNestableTasksAllowed(old_state); + } + virtual void quitNow() { + message_loop_->QuitNow(); + } + private: + MessageLoop* message_loop_; +}; + +} // namespace + +BrowserDevToolsAgent::BrowserDevToolsAgent() + : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), + dev_tools_client_(NULL) { + static int dev_tools_agent_counter; + routing_id_ = ++dev_tools_agent_counter; +} + +BrowserDevToolsAgent::~BrowserDevToolsAgent() { +} + +void BrowserDevToolsAgent::SetWebView(WebKit::WebView* web_view) { + web_view_ = web_view; +} + +void BrowserDevToolsAgent::sendMessageToInspectorFrontend( + const WebString& data) { + if (dev_tools_client_) + dev_tools_client_->AsyncCall(BrowserDevToolsCallArgs(data)); +} + +int BrowserDevToolsAgent::hostIdentifier() { + return routing_id_; +} + +void BrowserDevToolsAgent::runtimePropertyChanged( + const WebKit::WebString& name, + const WebKit::WebString& value) { + // TODO(cef): Implement. +} + +WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop* + BrowserDevToolsAgent::createClientMessageLoop() { + return new WebKitClientMessageLoopImpl(); +} + +void BrowserDevToolsAgent::AsyncCall(const BrowserDevToolsCallArgs &args) { + MessageLoop::current()->PostTask( + FROM_HERE, + base::Bind(&BrowserDevToolsAgent::Call, weak_factory_.GetWeakPtr(), + args)); +} + +void BrowserDevToolsAgent::Call(const BrowserDevToolsCallArgs &args) { + WebDevToolsAgent* web_agent = GetWebAgent(); + if (web_agent) + web_agent->dispatchOnInspectorBackend(args.data_); + if (BrowserDevToolsCallArgs::calls_count() == 1 && dev_tools_client_) + dev_tools_client_->all_messages_processed(); +} + +WebDevToolsAgent* BrowserDevToolsAgent::GetWebAgent() { + if (!web_view_) + return NULL; + return web_view_->devToolsAgent(); +} + +void BrowserDevToolsAgent::attach(BrowserDevToolsClient* client) { + DCHECK(!dev_tools_client_); + dev_tools_client_ = client; + WebDevToolsAgent* web_agent = GetWebAgent(); + if (web_agent) + web_agent->attach(); +} + +void BrowserDevToolsAgent::detach() { + DCHECK(dev_tools_client_); + WebDevToolsAgent* web_agent = GetWebAgent(); + if (web_agent) + web_agent->detach(); + dev_tools_client_ = NULL; +} + +bool BrowserDevToolsAgent::evaluateInWebInspector( + long call_id, // NOLINT(runtime/int) + const std::string& script) { + WebDevToolsAgent* agent = GetWebAgent(); + if (!agent) + return false; + agent->evaluateInWebInspector(call_id, WebString::fromUTF8(script)); + return true; +} diff --git a/cef1/libcef/browser_devtools_agent.h b/cef1/libcef/browser_devtools_agent.h new file mode 100644 index 000000000..efc6bb7e6 --- /dev/null +++ b/cef1/libcef/browser_devtools_agent.h @@ -0,0 +1,65 @@ +// 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_DEVTOOLS_AGENT_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_AGENT_H_ +#pragma once + +#include + +#include "base/memory/weak_ptr.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDevToolsAgentClient.h" + +namespace WebKit { + +class WebDevToolsAgent; +class WebView; + +} // namespace WebKit + +class BrowserDevToolsCallArgs; +class BrowserDevToolsClient; + +class BrowserDevToolsAgent : public WebKit::WebDevToolsAgentClient { + public: + BrowserDevToolsAgent(); + virtual ~BrowserDevToolsAgent(); + + void SetWebView(WebKit::WebView* web_view); + + // WebDevToolsAgentClient implementation. + virtual void sendMessageToInspectorFrontend( + const WebKit::WebString& data); + virtual int hostIdentifier(); + virtual void runtimePropertyChanged(const WebKit::WebString& name, + const WebKit::WebString& value); + + virtual WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop* + createClientMessageLoop(); + + void AsyncCall(const BrowserDevToolsCallArgs& args); + + void attach(BrowserDevToolsClient* client); + void detach(); + + bool evaluateInWebInspector(long call_id, // NOLINT(runtime/int) + const std::string& script); + + BrowserDevToolsClient* client() { return dev_tools_client_; } + + private: + void Call(const BrowserDevToolsCallArgs& args); + WebKit::WebDevToolsAgent* GetWebAgent(); + + base::WeakPtrFactory weak_factory_; + BrowserDevToolsClient* dev_tools_client_; + int routing_id_; + WebKit::WebDevToolsAgent* web_dev_tools_agent_; + WebKit::WebView* web_view_; + + DISALLOW_COPY_AND_ASSIGN(BrowserDevToolsAgent); +}; + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_AGENT_H_ diff --git a/cef1/libcef/browser_devtools_callargs.cc b/cef1/libcef/browser_devtools_callargs.cc new file mode 100644 index 000000000..efc8013f8 --- /dev/null +++ b/cef1/libcef/browser_devtools_callargs.cc @@ -0,0 +1,27 @@ +// 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 "libcef/browser_devtools_callargs.h" + +#include "base/logging.h" + +// static +int BrowserDevToolsCallArgs::calls_count_ = 0; + +BrowserDevToolsCallArgs::BrowserDevToolsCallArgs( + const WebKit::WebString& data) + : data_(data) { + ++calls_count_; +} + +BrowserDevToolsCallArgs::BrowserDevToolsCallArgs( + const BrowserDevToolsCallArgs& args) + : data_(args.data_) { + ++calls_count_; +} + +BrowserDevToolsCallArgs::~BrowserDevToolsCallArgs() { + --calls_count_; + DCHECK_GE(calls_count_, 0); +} diff --git a/cef1/libcef/browser_devtools_callargs.h b/cef1/libcef/browser_devtools_callargs.h new file mode 100644 index 000000000..b53de58df --- /dev/null +++ b/cef1/libcef/browser_devtools_callargs.h @@ -0,0 +1,29 @@ +// 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. + +#ifndef CEF_LIBCEF_BROWSER_DEVTOOLS_CALLARGS_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_CALLARGS_H_ +#pragma once + +#include "base/basictypes.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" + +class BrowserDevToolsCallArgs { + public: + explicit BrowserDevToolsCallArgs(const WebKit::WebString& data); + + BrowserDevToolsCallArgs(const BrowserDevToolsCallArgs& args); + + ~BrowserDevToolsCallArgs(); + + static int calls_count() { return calls_count_; } + + WebKit::WebString data_; + + private: + static int calls_count_; +}; + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_CALLARGS_H_ diff --git a/cef1/libcef/browser_devtools_client.cc b/cef1/libcef/browser_devtools_client.cc new file mode 100644 index 000000000..770df0312 --- /dev/null +++ b/cef1/libcef/browser_devtools_client.cc @@ -0,0 +1,87 @@ +// 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 "libcef/browser_devtools_client.h" +#include "libcef/browser_devtools_agent.h" +#include "libcef/browser_devtools_callargs.h" +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDevToolsAgent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDevToolsFrontend.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptSource.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/logging.h" +#include "base/message_loop.h" + +using WebKit::WebDevToolsAgent; +using WebKit::WebDevToolsFrontend; +using WebKit::WebDevToolsMessageData; +using WebKit::WebString; +using WebKit::WebView; + +BrowserDevToolsClient::BrowserDevToolsClient(CefBrowserImpl* browser, + BrowserDevToolsAgent* agent) + : ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), + browser_(browser), + dev_tools_agent_(agent), + web_view_(browser->UIT_GetWebView()) { + web_tools_frontend_.reset(WebDevToolsFrontend::create(web_view_, this, + WebString::fromUTF8(_Context->locale()))); + dev_tools_agent_->attach(this); +} + +BrowserDevToolsClient::~BrowserDevToolsClient() { + // It is a chance that page will be destroyed at detach step of + // dev_tools_agent_ and we should clean pending requests a bit earlier. + weak_factory_.InvalidateWeakPtrs(); + if (dev_tools_agent_) + dev_tools_agent_->detach(); +} + +void BrowserDevToolsClient::sendMessageToBackend( + const WebString& data) { + if (dev_tools_agent_) + dev_tools_agent_->AsyncCall(BrowserDevToolsCallArgs(data)); +} + +void BrowserDevToolsClient::activateWindow() { + NOTIMPLEMENTED(); +} + +void BrowserDevToolsClient::closeWindow() { + NOTIMPLEMENTED(); +} + +void BrowserDevToolsClient::dockWindow() { + NOTIMPLEMENTED(); +} + +void BrowserDevToolsClient::undockWindow() { + NOTIMPLEMENTED(); +} + +void BrowserDevToolsClient::AsyncCall(const BrowserDevToolsCallArgs &args) { + MessageLoop::current()->PostTask( + FROM_HERE, + base::Bind(&BrowserDevToolsClient::Call, weak_factory_.GetWeakPtr(), + args)); +} + +void BrowserDevToolsClient::Call(const BrowserDevToolsCallArgs &args) { + web_tools_frontend_->dispatchOnInspectorFrontend(args.data_); + if (BrowserDevToolsCallArgs::calls_count() == 1) + all_messages_processed(); +} + +void BrowserDevToolsClient::all_messages_processed() { + web_view_->mainFrame()->executeScript(WebKit::WebScriptSource( + WebString::fromUTF8("if (window.WebInspector && " + "WebInspector.queuesAreEmpty) WebInspector.queuesAreEmpty();"))); +} diff --git a/cef1/libcef/browser_devtools_client.h b/cef1/libcef/browser_devtools_client.h new file mode 100644 index 000000000..0e733da95 --- /dev/null +++ b/cef1/libcef/browser_devtools_client.h @@ -0,0 +1,55 @@ +// Copyright (c) 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_DEVTOOLS_CLIENT_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_CLIENT_H_ +#pragma once + +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDevToolsFrontendClient.h" + +namespace WebKit { +class WebDevToolsFrontend; +class WebView; +} // namespace WebKit + +class BrowserDevToolsCallArgs; +class BrowserDevToolsAgent; +class CefBrowserImpl; + +class BrowserDevToolsClient: public WebKit::WebDevToolsFrontendClient { + public: + BrowserDevToolsClient(CefBrowserImpl* browser, + BrowserDevToolsAgent* agent); + virtual ~BrowserDevToolsClient(); + + // WebDevToolsFrontendClient implementation + virtual void sendMessageToBackend(const WebKit::WebString& data); + + virtual void activateWindow(); + virtual void closeWindow(); + virtual void dockWindow(); + virtual void undockWindow(); + + void AsyncCall(const BrowserDevToolsCallArgs& args); + + void all_messages_processed(); + + CefBrowserImpl* browser() { return browser_; } + + private: + void Call(const BrowserDevToolsCallArgs& args); + + base::WeakPtrFactory weak_factory_; + CefBrowserImpl* browser_; + BrowserDevToolsAgent* dev_tools_agent_; + WebKit::WebView* web_view_; + scoped_ptr web_tools_frontend_; + + DISALLOW_COPY_AND_ASSIGN(BrowserDevToolsClient); +}; + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_CLIENT_H_ diff --git a/cef1/libcef/browser_devtools_scheme_handler.cc b/cef1/libcef/browser_devtools_scheme_handler.cc new file mode 100644 index 000000000..47645ed16 --- /dev/null +++ b/cef1/libcef/browser_devtools_scheme_handler.cc @@ -0,0 +1,133 @@ +// 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_devtools_scheme_handler.h" + +#include + +#include "include/cef_browser.h" +#include "include/cef_request.h" +#include "include/cef_response.h" +#include "include/cef_scheme.h" +#include "include/cef_stream.h" +#include "include/cef_url.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/cef_context.h" + +#include "base/file_util.h" +#include "base/string_util.h" +#include "grit/devtools_resources_map.h" +#include "net/base/mime_util.h" +#include "ui/base/resource/resource_bundle.h" + +const char kChromeDevToolsScheme[] = "chrome-devtools"; +const char kChromeDevToolsHost[] = "devtools"; +const char kChromeDevToolsURL[] = "chrome-devtools://devtools/"; + +namespace { + +class DevToolsSchemeHandler : public CefSchemeHandler { + public: + DevToolsSchemeHandler(const std::string& path, + CefRefPtr reader, + int size) + : path_(path), reader_(reader), size_(size) { + } + + virtual bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) + OVERRIDE { + callback->HeadersAvailable(); + return true; + } + + virtual void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) OVERRIDE { + response_length = size_; + + std::string mime_type = "text/plain"; + if (net::GetMimeTypeFromFile(FilePath(CefString(path_)), &mime_type)) + response->SetMimeType(mime_type); + + response->SetStatus(200); + } + + virtual 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); + } + + virtual void Cancel() OVERRIDE { + } + + private: + std::string path_; + CefRefPtr reader_; + int size_; + + IMPLEMENT_REFCOUNTING(DevToolSSchemeHandler); +}; + +class DevToolsSchemeHandlerFactory : public CefSchemeHandlerFactory { + public: + DevToolsSchemeHandlerFactory() {} + + virtual CefRefPtr Create(CefRefPtr browser, + const CefString& scheme_name, + CefRefPtr request) + OVERRIDE { + // Remove the query component of the URL, if any. + CefURLParts parts; + CefParseURL(request->GetURL(), parts); + cef_string_clear(&parts.spec); + cef_string_clear(&parts.query); + CefString urlStr; + CefCreateURL(parts, urlStr); + + std::string url = urlStr; + const char* path = &url.c_str()[strlen(kChromeDevToolsURL)]; + + int size = -1; + CefRefPtr reader = GetStreamReader(path, size); + if (!reader.get()) + return NULL; + + return new DevToolsSchemeHandler(path, reader, size); + } + + CefRefPtr GetStreamReader(const char* path, int& size) { + // Create a stream for the grit resource. + for (size_t i = 0; i < kDevtoolsResourcesSize; ++i) { + if (base::strcasecmp(kDevtoolsResources[i].name, path) == 0) { + base::StringPiece piece = + _Context->GetDataResource(kDevtoolsResources[i].value); + if (!piece.empty()) { + size = piece.size(); + return CefStreamReader::CreateForData(const_cast(piece.data()), + size); + } + } + } + + NOTREACHED() << "Missing DevTools resource: " << path; + return NULL; + } + + IMPLEMENT_REFCOUNTING(DevToolSSchemeHandlerFactory); +}; + +} // namespace + +// Register the DevTools scheme handler. +void RegisterDevToolsSchemeHandler(bool firstTime) { + if (firstTime) + CefRegisterCustomScheme(kChromeDevToolsScheme, true, false, true); + CefRegisterSchemeHandlerFactory(kChromeDevToolsScheme, kChromeDevToolsHost, + new DevToolsSchemeHandlerFactory()); +} diff --git a/cef1/libcef/browser_devtools_scheme_handler.h b/cef1/libcef/browser_devtools_scheme_handler.h new file mode 100644 index 000000000..e655b75c0 --- /dev/null +++ b/cef1/libcef/browser_devtools_scheme_handler.h @@ -0,0 +1,16 @@ +// 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_LIBCEF_BROWSER_DEVTOOLS_SCHEME_HANDLER_H_ +#define CEF_LIBCEF_BROWSER_DEVTOOLS_SCHEME_HANDLER_H_ +#pragma once + +extern const char kChromeDevToolsScheme[]; +extern const char kChromeDevToolsHost[]; +extern const char kChromeDevToolsURL[]; + +// Register the DevTools scheme handler. +void RegisterDevToolsSchemeHandler(bool firstTime); + +#endif // CEF_LIBCEF_BROWSER_DEVTOOLS_SCHEME_HANDLER_H_ diff --git a/cef1/libcef/browser_dom_storage_system.cc b/cef1/libcef/browser_dom_storage_system.cc new file mode 100644 index 000000000..06bd62e1c --- /dev/null +++ b/cef1/libcef/browser_dom_storage_system.cc @@ -0,0 +1,308 @@ +// 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_dom_storage_system.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" + +#include "base/auto_reset.h" +#include "base/path_service.h" +#include "googleurl/src/gurl.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebStorageArea.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebStorageEventDispatcher.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebStorageNamespace.h" +#include "webkit/database/database_util.h" +#include "webkit/dom_storage/dom_storage_area.h" +#include "webkit/dom_storage/dom_storage_host.h" +#include "webkit/dom_storage/dom_storage_task_runner.h" + +using dom_storage::DomStorageContext; +using dom_storage::DomStorageHost; +using dom_storage::DomStorageSession; +using dom_storage::DomStorageWorkerPoolTaskRunner; +using webkit_database::DatabaseUtil; +using WebKit::WebStorageArea; +using WebKit::WebStorageNamespace; +using WebKit::WebStorageEventDispatcher; +using WebKit::WebString; +using WebKit::WebURL; + +namespace { +const int kInvalidNamespaceId = -1; +} + +class BrowserDomStorageSystem::NamespaceImpl : public WebStorageNamespace { + public: + explicit NamespaceImpl(const base::WeakPtr& parent); + NamespaceImpl(const base::WeakPtr& parent, + int session_namespace_id); + virtual ~NamespaceImpl(); + virtual WebStorageArea* createStorageArea(const WebString& origin) OVERRIDE; + virtual WebStorageNamespace* copy() OVERRIDE; + virtual bool isSameNamespace(const WebStorageNamespace&) const OVERRIDE; + + private: + DomStorageContext* Context() { + if (!parent_.get()) + return NULL; + return parent_->context_.get(); + } + + base::WeakPtr parent_; + int namespace_id_; +}; + +class BrowserDomStorageSystem::AreaImpl : public WebStorageArea { + public: + AreaImpl(const base::WeakPtr& parent, + int namespace_id, const GURL& origin); + virtual ~AreaImpl(); + virtual unsigned length() OVERRIDE; + virtual WebString key(unsigned index) OVERRIDE; + virtual WebString getItem(const WebString& key) OVERRIDE; + virtual void setItem(const WebString& key, const WebString& newValue, + const WebURL& pageUrl, Result&) OVERRIDE; + virtual void removeItem(const WebString& key, + const WebURL& pageUrl) OVERRIDE; + virtual void clear(const WebURL& pageUrl) OVERRIDE; + + private: + DomStorageHost* Host() { + if (!parent_.get()) + return NULL; + return parent_->host_.get(); + } + + base::WeakPtr parent_; + int connection_id_; +}; + +// NamespaceImpl ----------------------------- + +BrowserDomStorageSystem::NamespaceImpl::NamespaceImpl( + const base::WeakPtr& parent) + : parent_(parent), + namespace_id_(dom_storage::kLocalStorageNamespaceId) { +} + +BrowserDomStorageSystem::NamespaceImpl::NamespaceImpl( + const base::WeakPtr& parent, + int session_namespace_id) + : parent_(parent), + namespace_id_(session_namespace_id) { +} + +BrowserDomStorageSystem::NamespaceImpl::~NamespaceImpl() { + if (namespace_id_ == dom_storage::kLocalStorageNamespaceId || + namespace_id_ == kInvalidNamespaceId || !Context()) { + return; + } + Context()->DeleteSessionNamespace(namespace_id_); +} + +WebStorageArea* BrowserDomStorageSystem::NamespaceImpl::createStorageArea( + const WebString& origin) { + return new AreaImpl(parent_, namespace_id_, GURL(origin)); +} + +WebStorageNamespace* BrowserDomStorageSystem::NamespaceImpl::copy() { + DCHECK_NE(dom_storage::kLocalStorageNamespaceId, namespace_id_); + int new_id = kInvalidNamespaceId; + if (Context()) { + new_id = Context()->AllocateSessionId(); + Context()->CloneSessionNamespace(namespace_id_, new_id, std::string()); + } + return new NamespaceImpl(parent_, new_id); +} + +bool BrowserDomStorageSystem::NamespaceImpl::isSameNamespace( + const WebStorageNamespace& other) const { + const NamespaceImpl* other_impl = static_cast(&other); + return namespace_id_ == other_impl->namespace_id_; +} + +// AreaImpl ----------------------------- + +BrowserDomStorageSystem::AreaImpl::AreaImpl( + const base::WeakPtr& parent, + int namespace_id, const GURL& origin) + : parent_(parent), + connection_id_(0) { + if (Host()) { + connection_id_ = (parent_->next_connection_id_)++; + Host()->OpenStorageArea(connection_id_, namespace_id, origin); + } +} + +BrowserDomStorageSystem::AreaImpl::~AreaImpl() { + if (Host()) + Host()->CloseStorageArea(connection_id_); +} + +unsigned BrowserDomStorageSystem::AreaImpl::length() { + if (Host()) + return Host()->GetAreaLength(connection_id_); + return 0; +} + +WebString BrowserDomStorageSystem::AreaImpl::key(unsigned index) { + if (Host()) + return Host()->GetAreaKey(connection_id_, index); + return NullableString16(true); +} + +WebString BrowserDomStorageSystem::AreaImpl::getItem(const WebString& key) { + if (Host()) + return Host()->GetAreaItem(connection_id_, key); + return NullableString16(true); +} + +void BrowserDomStorageSystem::AreaImpl::setItem( + const WebString& key, const WebString& newValue, + const WebURL& pageUrl, Result& result) { + result = ResultBlockedByQuota; + if (!Host()) + return; + + AutoReset auto_reset(&parent_->area_being_processed_, this); + NullableString16 unused; + if (!Host()->SetAreaItem(connection_id_, key, newValue, pageUrl, + &unused)) + return; + + result = ResultOK; +} + +void BrowserDomStorageSystem::AreaImpl::removeItem( + const WebString& key, const WebURL& pageUrl) { + if (!Host()) + return; + + AutoReset auto_reset(&parent_->area_being_processed_, this); + string16 notused; + Host()->RemoveAreaItem(connection_id_, key, pageUrl, ¬used); +} + +void BrowserDomStorageSystem::AreaImpl::clear(const WebURL& pageUrl) { + if (!Host()) + return; + + AutoReset auto_reset(&parent_->area_being_processed_, this); + Host()->ClearArea(connection_id_, pageUrl); +} + +// BrowserDomStorageSystem ----------------------------- + +BrowserDomStorageSystem* BrowserDomStorageSystem::g_instance_; + +BrowserDomStorageSystem::BrowserDomStorageSystem() + : weak_factory_(this), + area_being_processed_(NULL), + next_connection_id_(1) { + FilePath local_storage_path; + FilePath cache_path(_Context->cache_path()); + if (!cache_path.empty()) { + local_storage_path = cache_path.Append(FILE_PATH_LITERAL("Local Storage")); + if (!file_util::PathExists(local_storage_path) && + !file_util::CreateDirectory(local_storage_path)) { + LOG(WARNING) << "Failed to create Local Storage directory"; + local_storage_path.clear(); + } + } + + base::SequencedWorkerPool* worker_pool = _Context->blocking_pool(); + + context_ = new DomStorageContext(local_storage_path, FilePath(), NULL, + new DomStorageWorkerPoolTaskRunner( + worker_pool, + worker_pool->GetNamedSequenceToken("dom_storage_primary"), + worker_pool->GetNamedSequenceToken("dom_storage_commit"), + CefThread::GetMessageLoopProxyForThread(CefThread::FILE))); + + host_.reset(new DomStorageHost(context_)); + + DCHECK(!g_instance_); + g_instance_ = this; + context_->AddEventObserver(this); +} + +BrowserDomStorageSystem::~BrowserDomStorageSystem() { + g_instance_ = NULL; + host_.reset(); + context_->RemoveEventObserver(this); +} + +WebStorageNamespace* BrowserDomStorageSystem::CreateLocalStorageNamespace() { + return new NamespaceImpl(weak_factory_.GetWeakPtr()); +} + +WebStorageNamespace* BrowserDomStorageSystem::CreateSessionStorageNamespace() { + int id = context_->AllocateSessionId(); + context_->CreateSessionNamespace(id, std::string()); + return new NamespaceImpl(weak_factory_.GetWeakPtr(), id); +} + +void BrowserDomStorageSystem::OnDomStorageItemSet( + const dom_storage::DomStorageArea* area, + const string16& key, + const string16& new_value, + const NullableString16& old_value, + const GURL& page_url) { + DispatchDomStorageEvent(area, page_url, + NullableString16(key, false), + NullableString16(new_value, false), + old_value); +} + +void BrowserDomStorageSystem::OnDomStorageItemRemoved( + const dom_storage::DomStorageArea* area, + const string16& key, + const string16& old_value, + const GURL& page_url) { + DispatchDomStorageEvent(area, page_url, + NullableString16(key, false), + NullableString16(true), + NullableString16(old_value, false)); +} + +void BrowserDomStorageSystem::OnDomStorageAreaCleared( + const dom_storage::DomStorageArea* area, + const GURL& page_url) { + DispatchDomStorageEvent(area, page_url, + NullableString16(true), + NullableString16(true), + NullableString16(true)); +} + +void BrowserDomStorageSystem::DispatchDomStorageEvent( + const dom_storage::DomStorageArea* area, + const GURL& page_url, + const NullableString16& key, + const NullableString16& new_value, + const NullableString16& old_value) { + DCHECK(area_being_processed_); + if (area->namespace_id() == dom_storage::kLocalStorageNamespaceId) { + WebStorageEventDispatcher::dispatchLocalStorageEvent( + key, + old_value, + new_value, + area->origin(), + page_url, + area_being_processed_, + true /* originatedInProcess */); + } else { + NamespaceImpl session_namespace_for_event_dispatch( + base::WeakPtr(), area->namespace_id()); + WebStorageEventDispatcher::dispatchSessionStorageEvent( + key, + old_value, + new_value, + area->origin(), + page_url, + session_namespace_for_event_dispatch, + area_being_processed_, + true /* originatedInProcess */); + } +} diff --git a/cef1/libcef/browser_dom_storage_system.h b/cef1/libcef/browser_dom_storage_system.h new file mode 100644 index 000000000..0bcdb0a60 --- /dev/null +++ b/cef1/libcef/browser_dom_storage_system.h @@ -0,0 +1,80 @@ +// 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_DOM_STORAGE_SYSTEM_H_ +#define CEF_LIBCEF_BROWSER_DOM_STORAGE_SYSTEM_H_ +#pragma once + +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "webkit/dom_storage/dom_storage_context.h" + +namespace dom_storage { +class DomStorageHost; +} +namespace WebKit { +class WebStorageNamespace; +} + +// Class that composes dom_storage classes together for use +// in simple single process environments like test_shell and DRT. +class BrowserDomStorageSystem + : public dom_storage::DomStorageContext::EventObserver { + public: + static BrowserDomStorageSystem& instance() { return *g_instance_; } + + BrowserDomStorageSystem(); + virtual ~BrowserDomStorageSystem(); + + // The Create<<>> calls are bound to WebKit api that the embedder + // is responsible for implementing. These factories are called strictly + // on the 'main' webkit thread. Ditto the methods on the returned + // objects. SimplDomStorageSystem manufactures implementations of the + // WebStorageNamespace and WebStorageArea interfaces that ultimately + // plumb Get, Set, Remove, and Clear javascript calls to the dom_storage + // classes. The caller (webkit/webcore) takes ownership of the returned + // instances and will delete them when done. + WebKit::WebStorageNamespace* CreateLocalStorageNamespace(); + WebKit::WebStorageNamespace* CreateSessionStorageNamespace(); + + private: + // Inner classes that implement the WebKit WebStorageNamespace and + // WebStorageArea interfaces in terms of dom_storage classes. + class NamespaceImpl; + class AreaImpl; + + // DomStorageContext::EventObserver implementation which + // calls into webkit/webcore to dispatch events. + virtual void OnDomStorageItemSet( + const dom_storage::DomStorageArea* area, + const string16& key, + const string16& new_value, + const NullableString16& old_value, + const GURL& page_url) OVERRIDE; + virtual void OnDomStorageItemRemoved( + const dom_storage::DomStorageArea* area, + const string16& key, + const string16& old_value, + const GURL& page_url) OVERRIDE; + virtual void OnDomStorageAreaCleared( + const dom_storage::DomStorageArea* area, + const GURL& page_url) OVERRIDE; + + void DispatchDomStorageEvent( + const dom_storage::DomStorageArea* area, + const GURL& page_url, + const NullableString16& key, + const NullableString16& new_value, + const NullableString16& old_value); + + base::WeakPtrFactory weak_factory_; + scoped_refptr context_; + scoped_ptr host_; + AreaImpl* area_being_processed_; + int next_connection_id_; + + static BrowserDomStorageSystem* g_instance_; +}; + +#endif // CEF_LIBCEF_BROWSER_DOM_STORAGE_SYSTEM_H_ diff --git a/cef1/libcef/browser_drag_delegate_win.cc b/cef1/libcef/browser_drag_delegate_win.cc new file mode 100644 index 000000000..dcadee97f --- /dev/null +++ b/cef1/libcef/browser_drag_delegate_win.cc @@ -0,0 +1,363 @@ +// 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. + +#include "libcef/browser_drag_delegate_win.h" + +#include +#include + +#include "libcef/browser_impl.h" +#include "libcef/browser_webview_delegate.h" +#include "libcef/cef_thread.h" +#include "libcef/drag_download_file.h" +#include "libcef/drag_download_util.h" +#include "libcef/download_util.h" +#include "libcef/web_drag_source_win.h" +#include "libcef/web_drag_utils_win.h" +#include "libcef/web_drop_target_win.h" + +#include "base/bind.h" +#include "base/utf_string_conversions.h" +#include "net/base/file_stream.h" +#include "net/base/net_util.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/base/dragdrop/drag_utils.h" +#include "ui/gfx/image/image_skia.h" +#include "webkit/glue/webdropdata.h" + +using WebKit::WebDragOperationsMask; +using WebKit::WebDragOperationCopy; +using WebKit::WebDragOperationLink; +using WebKit::WebDragOperationMove; +using WebKit::WebView; + +namespace { + +HHOOK msg_hook = NULL; +DWORD drag_out_thread_id = 0; +bool mouse_up_received = false; + +LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) { + if (code == base::MessagePumpForUI::kMessageFilterCode && + !mouse_up_received) { + MSG* msg = reinterpret_cast(lparam); + // We do not care about WM_SYSKEYDOWN and WM_SYSKEYUP because when ALT key + // is pressed down on drag-and-drop, it means to create a link. + if (msg->message == WM_MOUSEMOVE || msg->message == WM_LBUTTONUP || + msg->message == WM_KEYDOWN || msg->message == WM_KEYUP) { + // Forward the message from the UI thread to the drag-and-drop thread. + PostThreadMessage(drag_out_thread_id, + msg->message, + msg->wParam, + msg->lParam); + + // If the left button is up, we do not need to forward the message any + // more. + if (msg->message == WM_LBUTTONUP || !(GetKeyState(VK_LBUTTON) & 0x8000)) + mouse_up_received = true; + + return TRUE; + } + } + return CallNextHookEx(msg_hook, code, wparam, lparam); +} + +} // namespace + +class DragDropThread : public base::Thread { + public: + explicit DragDropThread(BrowserDragDelegate* drag_handler) + : base::Thread("Chrome_DragDropThread"), + drag_handler_(drag_handler) { + } + + virtual ~DragDropThread() { + Thread::Stop(); + } + + protected: + // base::Thread implementations: + virtual void Init() { + int ole_result = OleInitialize(NULL); + DCHECK(ole_result == S_OK); + } + + virtual void CleanUp() { + OleUninitialize(); + } + + private: + // Hold a reference count to BrowserDragDelegate to make sure that it is + // always alive in the thread lifetime. + scoped_refptr drag_handler_; + + DISALLOW_COPY_AND_ASSIGN(DragDropThread); +}; + +BrowserDragDelegate::BrowserDragDelegate(BrowserWebViewDelegate* view) + : drag_drop_thread_id_(0), + view_(view), + drag_ended_(false), + old_drop_target_suspended_state_(false) { +} + +BrowserDragDelegate::~BrowserDragDelegate() { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + DCHECK(!drag_drop_thread_.get()); +} + +void BrowserDragDelegate::StartDragging(const WebDropData& drop_data, + WebDragOperationsMask ops, + const SkBitmap& image, + const gfx::Point& image_offset) { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + + CefBrowserImpl* browser = view_->GetBrowser(); + WebView* web_view = browser->UIT_GetWebView(); + drag_source_ = new WebDragSource(browser->UIT_GetWebViewWndHandle(), + web_view); + + const GURL& page_url = web_view->mainFrame()->document().url(); + const std::string& page_encoding = + web_view->mainFrame()->document().encoding().utf8(); + + // If it is not drag-out, do the drag-and-drop in the current UI thread. + if (drop_data.download_metadata.empty()) { + DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset); + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&BrowserDragDelegate::EndDragging, this, false)); + return; + } + + // We do not want to drag and drop the download to itself. + old_drop_target_suspended_state_ = view_->drop_target()->suspended(); + view_->drop_target()->set_suspended(true); + + // Start a background thread to do the drag-and-drop. + DCHECK(!drag_drop_thread_.get()); + drag_drop_thread_.reset(new DragDropThread(this)); + base::Thread::Options options; + options.message_loop_type = MessageLoop::TYPE_UI; + if (drag_drop_thread_->StartWithOptions(options)) { + drag_drop_thread_->message_loop()->PostTask( + FROM_HERE, + base::Bind(&BrowserDragDelegate::StartBackgroundDragging, + this, + drop_data, + ops, + page_url, + page_encoding, + image, + image_offset)); + } + + // Install a hook procedure to monitor the messages so that we can forward + // the appropriate ones to the background thread. + drag_out_thread_id = drag_drop_thread_->thread_id(); + mouse_up_received = false; + DCHECK(!msg_hook); + msg_hook = SetWindowsHookEx(WH_MSGFILTER, + MsgFilterProc, + NULL, + GetCurrentThreadId()); + + // Attach the input state of the background thread to the UI thread so that + // SetCursor can work from the background thread. + AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), TRUE); +} + +void BrowserDragDelegate::StartBackgroundDragging( + const WebDropData& drop_data, + WebDragOperationsMask ops, + const GURL& page_url, + const std::string& page_encoding, + const SkBitmap& image, + const gfx::Point& image_offset) { + drag_drop_thread_id_ = base::PlatformThread::CurrentId(); + + DoDragging(drop_data, ops, page_url, page_encoding, image, image_offset); + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&BrowserDragDelegate::EndDragging, this, true)); +} + +void BrowserDragDelegate::PrepareDragForDownload( + const WebDropData& drop_data, + ui::OSExchangeData* data, + const GURL& page_url, + const std::string& page_encoding) { + // Parse the download metadata. + string16 mime_type; + FilePath file_name; + GURL download_url; + if (!drag_download_util::ParseDownloadMetadata(drop_data.download_metadata, + &mime_type, + &file_name, + &download_url)) + return; + + // Generate the download filename. + std::string content_disposition = + "attachment; filename=" + UTF16ToUTF8(file_name.value()); + FilePath generated_file_name; + download_util::GenerateFileName(download_url, + content_disposition, + std::string(), + UTF16ToUTF8(mime_type), + std::string(), + &generated_file_name); + + // Provide the data as file (CF_HDROP). A temporary download file with the + // Zone.Identifier ADS (Alternate Data Stream) attached will be created. + linked_ptr empty_file_stream; + scoped_refptr download_file = + new DragDownloadFile(generated_file_name, + empty_file_stream, + download_url, + page_url, + page_encoding, + view_); + ui::OSExchangeData::DownloadFileInfo file_download(FilePath(), + download_file.get()); + data->SetDownloadFileInfo(file_download); + + // Enable asynchronous operation. + ui::OSExchangeDataProviderWin::GetIAsyncOperation(*data)->SetAsyncMode(TRUE); +} + +void BrowserDragDelegate::PrepareDragForFileContents( + const WebDropData& drop_data, ui::OSExchangeData* data) { + static const int kMaxFilenameLength = 255; // FAT and NTFS + FilePath file_name(drop_data.file_description_filename); + string16 extension = file_name.Extension(); + file_name = file_name.BaseName().RemoveExtension(); + // 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.value().empty()) { + // Retrieve the name from the URL. + file_name = FilePath( + net::GetSuggestedFilename(drop_data.url, "", "", "", "", "")); + if (file_name.value().size() + extension.size() > kMaxFilenameLength) { + file_name = FilePath(file_name.value().substr( + 0, kMaxFilenameLength - extension.size())); + } + } + file_name = file_name.ReplaceExtension(extension); + data->SetFileContents(file_name, drop_data.file_contents); +} + +void BrowserDragDelegate::PrepareDragForUrl(const WebDropData& drop_data, + ui::OSExchangeData* data) { + if (drop_data.url.SchemeIs("javascript")) { + // We don't want to allow javascript URLs to be dragged to the desktop. + } else { + data->SetURL(drop_data.url, drop_data.url_title); + } +} + +void BrowserDragDelegate::DoDragging(const WebDropData& drop_data, + WebDragOperationsMask ops, + const GURL& page_url, + const std::string& page_encoding, + const SkBitmap& image, + const gfx::Point& image_offset) { + ui::OSExchangeData data; + + if (!drop_data.download_metadata.empty()) { + PrepareDragForDownload(drop_data, &data, page_url, page_encoding); + + // Set the observer. + ui::OSExchangeDataProviderWin::GetDataObjectImpl(data)->set_observer(this); + } else { + // We set the file contents before the URL because the URL also sets file + // contents (to a .URL shortcut). We want to prefer file content data over + // a shortcut so we add it first. + if (!drop_data.file_contents.empty()) + PrepareDragForFileContents(drop_data, &data); + if (!drop_data.html.is_null() && !drop_data.html.string().empty()) + data.SetHtml(drop_data.html.string(), drop_data.html_base_url); + // We set the text contents before the URL because the URL also sets text + // content. + if (!drop_data.text.is_null() && !drop_data.text.string().empty()) + data.SetString(drop_data.text.string()); + if (drop_data.url.is_valid()) + PrepareDragForUrl(drop_data, &data); + } + + // Set drag image. + if (!image.isNull()) { + drag_utils::SetDragImageOnDataObject( + gfx::ImageSkia(image), gfx::Size(image.width(), image.height()), + image_offset, &data); + } + + // We need to enable recursive tasks on the message loop so we can get + // updates while in the system DoDragDrop loop. + bool old_state = MessageLoop::current()->NestableTasksAllowed(); + MessageLoop::current()->SetNestableTasksAllowed(true); + DWORD effect; + DoDragDrop(ui::OSExchangeDataProviderWin::GetIDataObject(data), drag_source_, + web_drag_utils_win::WebDragOpMaskToWinDragOpMask(ops), &effect); + MessageLoop::current()->SetNestableTasksAllowed(old_state); + + // This works because WebDragSource::OnDragSourceDrop uses PostTask to + // dispatch the actual event. + drag_source_->set_effect(effect); +} + +void BrowserDragDelegate::EndDragging(bool restore_suspended_state) { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + + if (drag_ended_) + return; + drag_ended_ = true; + + if (restore_suspended_state) + view_->drop_target()->set_suspended(old_drop_target_suspended_state_); + + if (msg_hook) { + AttachThreadInput(drag_out_thread_id, GetCurrentThreadId(), FALSE); + UnhookWindowsHookEx(msg_hook); + msg_hook = NULL; + } + + view_->EndDragging(); +} + +void BrowserDragDelegate::CancelDrag() { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + + drag_source_->CancelDrag(); +} + +void BrowserDragDelegate::CloseThread() { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + + drag_drop_thread_.reset(); +} + +void BrowserDragDelegate::OnWaitForData() { + DCHECK(drag_drop_thread_id_ == base::PlatformThread::CurrentId()); + + // When the left button is released and we start to wait for the data, end + // the dragging before DoDragDrop returns. This makes the page leave the drag + // mode so that it can start to process the normal input events. + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&BrowserDragDelegate::EndDragging, this, true)); +} + +void BrowserDragDelegate::OnDataObjectDisposed() { + DCHECK(drag_drop_thread_id_ == base::PlatformThread::CurrentId()); + + // The drag-and-drop thread is only closed after OLE is done with + // DataObjectImpl. + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&BrowserDragDelegate::CloseThread, this)); +} diff --git a/cef1/libcef/browser_drag_delegate_win.h b/cef1/libcef/browser_drag_delegate_win.h new file mode 100644 index 000000000..25290d533 --- /dev/null +++ b/cef1/libcef/browser_drag_delegate_win.h @@ -0,0 +1,104 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. +// Portions copyright (c) 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_DRAG_DELEGATE_WIN_H_ +#define CEF_LIBCEF_BROWSER_DRAG_DELEGATE_WIN_H_ +#pragma once + +#include + +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/threading/platform_thread.h" +#include "third_party/skia/include/core/SkBitmap.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" +#include "ui/base/dragdrop/os_exchange_data_provider_win.h" +#include "ui/gfx/point.h" + +class BrowserWebViewDelegate; +class DragDropThread; +class WebDragSource; +struct WebDropData; + +// Windows-specific drag-and-drop handling. +// If we are dragging a virtual file out of the browser, we use a background +// thread to do the drag-and-drop because we do not want to run nested +// message loop in the UI thread. For all other cases, the drag-and-drop happens +// in the UI thread. +class BrowserDragDelegate + : public ui::DataObjectImpl::Observer, + public base::RefCountedThreadSafe { + public: + explicit BrowserDragDelegate(BrowserWebViewDelegate* view); + virtual ~BrowserDragDelegate(); + + // Called on UI thread. + void StartDragging(const WebDropData& drop_data, + WebKit::WebDragOperationsMask ops, + const SkBitmap& image, + const gfx::Point& image_offset); + void CancelDrag(); + + // DataObjectImpl::Observer implementation. + // Called on drag-and-drop thread. + virtual void OnWaitForData(); + virtual void OnDataObjectDisposed(); + + private: + // Called on either UI thread or drag-and-drop thread. + void PrepareDragForDownload(const WebDropData& drop_data, + ui::OSExchangeData* data, + const GURL& page_url, + const std::string& page_encoding); + void PrepareDragForFileContents(const WebDropData& drop_data, + ui::OSExchangeData* data); + void PrepareDragForUrl(const WebDropData& drop_data, + ui::OSExchangeData* data); + void DoDragging(const WebDropData& drop_data, + WebKit::WebDragOperationsMask ops, + const GURL& page_url, + const std::string& page_encoding, + const SkBitmap& image, + const gfx::Point& image_offset); + + // Called on drag-and-drop thread. + void StartBackgroundDragging(const WebDropData& drop_data, + WebKit::WebDragOperationsMask ops, + const GURL& page_url, + const std::string& page_encoding, + const SkBitmap& image, + const gfx::Point& image_offset); + // Called on UI thread. + void EndDragging(bool restore_suspended_state); + void CloseThread(); + + // For debug check only. Access only on drag-and-drop thread. + base::PlatformThreadId drag_drop_thread_id_; + + // All the member variables below are accessed on UI thread. + + // Keep track of the BrowserWebViewDelegate it is associated with. + BrowserWebViewDelegate* view_; + + // |drag_source_| is our callback interface passed to the system when we + // want to initiate a drag and drop operation. We use it to tell if a + // drag operation is happening. + scoped_refptr drag_source_; + + // The thread used by the drag-out download. This is because we want to avoid + // running nested message loop in main UI thread. + scoped_ptr drag_drop_thread_; + + // The flag to guard that EndDragging is not called twice. + bool drag_ended_; + + // Keep track of the old suspended state of the drop target. + bool old_drop_target_suspended_state_; + + DISALLOW_COPY_AND_ASSIGN(BrowserDragDelegate); +}; + + +#endif // CEF_LIBCEF_BROWSER_DRAG_DELEGATE_WIN_H_ diff --git a/cef1/libcef/browser_file_system.cc b/cef1/libcef/browser_file_system.cc new file mode 100644 index 000000000..43bb4fbe2 --- /dev/null +++ b/cef1/libcef/browser_file_system.cc @@ -0,0 +1,323 @@ +// 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_file_system.h" +#include "libcef/browser_file_writer.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "base/file_path.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" +#include "base/time.h" +#include "base/utf_string_conversions.h" +#include "googleurl/src/gurl.h" +#include "net/base/mime_util.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileSystemCallbacks.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileSystemEntry.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebVector.h" +#include "webkit/blob/blob_storage_controller.h" +#include "webkit/fileapi/file_system_util.h" +#include "webkit/fileapi/mock_file_system_options.h" +#include "webkit/glue/webkit_glue.h" + +using base::WeakPtr; + +using WebKit::WebFileInfo; +using WebKit::WebFileSystem; +using WebKit::WebFileSystemCallbacks; +using WebKit::WebFileSystemEntry; +using WebKit::WebFileWriter; +using WebKit::WebFileWriterClient; +using WebKit::WebFrame; +using WebKit::WebSecurityOrigin; +using WebKit::WebString; +using WebKit::WebURL; +using WebKit::WebVector; + +using webkit_blob::BlobData; +using webkit_blob::BlobStorageController; +using fileapi::FileSystemContext; +using fileapi::FileSystemOperationInterface; + +namespace { +MessageLoop* g_io_thread; +webkit_blob::BlobStorageController* g_blob_storage_controller; + +void RegisterBlob(const GURL& blob_url, const FilePath& file_path) { + DCHECK(g_blob_storage_controller); + + FilePath::StringType extension = file_path.Extension(); + if (!extension.empty()) + extension = extension.substr(1); // Strip leading ".". + + // This may fail, but then we'll be just setting the empty mime type. + std::string mime_type; + net::GetWellKnownMimeTypeFromExtension(extension, &mime_type); + + BlobData::Item item; + item.SetToFile(file_path, 0, -1, base::Time()); + g_blob_storage_controller->StartBuildingBlob(blob_url); + g_blob_storage_controller->AppendBlobDataItem(blob_url, item); + g_blob_storage_controller->FinishBuildingBlob(blob_url, mime_type); +} + +} // namespace + +BrowserFileSystem::BrowserFileSystem() { +} + +void BrowserFileSystem::CreateContext() { + if (file_system_context_.get()) + return; + if (file_system_dir_.CreateUniqueTempDir()) { + std::vector additional_allowed_schemes; + additional_allowed_schemes.push_back("file"); + + file_system_context_ = new FileSystemContext( + CefThread::GetMessageLoopProxyForThread(CefThread::FILE), + CefThread::GetMessageLoopProxyForThread(CefThread::IO), + NULL /* special storage policy */, + NULL /* quota manager */, + file_system_dir_.path(), + fileapi::FileSystemOptions( + fileapi::FileSystemOptions::PROFILE_MODE_NORMAL, + additional_allowed_schemes)); + } else { + LOG(WARNING) << "Failed to create a temp dir for the filesystem." + "FileSystem feature will be disabled."; + } +} + +BrowserFileSystem::~BrowserFileSystem() { +} + +void BrowserFileSystem::OpenFileSystem( + WebFrame* frame, WebFileSystem::Type web_filesystem_type, + long long, bool create, // NOLINT(runtime/int) + WebFileSystemCallbacks* callbacks) { + if (!frame || !file_system_context_.get()) { + // The FileSystem temp directory was not initialized successfully. + callbacks->didFail(WebKit::WebFileErrorSecurity); + return; + } + + fileapi::FileSystemType type; + if (web_filesystem_type == WebFileSystem::TypeTemporary) + type = fileapi::kFileSystemTypeTemporary; + else if (web_filesystem_type == WebFileSystem::TypePersistent) + type = fileapi::kFileSystemTypePersistent; + else if (web_filesystem_type == WebFileSystem::TypeExternal) + type = fileapi::kFileSystemTypeExternal; + else { + // Unknown type filesystem is requested. + callbacks->didFail(WebKit::WebFileErrorSecurity); + return; + } + + GURL origin_url(frame->document().securityOrigin().toString()); + file_system_context_->OpenFileSystem( + origin_url, type, create, OpenFileSystemHandler(callbacks)); +} + +void BrowserFileSystem::move( + const WebURL& src_path, + const WebURL& dest_path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(src_path)->Move(GURL(src_path), GURL(dest_path), + FinishHandler(callbacks)); +} + +void BrowserFileSystem::copy( + const WebURL& src_path, const WebURL& dest_path, + WebFileSystemCallbacks* callbacks) { + GetNewOperation(src_path)->Copy(GURL(src_path), GURL(dest_path), + FinishHandler(callbacks)); +} + +void BrowserFileSystem::remove( + const WebURL& path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->Remove(path, false /* recursive */, + FinishHandler(callbacks)); +} + +void BrowserFileSystem::removeRecursively( + const WebURL& path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->Remove(path, true /* recursive */, + FinishHandler(callbacks)); +} + +void BrowserFileSystem::readMetadata( + const WebURL& path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->GetMetadata(path, GetMetadataHandler(callbacks)); +} + +void BrowserFileSystem::createFile( + const WebURL& path, bool exclusive, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->CreateFile(path, exclusive, FinishHandler(callbacks)); +} + +void BrowserFileSystem::createDirectory( + const WebURL& path, bool exclusive, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->CreateDirectory(path, exclusive, false, + FinishHandler(callbacks)); +} + +void BrowserFileSystem::fileExists( + const WebURL& path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->FileExists(path, FinishHandler(callbacks)); +} + +void BrowserFileSystem::directoryExists( + const WebURL& path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->DirectoryExists(path, FinishHandler(callbacks)); +} + +void BrowserFileSystem::readDirectory( + const WebURL& path, WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->ReadDirectory(path, ReadDirectoryHandler(callbacks)); +} + +WebFileWriter* BrowserFileSystem::createFileWriter( + const WebURL& path, WebFileWriterClient* client) { + return new BrowserFileWriter(path, client, file_system_context_.get()); +} + +void BrowserFileSystem::createSnapshotFileAndReadMetadata( + const WebURL& blobURL, + const WebURL& path, + WebFileSystemCallbacks* callbacks) { + GetNewOperation(path)->CreateSnapshotFile( + path, SnapshotFileHandler(blobURL, callbacks)); +} + +// static +void BrowserFileSystem::InitializeOnIOThread( + webkit_blob::BlobStorageController* blob_storage_controller) { + g_io_thread = MessageLoop::current(); + g_blob_storage_controller = blob_storage_controller; +} + +// static +void BrowserFileSystem::CleanupOnIOThread() { + g_io_thread = NULL; + g_blob_storage_controller = NULL; +} + +FileSystemOperationInterface* BrowserFileSystem::GetNewOperation( + const WebURL& url) { + return file_system_context_->CreateFileSystemOperation(GURL(url)); +} + +FileSystemOperationInterface::StatusCallback +BrowserFileSystem::FinishHandler(WebFileSystemCallbacks* callbacks) { + return base::Bind(&BrowserFileSystem::DidFinish, + AsWeakPtr(), base::Unretained(callbacks)); +} + +FileSystemOperationInterface::ReadDirectoryCallback +BrowserFileSystem::ReadDirectoryHandler(WebFileSystemCallbacks* callbacks) { + return base::Bind(&BrowserFileSystem::DidReadDirectory, + AsWeakPtr(), base::Unretained(callbacks)); +} + +FileSystemOperationInterface::GetMetadataCallback +BrowserFileSystem::GetMetadataHandler(WebFileSystemCallbacks* callbacks) { + return base::Bind(&BrowserFileSystem::DidGetMetadata, + AsWeakPtr(), base::Unretained(callbacks)); +} + +FileSystemContext::OpenFileSystemCallback +BrowserFileSystem::OpenFileSystemHandler(WebFileSystemCallbacks* callbacks) { + return base::Bind(&BrowserFileSystem::DidOpenFileSystem, + AsWeakPtr(), base::Unretained(callbacks)); +} + +FileSystemOperationInterface::SnapshotFileCallback +BrowserFileSystem::SnapshotFileHandler(const GURL& blob_url, + WebFileSystemCallbacks* callbacks) { + return base::Bind(&BrowserFileSystem::DidCreateSnapshotFile, + AsWeakPtr(), blob_url, base::Unretained(callbacks)); +} + +void BrowserFileSystem::DidFinish(WebFileSystemCallbacks* callbacks, + base::PlatformFileError result) { + if (result == base::PLATFORM_FILE_OK) + callbacks->didSucceed(); + else + callbacks->didFail(fileapi::PlatformFileErrorToWebFileError(result)); +} + +void BrowserFileSystem::DidGetMetadata(WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const base::PlatformFileInfo& info, + const FilePath& platform_path) { + if (result == base::PLATFORM_FILE_OK) { + WebFileInfo web_file_info; + web_file_info.length = info.size; + web_file_info.modificationTime = info.last_modified.ToDoubleT(); + web_file_info.type = info.is_directory ? + WebFileInfo::TypeDirectory : WebFileInfo::TypeFile; + web_file_info.platformPath = + webkit_glue::FilePathToWebString(platform_path); + callbacks->didReadMetadata(web_file_info); + } else { + callbacks->didFail(fileapi::PlatformFileErrorToWebFileError(result)); + } +} + +void BrowserFileSystem::DidReadDirectory( + WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const std::vector& entries, + bool has_more) { + if (result == base::PLATFORM_FILE_OK) { + std::vector web_entries_vector; + for (std::vector::const_iterator it = + entries.begin(); it != entries.end(); ++it) { + WebFileSystemEntry entry; + entry.name = webkit_glue::FilePathStringToWebString(it->name); + entry.isDirectory = it->is_directory; + web_entries_vector.push_back(entry); + } + WebVector web_entries = web_entries_vector; + callbacks->didReadDirectory(web_entries, has_more); + } else { + callbacks->didFail(fileapi::PlatformFileErrorToWebFileError(result)); + } +} + +void BrowserFileSystem::DidOpenFileSystem( + WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const std::string& name, const GURL& root) { + if (result == base::PLATFORM_FILE_OK) { + if (!root.is_valid()) + callbacks->didFail(WebKit::WebFileErrorSecurity); + else + callbacks->didOpenFileSystem(WebString::fromUTF8(name), root); + } else { + callbacks->didFail(fileapi::PlatformFileErrorToWebFileError(result)); + } +} + +void BrowserFileSystem::DidCreateSnapshotFile( + const GURL& blob_url, + WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const base::PlatformFileInfo& info, + const FilePath& platform_path, + const scoped_refptr& file_ref) { + DCHECK(g_io_thread); + if (result == base::PLATFORM_FILE_OK) { + g_io_thread->PostTask( + FROM_HERE, + base::Bind(&RegisterBlob, blob_url, platform_path)); + } + DidGetMetadata(callbacks, result, info, platform_path); +} diff --git a/cef1/libcef/browser_file_system.h b/cef1/libcef/browser_file_system.h new file mode 100644 index 000000000..92be43d45 --- /dev/null +++ b/cef1/libcef/browser_file_system.h @@ -0,0 +1,146 @@ +// 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_FILE_SYSTEM_H_ +#define CEF_LIBCEF_BROWSER_FILE_SYSTEM_H_ +#pragma once + +#include + +#include "base/file_util_proxy.h" +#include "base/id_map.h" +#include "base/memory/weak_ptr.h" +#include "base/scoped_temp_dir.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFileSystem.h" +#include "webkit/fileapi/file_system_context.h" +#include "webkit/fileapi/file_system_operation_interface.h" +#include "webkit/fileapi/file_system_types.h" + +namespace WebKit { +class WebFileSystemCallbacks; +class WebFrame; +class WebURL; +} + +namespace fileapi { +class FileSystemContext; +} + +namespace webkit_blob { +class BlobStorageController; +} + +class BrowserFileSystem + : public WebKit::WebFileSystem, + public base::SupportsWeakPtr { + public: + BrowserFileSystem(); + virtual ~BrowserFileSystem(); + + void CreateContext(); + + void OpenFileSystem(WebKit::WebFrame* frame, + WebKit::WebFileSystem::Type type, + long long size, // NOLINT(runtime/int) + bool create, + WebKit::WebFileSystemCallbacks* callbacks); + + fileapi::FileSystemContext* file_system_context() { + return file_system_context_.get(); + } + + // WebKit::WebFileSystem implementation. + virtual void move( + const WebKit::WebURL& src_path, + const WebKit::WebURL& dest_path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void copy( + const WebKit::WebURL& src_path, + const WebKit::WebURL& dest_path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void remove( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void removeRecursively( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void readMetadata( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void createFile( + const WebKit::WebURL& path, + bool exclusive, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void createDirectory( + const WebKit::WebURL& path, + bool exclusive, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void fileExists( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void directoryExists( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual void readDirectory( + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks*) OVERRIDE; + virtual WebKit::WebFileWriter* createFileWriter( + const WebKit::WebURL& path, WebKit::WebFileWriterClient*) OVERRIDE; + virtual void createSnapshotFileAndReadMetadata( + const WebKit::WebURL& blobURL, + const WebKit::WebURL& path, + WebKit::WebFileSystemCallbacks* callbacks) OVERRIDE; + + static void InitializeOnIOThread( + webkit_blob::BlobStorageController* blob_storage_controller); + static void CleanupOnIOThread(); + + private: + // Helpers. + fileapi::FileSystemOperationInterface* GetNewOperation( + const WebKit::WebURL& path); + + // Callback Handlers + fileapi::FileSystemOperationInterface::StatusCallback FinishHandler( + WebKit::WebFileSystemCallbacks* callbacks); + fileapi::FileSystemOperationInterface::GetMetadataCallback GetMetadataHandler( + WebKit::WebFileSystemCallbacks* callbacks); + fileapi::FileSystemOperationInterface::ReadDirectoryCallback + ReadDirectoryHandler(WebKit::WebFileSystemCallbacks* callbacks); + fileapi::FileSystemContext::OpenFileSystemCallback OpenFileSystemHandler( + WebKit::WebFileSystemCallbacks* callbacks); + fileapi::FileSystemOperationInterface::SnapshotFileCallback + SnapshotFileHandler(const GURL& blob_url, + WebKit::WebFileSystemCallbacks* callbacks); + void DidFinish(WebKit::WebFileSystemCallbacks* callbacks, + base::PlatformFileError result); + void DidGetMetadata(WebKit::WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const base::PlatformFileInfo& info, + const FilePath& platform_path); + void DidReadDirectory( + WebKit::WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const std::vector& entries, + bool has_more); + void DidOpenFileSystem(WebKit::WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const std::string& name, const GURL& root); + void DidCreateSnapshotFile( + const GURL& blob_url, + WebKit::WebFileSystemCallbacks* callbacks, + base::PlatformFileError result, + const base::PlatformFileInfo& info, + const FilePath& platform_path, + const scoped_refptr& file_ref); + + // A temporary directory for FileSystem API. + ScopedTempDir file_system_dir_; + + scoped_refptr file_system_context_; + + DISALLOW_COPY_AND_ASSIGN(BrowserFileSystem); +}; + +#endif // CEF_LIBCEF_BROWSER_FILE_SYSTEM_H_ diff --git a/cef1/libcef/browser_file_writer.cc b/cef1/libcef/browser_file_writer.cc new file mode 100644 index 000000000..9acff66fe --- /dev/null +++ b/cef1/libcef/browser_file_writer.cc @@ -0,0 +1,182 @@ +// 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_file_writer.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/message_loop_proxy.h" +#include "net/url_request/url_request_context.h" +#include "webkit/fileapi/file_system_context.h" +#include "webkit/fileapi/file_system_operation_interface.h" +#include "webkit/glue/webkit_glue.h" + +using fileapi::FileSystemContext; +using fileapi::FileSystemOperationInterface; +using fileapi::WebFileWriterBase; +using WebKit::WebFileWriterClient; +using WebKit::WebString; +using WebKit::WebURL; + +net::URLRequestContext* BrowserFileWriter::request_context_ = NULL; + +// Helper class to proxy the write and truncate calls to the IO thread, +// and to proxy the results back to the main thead. There is a one-to-one +// relationship between BrowserFileWriters and IOThreadBackends. +class BrowserFileWriter::IOThreadProxy + : public base::RefCountedThreadSafe { + public: + IOThreadProxy(const base::WeakPtr& simple_writer, + FileSystemContext* file_system_context) + : simple_writer_(simple_writer), + operation_(NULL), + file_system_context_(file_system_context) { + io_thread_ = CefThread::GetMessageLoopProxyForThread(CefThread::IO); + main_thread_ = base::MessageLoopProxy::current(); + } + + void Truncate(const GURL& path, int64 offset) { + if (!io_thread_->BelongsToCurrentThread()) { + io_thread_->PostTask( + FROM_HERE, + base::Bind(&IOThreadProxy::Truncate, this, path, offset)); + return; + } + DCHECK(!operation_); + operation_ = GetNewOperation(path); + operation_->Truncate(path, offset, + base::Bind(&IOThreadProxy::DidFinish, this)); + } + + void Write(const GURL& path, const GURL& blob_url, int64 offset) { + if (!io_thread_->BelongsToCurrentThread()) { + io_thread_->PostTask( + FROM_HERE, + base::Bind(&IOThreadProxy::Write, this, path, blob_url, offset)); + return; + } + DCHECK(request_context_); + DCHECK(!operation_); + operation_ = GetNewOperation(path); + operation_->Write(request_context_, path, blob_url, offset, + base::Bind(&IOThreadProxy::DidWrite, this)); + } + + void Cancel() { + if (!io_thread_->BelongsToCurrentThread()) { + io_thread_->PostTask( + FROM_HERE, + base::Bind(&IOThreadProxy::Cancel, this)); + return; + } + if (!operation_) { + DidFailOnMainThread(base::PLATFORM_FILE_ERROR_INVALID_OPERATION); + return; + } + operation_->Cancel(base::Bind(&IOThreadProxy::DidFinish, this)); + } + + private: + friend class base::RefCountedThreadSafe; + virtual ~IOThreadProxy() {} + + FileSystemOperationInterface* GetNewOperation(const GURL& path) { + return file_system_context_->CreateFileSystemOperation(path); + } + + void DidSucceedOnMainThread() { + if (!main_thread_->BelongsToCurrentThread()) { + main_thread_->PostTask( + FROM_HERE, + base::Bind(&IOThreadProxy::DidSucceedOnMainThread, this)); + return; + } + if (simple_writer_) + simple_writer_->DidSucceed(); + } + + void DidFailOnMainThread(base::PlatformFileError error_code) { + if (!main_thread_->BelongsToCurrentThread()) { + main_thread_->PostTask( + FROM_HERE, + base::Bind(&IOThreadProxy::DidFailOnMainThread, this, error_code)); + return; + } + if (simple_writer_) + simple_writer_->DidFail(error_code); + } + + void DidWriteOnMainThread(int64 bytes, bool complete) { + if (!main_thread_->BelongsToCurrentThread()) { + main_thread_->PostTask( + FROM_HERE, + base::Bind(&IOThreadProxy::DidWriteOnMainThread, + this, bytes, complete)); + return; + } + if (simple_writer_) + simple_writer_->DidWrite(bytes, complete); + } + + void ClearOperation() { + DCHECK(io_thread_->BelongsToCurrentThread()); + operation_ = NULL; + } + + void DidFinish(base::PlatformFileError result) { + if (result == base::PLATFORM_FILE_OK) + DidSucceedOnMainThread(); + else + DidFailOnMainThread(result); + ClearOperation(); + } + + void DidWrite(base::PlatformFileError result, int64 bytes, bool complete) { + if (result == base::PLATFORM_FILE_OK) { + DidWriteOnMainThread(bytes, complete); + if (complete) + ClearOperation(); + } else { + DidFailOnMainThread(result); + ClearOperation(); + } + } + + scoped_refptr io_thread_; + scoped_refptr main_thread_; + + // Only used on the main thread. + base::WeakPtr simple_writer_; + + // Only used on the io thread. + FileSystemOperationInterface* operation_; + + scoped_refptr file_system_context_; +}; + + +BrowserFileWriter::BrowserFileWriter( + const GURL& path, + WebFileWriterClient* client, + FileSystemContext* file_system_context) + : WebFileWriterBase(path, client), + io_thread_proxy_(new IOThreadProxy(AsWeakPtr(), file_system_context)) { +} + +BrowserFileWriter::~BrowserFileWriter() { +} + +void BrowserFileWriter::DoTruncate(const GURL& path, int64 offset) { + io_thread_proxy_->Truncate(path, offset); +} + +void BrowserFileWriter::DoWrite( + const GURL& path, const GURL& blob_url, int64 offset) { + io_thread_proxy_->Write(path, blob_url, offset); +} + +void BrowserFileWriter::DoCancel() { + io_thread_proxy_->Cancel(); +} diff --git a/cef1/libcef/browser_file_writer.h b/cef1/libcef/browser_file_writer.h new file mode 100644 index 000000000..869301430 --- /dev/null +++ b/cef1/libcef/browser_file_writer.h @@ -0,0 +1,52 @@ +// 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_FILE_WRITER_H_ +#define CEF_LIBCEF_BROWSER_FILE_WRITER_H_ +#pragma once + +#include "base/memory/ref_counted.h" +#include "base/memory/weak_ptr.h" +#include "webkit/fileapi/webfilewriter_base.h" + +namespace net { +class URLRequestContext; +} // namespace net + +namespace fileapi { +class FileSystemContext; +} + +// An implementation of WebFileWriter for use in test_shell and DRT. +class BrowserFileWriter : public fileapi::WebFileWriterBase, + public base::SupportsWeakPtr { + public: + BrowserFileWriter( + const GURL& path, + WebKit::WebFileWriterClient* client, + fileapi::FileSystemContext* file_system_context); + virtual ~BrowserFileWriter(); + + // Called by CefProcessIOThread when the context is created and destroyed. + static void InitializeOnIOThread(net::URLRequestContext* request_context) { + request_context_ = request_context; + } + static void CleanupOnIOThread() { + request_context_ = NULL; + } + + protected: + // WebFileWriterBase overrides + virtual void DoTruncate(const GURL& path, int64 offset) OVERRIDE; + virtual void DoWrite(const GURL& path, const GURL& blob_url, + int64 offset) OVERRIDE; + virtual void DoCancel() OVERRIDE; + + private: + class IOThreadProxy; + scoped_refptr io_thread_proxy_; + static net::URLRequestContext* request_context_; +}; + +#endif // CEF_LIBCEF_BROWSER_FILE_WRITER_H_ diff --git a/cef1/libcef/browser_impl.cc b/cef1/libcef/browser_impl.cc new file mode 100644 index 000000000..025a4439d --- /dev/null +++ b/cef1/libcef/browser_impl.cc @@ -0,0 +1,1685 @@ +// Copyright (c) 2012 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. + +#include "libcef/browser_impl.h" +#include "libcef/browser_devtools_scheme_handler.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/browser_zoom_map.h" +#include "libcef/cef_context.h" +#include "libcef/dom_document_impl.h" +#include "libcef/request_impl.h" +#include "libcef/stream_impl.h" +#include "libcef/v8_impl.h" + +#include "base/bind.h" +#include "base/file_path.h" +#include "base/path_service.h" +#include "base/stringprintf.h" +#include "base/synchronization/waitable_event.h" +#include "base/utf_string_conversions.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebHTTPBody.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPlugin.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebRange.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptSource.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/glue_serialize.h" +#include "webkit/plugins/npapi/webplugin_delegate.h" +#include "webkit/plugins/npapi/webplugin_impl.h" +#include "webkit/glue/webkit_glue.h" + +using WebKit::WebDocument; +using WebKit::WebFrame; +using WebKit::WebHTTPBody; +using WebKit::WebPlugin; +using WebKit::WebPluginDocument; +using WebKit::WebRange; +using WebKit::WebRect; +using WebKit::WebScriptSource; +using WebKit::WebString; +using WebKit::WebURL; +using WebKit::WebURLRequest; +using WebKit::WebView; + +namespace { + +class CreateBrowserHelper { + public: + CreateBrowserHelper(CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings) + : window_info_(windowInfo), + client_(client), + url_(url), + settings_(settings) {} + + CefWindowInfo window_info_; + CefRefPtr client_; + CefString url_; + CefBrowserSettings settings_; +}; + +void UIT_CreateBrowserWithHelper(CreateBrowserHelper* helper) { + CefBrowser::CreateBrowserSync(helper->window_info_, helper->client_, + helper->url_, helper->settings_); + delete helper; +} + +} // namespace + + +CefBrowserImpl::PaintDelegate::PaintDelegate(CefBrowserImpl* browser) + : browser_(browser) { +} + +CefBrowserImpl::PaintDelegate::~PaintDelegate() { +} + +void CefBrowserImpl::PaintDelegate::Paint( + bool popup, const std::vector& dirtyRects, const void* buffer) { + CefRefPtr client = browser_->GetClient(); + if (!client.get()) + return; + CefRefPtr handler = client->GetRenderHandler(); + if (!handler.get()) + return; + + handler->OnPaint(browser_, (popup?PET_POPUP:PET_VIEW), dirtyRects, buffer); +} + + +// static +bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, + CefRefPtr client, + const CefString& url, + const CefBrowserSettings& settings) { + // 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; + } + + // Create the browser on the UI thread. + CreateBrowserHelper* helper = + new CreateBrowserHelper(windowInfo, client, url, settings); + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(UIT_CreateBrowserWithHelper, helper)); + return true; +} + +// static +CefRefPtr CefBrowser::CreateBrowserSync( + CefWindowInfo& windowInfo, CefRefPtr client, + const CefString& url, const CefBrowserSettings& settings) { + // 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 (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + CefRefPtr browser( + new CefBrowserImpl(windowInfo, settings, NULL, client)); + if (!static_cast(browser.get())->UIT_CreateBrowser(url)) + return NULL; + + return browser; +} + + +CefBrowserImpl::CefBrowserImpl(const CefWindowInfo& windowInfo, + const CefBrowserSettings& settings, + gfx::NativeView opener, + CefRefPtr client) + : window_info_(windowInfo), + settings_(settings), + opener_(opener), + is_modal_(false), + client_(client), + webviewhost_(NULL), + popuphost_(NULL), + zoom_level_(0.0), + can_go_back_(false), + can_go_forward_(false), + has_document_(false), + is_dropping_(false), + is_in_onsetfocus_(false), + unique_id_(0) +#if defined(OS_WIN) + , opener_was_disabled_by_modal_loop_(false), + internal_modal_message_loop_is_active_(false) +#endif +{ // NOLINT(whitespace/braces) + delegate_.reset(new BrowserWebViewDelegate(this)); + popup_delegate_.reset(new BrowserWebViewDelegate(this)); + nav_controller_.reset(new BrowserNavigationController(this)); + + if (!file_system_root_.CreateUniqueTempDir()) { + LOG(WARNING) << "Failed to create a temp dir for the filesystem." + "FileSystem feature will be disabled."; + DCHECK(file_system_root_.path().empty()); + } + + // Create the singleton main frame reference. + main_frame_ = new CefFrameImpl(this, 0, CefString(), CefString()); +} + +void CefBrowserImpl::CloseBrowser() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_CloseBrowser, this)); +} + +void CefBrowserImpl::GoBack() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleActionView, this, + MENU_ID_NAV_BACK)); +} + +void CefBrowserImpl::GoForward() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleActionView, this, + MENU_ID_NAV_FORWARD)); +} + +void CefBrowserImpl::Reload() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleActionView, this, + MENU_ID_NAV_RELOAD)); +} + +void CefBrowserImpl::ReloadIgnoreCache() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleActionView, this, + MENU_ID_NAV_RELOAD_NOCACHE)); +} + +void CefBrowserImpl::StopLoad() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleActionView, this, + MENU_ID_NAV_STOP)); +} + +void CefBrowserImpl::SetFocus(bool enable) { + if (CefThread::CurrentlyOn(CefThread::UI)) { + // If SetFocus() is called from inside the OnSetFocus() callback do not re- + // enter the callback. + if (enable && !is_in_onsetfocus_) { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) { + CefRefPtr client = GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetFocusHandler(); + if (handler.get()) { + is_in_onsetfocus_ = true; + bool handled = handler->OnSetFocus(this, FOCUS_SOURCE_SYSTEM); + is_in_onsetfocus_ = false; + + if (handled) + return; + } + } + } + } + + UIT_SetFocus(UIT_GetWebViewHost(), enable); + } else { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::SetFocus, this, enable)); + } +} + +CefRefPtr CefBrowserImpl::GetMainFrame() { + return GetMainCefFrame(0, GURL()).get(); +} + +CefRefPtr CefBrowserImpl::GetFocusedFrame() { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + WebView* view = UIT_GetWebView(); + return view ? UIT_GetCefFrame(view->focusedFrame()) : NULL; +} + +CefRefPtr CefBrowserImpl::GetFrame(const CefString& name) { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + WebView* view = UIT_GetWebView(); + if (!view) + return NULL; + + WebFrame* frame = view->findFrameByName(string16(name)); + if (frame) + return UIT_GetCefFrame(frame); + return NULL; +} + +void CefBrowserImpl::GetFrameNames(std::vector& names) { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return; + } + + WebView* view = UIT_GetWebView(); + if (!view) + return; + + WebFrame* main_frame = view->mainFrame(); + WebFrame* it = main_frame; + do { + if (it != main_frame) { + string16 str = it->name(); + names.push_back(str); + } + it = it->traverseNext(true); + } while (it != main_frame); +} + +void CefBrowserImpl::Find(int identifier, const CefString& searchText, + bool forward, bool matchCase, bool findNext) { + WebKit::WebFindOptions options; + options.forward = forward; + options.matchCase = matchCase; + options.findNext = findNext; + + // Execute the request on the UI thread. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_Find, this, identifier, searchText, + options)); +} + +void CefBrowserImpl::StopFinding(bool clearSelection) { + // Execute the request on the UI thread. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_StopFinding, this, clearSelection)); +} + +void CefBrowserImpl::SetZoomLevel(double zoomLevel) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SetZoomLevel, this, zoomLevel)); +} + +void CefBrowserImpl::ClearHistory() { + if (CefThread::CurrentlyOn(CefThread::UI)) { + bool old_can_go_back = !nav_controller_->IsAtStart(); + bool old_can_go_forward = !nav_controller_->IsAtEnd(); + nav_controller_->Reset(); + + if (old_can_go_back || old_can_go_forward) { + set_nav_state(false, false); + if (client_.get()) { + CefRefPtr handler = client_->GetDisplayHandler(); + if (handler.get()) { + // Notify the handler of a navigation state change + handler->OnNavStateChange(this, false, false); + } + } + } + } else { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::ClearHistory, this)); + } +} + +void CefBrowserImpl::ShowDevTools() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_ShowDevTools, this)); +} + +void CefBrowserImpl::CloseDevTools() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_CloseDevTools, this)); +} + +bool CefBrowserImpl::GetSize(PaintElementType type, int& width, int& height) { + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + width = height = 0; + + if (type == PET_VIEW) { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) { + host->GetSize(width, height); + return true; + } + } else if (type == PET_POPUP) { + if (popuphost_) { + popuphost_->GetSize(width, height); + return true; + } + } + + return false; +} + +void CefBrowserImpl::SetSize(PaintElementType type, int width, int height) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SetSize, this, type, width, height)); +} + +bool CefBrowserImpl::IsPopupVisible() { + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + return (popuphost_ != NULL); +} + +void CefBrowserImpl::HidePopup() { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_ClosePopupWidget, this)); +} + +void CefBrowserImpl::Invalidate(const CefRect& dirtyRect) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_Invalidate, this, dirtyRect)); +} + +bool CefBrowserImpl::GetImage(PaintElementType type, int width, int height, + void* buffer) { + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + if (type == PET_VIEW) { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + return host->GetImage(width, height, buffer); + } else if (type == PET_POPUP) { + if (popuphost_) + return popuphost_->GetImage(width, height, buffer); + } + + return false; +} + +void CefBrowserImpl::SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, + int modifiers) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SendKeyEvent, this, type, keyInfo, + modifiers)); +} + +void CefBrowserImpl::SendMouseClickEvent(int x, int y, MouseButtonType type, + bool mouseUp, int clickCount) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SendMouseClickEvent, this, x, y, type, + mouseUp, clickCount)); +} + +void CefBrowserImpl::SendMouseMoveEvent(int x, int y, bool mouseLeave) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SendMouseMoveEvent, this, x, y, + mouseLeave)); +} + +void CefBrowserImpl::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SendMouseWheelEvent, this, x, y, deltaX, + deltaY)); +} + +void CefBrowserImpl::SendFocusEvent(bool setFocus) { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SendFocusEvent, this, setFocus)); +} + +void CefBrowserImpl::SendCaptureLostEvent() { + // Intentially post event tasks in all cases so that painting tasks can be + // handled at sane times. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_SendCaptureLostEvent, this)); +} + +void CefBrowserImpl::Undo(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_UNDO, frame)); +} + +void CefBrowserImpl::Redo(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_REDO, frame)); +} + +void CefBrowserImpl::Cut(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_CUT, frame)); +} + +void CefBrowserImpl::Copy(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_COPY, frame)); +} + +void CefBrowserImpl::Paste(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_PASTE, + frame)); +} + +void CefBrowserImpl::Delete(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_DELETE, + frame)); +} + +void CefBrowserImpl::SelectAll(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_SELECTALL, + frame)); +} + + +void CefBrowserImpl::Print(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_PRINT, + frame)); +} + +void CefBrowserImpl::ViewSource(CefRefPtr frame) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_HandleAction, this, MENU_ID_VIEWSOURCE, + frame)); +} + +CefString CefBrowserImpl::GetSource(CefRefPtr frame) { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return CefString(); + } + + // Retrieve the document string directly + WebKit::WebFrame* web_frame = UIT_GetWebFrame(frame); + if (web_frame) + return string16(web_frame->contentAsMarkup()); + return CefString(); +} + +CefString CefBrowserImpl::GetText(CefRefPtr frame) { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return CefString(); + } + + // Retrieve the document text directly + WebKit::WebFrame* web_frame = UIT_GetWebFrame(frame); + if (web_frame) + return webkit_glue::DumpDocumentText(web_frame); + return CefString(); +} + +void CefBrowserImpl::LoadRequest(CefRefPtr frame, + CefRefPtr request) { + DCHECK(request.get() != NULL); + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_LoadURLForRequestRef, this, frame, + request)); +} + +void CefBrowserImpl::LoadURL(CefRefPtr frame, + const CefString& url) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_LoadURL, this, frame, url)); +} + +void CefBrowserImpl::LoadString(CefRefPtr frame, + const CefString& string, + const CefString& url) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_LoadHTML, this, frame, string, url)); +} + +void CefBrowserImpl::LoadStream(CefRefPtr frame, + CefRefPtr stream, + const CefString& url) { + DCHECK(stream.get() != NULL); + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_LoadHTMLForStreamRef, this, frame, stream, + url)); +} + +void CefBrowserImpl::ExecuteJavaScript(CefRefPtr frame, + const CefString& jsCode, + const CefString& scriptUrl, + int startLine) { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_ExecuteJavaScript, this, frame, jsCode, + scriptUrl, startLine)); +} + +CefRefPtr CefBrowserImpl::GetParent(CefRefPtr frame) { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + WebFrame* web_frame = UIT_GetWebFrame(frame); + if (web_frame) { + if (web_frame->parent() == NULL) { + // This is the main frame. + return NULL; + } + return UIT_GetCefFrame(web_frame->parent()); + } + return NULL; +} + +CefRefPtr CefBrowserImpl::GetCefFrame(int64 id) { + AutoLock lock_scope(this); + FrameMap::const_iterator it = frames_.find(id); + if (it != frames_.end()) + return it->second; + + return NULL; +} + +CefRefPtr CefBrowserImpl::GetOrCreateCefFrame( + int64 id, + const CefString& name, + const GURL& url) { + CefRefPtr cef_frame; + + if (name.empty()) { + // Use the single main frame reference. + cef_frame = GetMainCefFrame(id, url); + } else { + // Locate or create the appropriate named reference. + AutoLock lock_scope(this); + FrameMap::const_iterator it = frames_.find(id); + if (it != frames_.end()) { + cef_frame = it->second; + cef_frame->set_url(url.spec()); + } else { + cef_frame = new CefFrameImpl(this, id, name, url.spec()); + frames_.insert(std::make_pair(id, cef_frame.get())); + } + } + + return cef_frame; +} + +void CefBrowserImpl::RemoveCefFrame(int64 id) { + AutoLock lock_scope(this); + // Remove the appropriate reference. + FrameMap::iterator it = frames_.find(id); + if (it != frames_.end()) + frames_.erase(it); +} + +CefRefPtr CefBrowserImpl::GetMainCefFrame(int64 id, + const GURL& url) { + if (id != 0) + main_frame_->set_id(id); + + if (!url.is_empty()) + main_frame_->set_url(url.spec()); + + return main_frame_; +} + +CefRefPtr CefBrowserImpl::UIT_GetCefFrame(WebFrame* frame) { + REQUIRE_UIT(); + + CefRefPtr cef_frame; + GURL url = frame->document().url(); + + if (frame->parent() == 0) { + // Use the single main frame reference. + cef_frame = GetMainCefFrame(frame->identifier(), url); + } else { + // Locate or create the appropriate reference. + CefString name = string16(frame->name()); + DCHECK(!name.empty()); + cef_frame = GetOrCreateCefFrame(frame->identifier(), name, url); + } + + return cef_frame.get(); +} + +void CefBrowserImpl::UIT_UpdateCefFrame(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + GURL url = frame->document().url(); + + if (frame->parent() == 0) { + // Update the single main frame reference. + GetMainCefFrame(frame->identifier(), url); + } else { + // Update the appropriate reference if it currently exists. + CefRefPtr cef_frame = GetCefFrame(frame->identifier()); + if (cef_frame.get()) + cef_frame->set_url(url.spec()); + } +} + +WebFrame* CefBrowserImpl::UIT_GetMainWebFrame() { + REQUIRE_UIT(); + + WebView* view = UIT_GetWebView(); + if (view) + return view ->mainFrame(); + return NULL; +} + +WebFrame* CefBrowserImpl::UIT_GetWebFrame(CefRefPtr frame) { + REQUIRE_UIT(); + + WebView* view = UIT_GetWebView(); + if (!view) + return NULL; + + CefString name = frame->GetName(); + if (name.empty()) + return view ->mainFrame(); + return view ->findFrameByName(string16(name)); +} + +void CefBrowserImpl::UIT_DestroyBrowser() { + if (client_.get()) { + CefRefPtr handler = client_->GetLifeSpanHandler(); + if (handler.get()) { + // Notify the handler that the window is about to be closed. + handler->OnBeforeClose(this); + } + } + +#if defined(OS_WIN) + if (is_modal_) { + // Exit our own internal modal message loop now. + if (internal_modal_message_loop_is_active_) { + MessageLoop* message_loop = MessageLoop::current(); + message_loop->QuitNow(); + } + } + + UIT_GetWebViewDelegate()->RevokeDragDrop(); +#endif + + // If the current browser window is a dev tools client then disconnect from + // the agent and destroy the client before destroying the window. + UIT_DestroyDevToolsClient(); + + if (dev_tools_agent_.get()) { + BrowserDevToolsClient* client = dev_tools_agent_->client(); + if (client) { + CefBrowserImpl* browser = client->browser(); + // Destroy the client before freeing the agent. + browser->UIT_DestroyDevToolsClient(); + if (!_Context->shutting_down()) { + // Explicitly close the client browser window. + browser->UIT_CloseBrowser(); + } + } + // Free the agent. + dev_tools_agent_.reset(); + } + + // Clean up anything associated with the WebViewHost widget. + if (webviewhost_.get()) { + if (webviewhost_->webwidget()) + webviewhost_->webwidget()->close(); + webviewhost_.reset(); + } + + // Remove the reference to the window handle. + UIT_ClearMainWndHandle(); + + main_frame_ = NULL; + + // Delete the proxy on the IO thread. + CefThread::DeleteSoon(CefThread::IO, FROM_HERE, + request_context_proxy_.release()); + + // Remove the reference added in UIT_CreateBrowser(). + Release(); + + // Remove the browser from the list maintained by the context. + _Context->RemoveBrowser(this); +} + +void CefBrowserImpl::UIT_CloseBrowser() { + REQUIRE_UIT(); + if (IsWindowRenderingDisabled()) { + UIT_DestroyBrowser(); + } else { + gfx::NativeView view = UIT_GetMainWndHandle(); + if (view) + UIT_CloseView(view); + } +} + +void CefBrowserImpl::UIT_LoadURL(CefRefPtr frame, + const CefString& url) { + UIT_LoadURLForRequest(frame, url, CefString(), WebHTTPBody(), + CefRequest::HeaderMap()); +} + +void CefBrowserImpl::UIT_LoadURLForRequestRef(CefRefPtr frame, + CefRefPtr request) { + CefString url = request->GetURL(); + CefString method = request->GetMethod(); + + CefRequestImpl* impl = static_cast(request.get()); + + WebHTTPBody upload_data; + CefRefPtr postdata = impl->GetPostData(); + if (postdata.get()) { + upload_data.initialize(); + static_cast(postdata.get())->Get(upload_data); + } + + CefRequest::HeaderMap headers; + impl->GetHeaderMap(headers); + + UIT_LoadURLForRequest(frame, url, method, upload_data, headers); +} + +void CefBrowserImpl::UIT_LoadURLForRequest(CefRefPtr frame, + const CefString& url, + const CefString& method, + const WebKit::WebHTTPBody& upload_data, + const CefRequest::HeaderMap& headers) { + REQUIRE_UIT(); + + if (url.empty()) + return; + + std::string urlStr(url); + GURL gurl = GURL(urlStr); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + std::string new_url = std::string("http://") + urlStr; + gurl = GURL(new_url); + if (!gurl.is_valid()) + return; + } + + nav_controller_->LoadEntry( + new BrowserNavigationEntry(-1, gurl, CefString(), frame->GetName(), + method, upload_data, headers)); +} + +void CefBrowserImpl::UIT_LoadHTML(CefRefPtr frame, + const CefString& html, + const CefString& url) { + REQUIRE_UIT(); + + std::string urlStr(url); + GURL gurl = GURL(urlStr); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + std::string new_url = std::string("http://") + urlStr; + gurl = GURL(new_url); + if (!gurl.is_valid()) + return; + } + + WebFrame* web_frame = UIT_GetWebFrame(frame); + if (web_frame) + web_frame->loadHTMLString(std::string(html), gurl); +} + +void CefBrowserImpl::UIT_LoadHTMLForStreamRef(CefRefPtr frame, + CefRefPtr stream, + const CefString& url) { + REQUIRE_UIT(); + + std::string urlStr(url); + GURL gurl = GURL(urlStr); + + if (!gurl.is_valid() && !gurl.has_scheme()) { + // Try to add "http://" at the beginning + std::string new_url = std::string("http://") + urlStr; + gurl = GURL(new_url); + if (!gurl.is_valid()) + return; + } + + // read all of the stream data into a std::string. + std::stringstream ss; + char buff[BUFFER_SIZE]; + size_t read; + do { + read = stream->Read(buff, sizeof(char), BUFFER_SIZE-1); + if (read > 0) { + buff[read] = 0; + ss << buff; + } + } + while (read > 0); + + WebFrame* web_frame = UIT_GetWebFrame(frame); + if (web_frame) + web_frame->loadHTMLString(ss.str(), gurl); +} + +void CefBrowserImpl::UIT_ExecuteJavaScript(CefRefPtr frame, + const CefString& js_code, + const CefString& script_url, + int start_line) { + REQUIRE_UIT(); + + WebFrame* web_frame = UIT_GetWebFrame(frame); + if (web_frame) { + web_frame->executeScript(WebScriptSource(string16(js_code), + WebURL(GURL(std::string(script_url))), start_line)); + } +} + +void CefBrowserImpl::UIT_GoBackOrForward(int offset) { + REQUIRE_UIT(); + nav_controller_->GoToOffset(offset); +} + +void CefBrowserImpl::UIT_Reload(bool ignoreCache) { + REQUIRE_UIT(); + nav_controller_->Reload(ignoreCache); +} + +bool CefBrowserImpl::UIT_Navigate(const BrowserNavigationEntry& entry, + bool reload, + bool ignoreCache) { + REQUIRE_UIT(); + + WebView* view = UIT_GetWebView(); + if (!view) + return false; + + // Get the right target frame for the entry. + WebFrame* frame; + if (!entry.GetTargetFrame().empty()) + frame = view->findFrameByName(string16(entry.GetTargetFrame())); + else + frame = view->mainFrame(); + + // TODO(mpcomplete): should we clear the target frame, or should + // back/forward navigations maintain the target frame? + + // A navigation resulting from loading a javascript URL should not be + // treated as a browser initiated event. Instead, we want it to look as if + // the page initiated any load resulting from JS execution. + if (!entry.GetURL().SchemeIs("javascript")) { + delegate_->set_pending_extra_data( + new BrowserExtraData(entry.GetPageID())); + } + + // If we are reloading, then WebKit will use the state of the current page. + // Otherwise, we give it the state to navigate to. + if (reload) { + frame->reload(ignoreCache); + } else if (!entry.GetContentState().empty()) { + DCHECK_NE(entry.GetPageID(), -1); + frame->loadHistoryItem( + webkit_glue::HistoryItemFromString(entry.GetContentState())); + } else { + DCHECK_EQ(entry.GetPageID(), -1); + WebURLRequest request(entry.GetURL()); + + if (entry.GetMethod().length() > 0) + request.setHTTPMethod(string16(entry.GetMethod())); + + if (entry.GetHeaders().size() > 0) + CefRequestImpl::SetHeaderMap(entry.GetHeaders(), request); + + if (!entry.GetUploadData().isNull()) { + string16 method = request.httpMethod(); + if (method == ASCIIToUTF16("GET") || method == ASCIIToUTF16("HEAD")) + request.setHTTPMethod(ASCIIToUTF16("POST")); + + if (request.httpHeaderField(ASCIIToUTF16("Content-Type")).length() == 0) { + request.setHTTPHeaderField( + ASCIIToUTF16("Content-Type"), + ASCIIToUTF16("application/x-www-form-urlencoded")); + } + request.setHTTPBody(entry.GetUploadData()); + } + + frame->loadRequest(request); + } + + // In case LoadRequest failed before DidCreateDataSource was called. + delegate_->set_pending_extra_data(NULL); + + if (client_.get()) { + CefRefPtr handler = client_->GetFocusHandler(); + if (!handler.get() || + (handler.get() && + !handler->OnSetFocus(this, FOCUS_SOURCE_NAVIGATION))) { + // Restore focus to the main frame prior to loading new request. + // This makes sure that we don't have a focused iframe. Otherwise, that + // iframe would keep focus when the SetFocus called immediately after + // LoadRequest, thus making some tests fail (see http://b/issue?id=845337 + // for more details). + // TODO(cef): The above comment may be wrong, or the below call to + // setFocusedFrame() may be unnecessary or in the wrong place. See this + // thread for additional details: + // http://groups.google.com/group/chromium-dev/browse_thread/thread/42bcd31b59e3a168 + view->setFocusedFrame(frame); + + // Give focus to the window if it is currently visible. + if (!IsWindowRenderingDisabled() && + UIT_IsViewVisible(UIT_GetMainWndHandle())) + UIT_SetFocus(UIT_GetWebViewHost(), true); + } + } + + return true; +} + +void CefBrowserImpl::UIT_SetSize(PaintElementType type, int width, int height) { + if (type == PET_VIEW) { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SetSize(width, height); + } else if (type == PET_POPUP) { + if (popuphost_) + popuphost_->SetSize(width, height); + } +} + +void CefBrowserImpl::UIT_Invalidate(const CefRect& dirtyRect) { + REQUIRE_UIT(); + WebViewHost* host = UIT_GetWebViewHost(); + if (host) { + gfx::Rect rect(dirtyRect.x, dirtyRect.y, dirtyRect.width, + dirtyRect.height); + + // Used when window rendering is disabled to send the specified region to + // the paint delegate when WebWidget::Paint() is next called. + host->UpdateRedrawRect(rect); + + // Cause WebWidget::Paint() to be called when next appropriate. + host->InvalidateRect(rect); + } +} + +void CefBrowserImpl::UIT_SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, + int modifiers) { + REQUIRE_UIT(); + if (popuphost_) { + // Send the event to the popup. + popuphost_->SendKeyEvent(type, keyInfo, modifiers); + } else { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SendKeyEvent(type, keyInfo, modifiers); + } +} + +void CefBrowserImpl::UIT_SendMouseClickEvent(int x, int y, MouseButtonType type, + bool mouseUp, int clickCount) { + REQUIRE_UIT(); + if (popuphost_ && popup_rect_.Contains(x, y)) { + // Send the event to the popup. + popuphost_->SendMouseClickEvent(x - popup_rect_.x(), y - popup_rect_.y(), + type, mouseUp, clickCount); + } else { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SendMouseClickEvent(x, y, type, mouseUp, clickCount); + } +} + +void CefBrowserImpl::UIT_SendMouseMoveEvent(int x, int y, bool mouseLeave) { + REQUIRE_UIT(); + if (popuphost_ && popup_rect_.Contains(x, y)) { + // Send the event to the popup. + popuphost_->SendMouseMoveEvent(x - popup_rect_.x(), y - popup_rect_.y(), + mouseLeave); + } else { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SendMouseMoveEvent(x, y, mouseLeave); + } +} + +void CefBrowserImpl::UIT_SendMouseWheelEvent(int x, int y, int deltaX, + int deltaY) { + REQUIRE_UIT(); + if (popuphost_ && popup_rect_.Contains(x, y)) { + // Send the event to the popup. + popuphost_->SendMouseWheelEvent(x - popup_rect_.x(), y - popup_rect_.y(), + deltaX, deltaY); + } else { + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SendMouseWheelEvent(x, y, deltaX, deltaY); + } +} + +void CefBrowserImpl::UIT_SendFocusEvent(bool setFocus) { + REQUIRE_UIT(); + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SendFocusEvent(setFocus); +} + +void CefBrowserImpl::UIT_SendCaptureLostEvent() { + REQUIRE_UIT(); + WebViewHost* host = UIT_GetWebViewHost(); + if (host) + host->SendCaptureLostEvent(); +} + +CefRefPtr CefBrowserImpl::UIT_CreatePopupWindow( + const CefString& url, const CefPopupFeatures& features) { + REQUIRE_UIT(); + + CefWindowInfo info; +#if defined(OS_WIN) + info.SetAsPopup(NULL, CefString()); +#endif + +#if (defined(OS_WIN) || defined(OS_MACOSX)) + // Default to the size from the popup features. + if (features.xSet) + info.m_x = features.x; + if (features.ySet) + info.m_y = features.y; + if (features.widthSet) + info.m_nWidth = features.width; + if (features.heightSet) + info.m_nHeight = features.height; +#endif + + CefRefPtr client = client_; + + // Start with the current browser window's settings. + CefBrowserSettings settings(settings_); + + if (client_.get()) { + CefRefPtr handler = client_->GetLifeSpanHandler(); + // Give the handler an opportunity to modify window attributes, handler, + // or cancel the window creation. + if (handler.get() && + handler->OnBeforePopup(this, features, info, url, client, settings)) { + return NULL; + } + } + + // Modal windows need to know which window is being suspended (the opener) + // so that it can be disabled while the modal window is open. + CefRefPtr browser( + new CefBrowserImpl(info, settings, UIT_GetMainWndHandle(), client)); + + // Don't pass the URL to UIT_CreateBrowser for popup windows or the URL will + // be loaded twice. + if (!browser->UIT_CreateBrowser(CefString())) + return NULL; + + return browser; +} + +WebKit::WebWidget* CefBrowserImpl::UIT_CreatePopupWidget() { + REQUIRE_UIT(); + + DCHECK(!popuphost_); + popuphost_ = WebWidgetHost::Create( + (IsWindowRenderingDisabled()?NULL:UIT_GetMainWndHandle()), + popup_delegate_.get(), paint_delegate_.get()); + popuphost_->set_popup(true); + + return popuphost_->webwidget(); +} + +void CefBrowserImpl::UIT_ClosePopupWidget() { + REQUIRE_UIT(); + + if (!popuphost_) + return; + +#if !defined(OS_MACOSX) + // Mac uses a WebPopupMenu for select lists so no closing is necessary. + if (!IsWindowRenderingDisabled()) + UIT_CloseView(UIT_GetPopupWndHandle()); +#endif + popuphost_ = NULL; + popup_rect_ = gfx::Rect(); + + if (IsWindowRenderingDisabled() && client_.get()) { + CefRefPtr handler = client_->GetRenderHandler(); + if (handler.get()) { + // Notify the handler of popup visibility change. + handler->OnPopupShow(this, false); + } + } +} + +void CefBrowserImpl::UIT_Show(WebKit::WebNavigationPolicy policy) { + REQUIRE_UIT(); + delegate_->show(policy); +} + +void CefBrowserImpl::UIT_HandleActionView(cef_menu_id_t menuId) { + return UIT_HandleAction(menuId, NULL); +} + +void CefBrowserImpl::UIT_HandleAction(cef_menu_id_t menuId, + CefRefPtr frame) { + REQUIRE_UIT(); + + WebFrame* web_frame = NULL; + if (frame) + web_frame = UIT_GetWebFrame(frame); + + switch (menuId) { + case MENU_ID_NAV_BACK: + UIT_GoBackOrForward(-1); + break; + case MENU_ID_NAV_FORWARD: + UIT_GoBackOrForward(1); + break; + case MENU_ID_NAV_RELOAD: + UIT_Reload(false); + break; + case MENU_ID_NAV_RELOAD_NOCACHE: + UIT_Reload(true); + break; + case MENU_ID_NAV_STOP: + if (UIT_GetWebView()) + UIT_GetWebView()->mainFrame()->stopLoading(); + break; + case MENU_ID_UNDO: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("Undo")); + break; + case MENU_ID_REDO: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("Redo")); + break; + case MENU_ID_CUT: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("Cut")); + break; + case MENU_ID_COPY: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("Copy")); + break; + case MENU_ID_PASTE: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("Paste")); + break; + case MENU_ID_DELETE: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("Delete")); + break; + case MENU_ID_SELECTALL: + if (web_frame) + web_frame->executeCommand(WebString::fromUTF8("SelectAll")); + break; + case MENU_ID_PRINT: + if (web_frame) + UIT_PrintPages(web_frame); + break; + case MENU_ID_VIEWSOURCE: + if (web_frame) + UIT_ViewDocumentString(web_frame); + break; + } +} + +void CefBrowserImpl::UIT_Find(int identifier, const CefString& search_text, + const WebKit::WebFindOptions& options) { + WebView* view = UIT_GetWebView(); + if (!view) + return; + + WebFrame* main_frame = view->mainFrame(); + string16 searchText(search_text); + + if (main_frame->document().isPluginDocument()) { + WebPlugin* plugin = main_frame->document().to().plugin(); + if (plugin) { + if (options.findNext) { + // Just navigate back/forward. + plugin->selectFindResult(options.forward); + } else { + if (plugin->startFind(searchText, options.matchCase, identifier)) { + } else { + // No find results. + UIT_NotifyFindStatus(identifier, 0, gfx::Rect(), 0, true); + } + } + return; + } + } + + WebFrame* frame_after_main = main_frame->traverseNext(true); + WebFrame* focused_frame = view->focusedFrame(); + WebFrame* search_frame = focused_frame; // start searching focused frame. + + bool multi_frame = (frame_after_main != main_frame); + + // If we have multiple frames, we don't want to wrap the search within the + // frame, so we check here if we only have main_frame in the chain. + bool wrap_within_frame = !multi_frame; + + WebRect selection_rect; + bool result = false; + + // If something is selected when we start searching it means we cannot just + // increment the current match ordinal; we need to re-generate it. + WebRange current_selection = focused_frame->selectionRange(); + + do { + result = search_frame->find(identifier, searchText, options, + wrap_within_frame, &selection_rect); + + if (!result) { + // don't leave text selected as you move to the next frame. + search_frame->executeCommand(WebString::fromUTF8("Unselect")); + + // Find the next frame, but skip the invisible ones. + do { + // What is the next frame to search? (we might be going backwards). Note + // that we specify wrap=true so that search_frame never becomes NULL. + search_frame = options.forward ? + search_frame->traverseNext(true) : + search_frame->traversePrevious(true); + } while (!search_frame->hasVisibleContent() && + search_frame != focused_frame); + + // Make sure selection doesn't affect the search operation in new frame. + search_frame->executeCommand(WebString::fromUTF8("Unselect")); + + // If we have multiple frames and we have wrapped back around to the + // focused frame, we need to search it once more allowing wrap within + // the frame, otherwise it will report 'no match' if the focused frame has + // reported matches, but no frames after the focused_frame contain a + // match for the search word(s). + if (multi_frame && search_frame == focused_frame) { + result = search_frame->find( + identifier, searchText, + options, true, // Force wrapping. + &selection_rect); + } + } + + view->setFocusedFrame(search_frame); + } while (!result && search_frame != focused_frame); + + if (options.findNext && current_selection.isNull()) { + // Force the main_frame to report the actual count. + main_frame->increaseMatchCount(0, identifier); + } else { + // If nothing is found, set result to "0 of 0", otherwise, set it to + // "-1 of 1" to indicate that we found at least one item, but we don't know + // yet what is active. + int ordinal = result ? -1 : 0; // -1 here means, we might know more later. + int match_count = result ? 1 : 0; // 1 here means possibly more coming. + + // If we find no matches then this will be our last status update. + // Otherwise the scoping effort will send more results. + bool final_status_update = !result; + + // Send the search result. + UIT_NotifyFindStatus(identifier, match_count, selection_rect, ordinal, + final_status_update); + + // Scoping effort begins, starting with the mainframe. + search_frame = main_frame; + + main_frame->resetMatchCount(); + + do { + // Cancel all old scoping requests before starting a new one. + search_frame->cancelPendingScopingEffort(); + + // We don't start another scoping effort unless at least one match has + // been found. + if (result) { + // Start new scoping request. If the scoping function determines that it + // needs to scope, it will defer until later. + search_frame->scopeStringMatches(identifier, searchText, options, + true); // reset the tickmarks + } + + // Iterate to the next frame. The frame will not necessarily scope, for + // example if it is not visible. + search_frame = search_frame->traverseNext(true); + } while (search_frame != main_frame); + } +} + +void CefBrowserImpl::UIT_StopFinding(bool clear_selection) { + WebView* view = UIT_GetWebView(); + if (!view) + return; + + WebDocument doc = view->mainFrame()->document(); + if (doc.isPluginDocument()) { + WebPlugin* plugin = + view->mainFrame()->document().to().plugin(); + if (plugin) + plugin->stopFind(); + return; + } + + if (clear_selection) + view->focusedFrame()->executeCommand(WebString::fromUTF8("Unselect")); + + WebFrame* frame = view->mainFrame(); + while (frame) { + frame->stopFinding(clear_selection); + frame = frame->traverseNext(false); + } +} + +void CefBrowserImpl::UIT_NotifyFindStatus(int identifier, int count, + const WebKit::WebRect& 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, identifier, count, rect, active_match_ordinal, + final_update); + } + } +} + +void CefBrowserImpl::UIT_SetZoomLevel(double zoomLevel) { + REQUIRE_UIT(); + WebKit::WebFrame* web_frame = UIT_GetMainWebFrame(); + if (web_frame) { + web_frame->view()->setZoomLevel(false, zoomLevel); + ZoomMap::GetInstance()->set(web_frame->document().url(), zoomLevel); + set_zoom_level(zoomLevel); + } +} + +void CefBrowserImpl::UIT_ShowDevTools() { + REQUIRE_UIT(); + + if (!dev_tools_agent_.get()) + return; + + BrowserDevToolsClient* client = dev_tools_agent_->client(); + if (!client) { + // Create the inspector window. + CefString url(base::StringPrintf( + "%sdevtools.html?docked=false&toolbarColor=rgba(223,223,223,1)&" + "textColor=rgba(18,50,114,1)", + kChromeDevToolsURL)); + + CefPopupFeatures features; + CefRefPtr browser = UIT_CreatePopupWindow(url, features); + if (browser.get()) { + browser->UIT_CreateDevToolsClient(dev_tools_agent_.get()); + browser->UIT_LoadURL(browser->GetMainFrame(), url); + browser->UIT_Show(WebKit::WebNavigationPolicyNewWindow); + } + } else { + // Give focus to the existing inspector window. + client->browser()->UIT_Show(WebKit::WebNavigationPolicyNewWindow); + } +} + +void CefBrowserImpl::UIT_CloseDevTools() { + REQUIRE_UIT(); + + if (!dev_tools_agent_.get()) + return; + + BrowserDevToolsClient* client = dev_tools_agent_->client(); + if (client) + client->browser()->UIT_CloseBrowser(); +} + +void CefBrowserImpl::UIT_VisitDOM(CefRefPtr frame, + CefRefPtr visitor) { + REQUIRE_UIT(); + + WebKit::WebFrame* web_frame = UIT_GetWebFrame(frame); + if (!web_frame) + return; + + // Create a CefDOMDocumentImpl object that is valid only for the scope of this + // method. + CefRefPtr documentImpl; + const WebKit::WebDocument& document = web_frame->document(); + if (!document.isNull()) + documentImpl = new CefDOMDocumentImpl(this, web_frame); + + visitor->Visit(documentImpl.get()); + + if (documentImpl.get()) + documentImpl->Detach(); +} + +void CefBrowserImpl::UIT_AddFrameObject(WebKit::WebFrame* frame, + CefTrackNode* tracked_object) { + REQUIRE_UIT(); + + CefRefPtr manager; + + if (!frame_objects_.empty()) { + FrameObjectMap::const_iterator it = frame_objects_.find(frame); + if (it != frame_objects_.end()) + manager = it->second; + } + + if (!manager.get()) { + manager = new CefTrackManager(); + frame_objects_.insert(std::make_pair(frame, manager)); + } + + manager->Add(tracked_object); +} + +void CefBrowserImpl::UIT_BeforeFrameClosed(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + if (!frame_objects_.empty()) { + // Remove any tracked objects associated with the frame. + FrameObjectMap::iterator it = frame_objects_.find(frame); + if (it != frame_objects_.end()) + frame_objects_.erase(it); + } +} + +void CefBrowserImpl::set_zoom_level(double zoomLevel) { + AutoLock lock_scope(this); + zoom_level_ = zoomLevel; +} + +double CefBrowserImpl::zoom_level() { + AutoLock lock_scope(this); + return zoom_level_; +} + +void CefBrowserImpl::set_nav_state(bool can_go_back, bool can_go_forward) { + AutoLock lock_scope(this); + can_go_back_ = can_go_back; + can_go_forward_ = can_go_forward; +} + +bool CefBrowserImpl::can_go_back() { + AutoLock lock_scope(this); + return can_go_back_; +} + +bool CefBrowserImpl::can_go_forward() { + AutoLock lock_scope(this); + return can_go_forward_; +} + +void CefBrowserImpl::set_has_document(bool has_document) { + AutoLock lock_scope(this); + has_document_ = has_document; +} + +bool CefBrowserImpl::has_document() { + AutoLock lock_scope(this); + return has_document_; +} + +void CefBrowserImpl::set_pending_url(const GURL& url) { + AutoLock lock_scope(this); + pending_url_ = url; +} + +GURL CefBrowserImpl::pending_url() { + AutoLock lock_scope(this); + return pending_url_; +} + +net::URLRequestContext* CefBrowserImpl::request_context_proxy() { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (!request_context_proxy_.get()) { + request_context_proxy_.reset( + new BrowserRequestContextProxy(_Context->request_context(), this)); + } + return request_context_proxy_.get(); +} + +void CefBrowserImpl::UIT_CreateDevToolsClient(BrowserDevToolsAgent *agent) { + dev_tools_client_.reset(new BrowserDevToolsClient(this, agent)); +} + +void CefBrowserImpl::UIT_DestroyDevToolsClient() { + if (dev_tools_client_.get()) { + // Free the client. This will cause the client to clear pending messages + // and detach from the agent. + dev_tools_client_.reset(); + } +} + + +// CefFrameImpl + +CefFrameImpl::CefFrameImpl(CefBrowserImpl* browser, + int64 id, + const CefString& name, + const CefString& url) + : browser_(browser), + name_(name), + id_(id), + url_(url) { +} + +CefFrameImpl::~CefFrameImpl() { + if (!IsMain()) + browser_->RemoveCefFrame(id_); +} + +bool CefFrameImpl::IsFocused() { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return false; + } + + return (browser_->UIT_GetWebView() && + (browser_->UIT_GetWebFrame(this) == + browser_->UIT_GetWebView()->focusedFrame())); +} + +int64 CefFrameImpl::GetIdentifier() { + base::AutoLock lock_scope(lock_); + return id_; +} + +CefString CefFrameImpl::GetURL() { + base::AutoLock lock_scope(lock_); + return url_; +} + +void CefFrameImpl::VisitDOM(CefRefPtr visitor) { + if (!visitor.get()) { + NOTREACHED() << "invalid parameter"; + return; + } + CefRefPtr framePtr(this); + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefBrowserImpl::UIT_VisitDOM, browser_.get(), framePtr, + visitor)); +} + +CefRefPtr CefFrameImpl::GetV8Context() { + // Verify that this method is being called on the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return NULL; + } + + WebKit::WebFrame* frame = browser_->UIT_GetWebFrame(this); + if (frame) { + v8::HandleScope handle_scope; + return new CefV8ContextImpl(webkit_glue::GetV8Context(frame)); + } else { + return NULL; + } +} + +void CefFrameImpl::set_id(int64 id) { + base::AutoLock lock_scope(lock_); + id_ = id; +} + +void CefFrameImpl::set_url(const CefString& url) { + base::AutoLock lock_scope(lock_); + url_ = url; +} diff --git a/cef1/libcef/browser_impl.h b/cef1/libcef/browser_impl.h new file mode 100644 index 000000000..9bfc6dadd --- /dev/null +++ b/cef1/libcef/browser_impl.h @@ -0,0 +1,502 @@ +// Copyright (c) 2012 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. + +#ifndef CEF_LIBCEF_BROWSER_IMPL_H_ +#define CEF_LIBCEF_BROWSER_IMPL_H_ +#pragma once + +#include +#include +#include + +#include "include/cef_browser.h" +#include "include/cef_client.h" +#include "include/cef_frame.h" + +#include "libcef/webview_host.h" +#include "libcef/browser_devtools_agent.h" +#include "libcef/browser_devtools_client.h" +#include "libcef/browser_webview_delegate.h" +#include "libcef/browser_navigation_controller.h" +#include "libcef/browser_request_context_proxy.h" +#include "libcef/cef_thread.h" +#include "libcef/tracker.h" +#if defined(OS_WIN) +#include "libcef/printing/win_printing_context.h" +#endif + +#include "base/scoped_temp_dir.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFindOptions.h" + +namespace base { +class WaitableEvent; +} +namespace WebKit { +class WebView; +} + +class CefFrameImpl; + +#define BUFFER_SIZE 32768 + + +// Implementation of CefBrowser. +class CefBrowserImpl : public CefBrowser { + public: + class PaintDelegate : public WebWidgetHost::PaintDelegate { + public: + explicit PaintDelegate(CefBrowserImpl* browser); + virtual ~PaintDelegate(); + + virtual void Paint(bool popup, const std::vector& dirtyRects, + const void* buffer) OVERRIDE; + + protected: + CefBrowserImpl* browser_; + }; + + CefBrowserImpl(const CefWindowInfo& windowInfo, + const CefBrowserSettings& settings, + gfx::NativeView opener, + CefRefPtr client); + virtual ~CefBrowserImpl() {} + +#if defined(OS_WIN) + static LPCTSTR GetWndClass(); + static LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, + LPARAM lParam); +#endif + + // CefBrowser methods + virtual void CloseBrowser() OVERRIDE; + virtual bool CanGoBack() OVERRIDE { return can_go_back(); } + virtual void GoBack() OVERRIDE; + virtual bool CanGoForward() OVERRIDE { return can_go_forward(); } + virtual void GoForward() OVERRIDE; + virtual void Reload() OVERRIDE; + virtual void ReloadIgnoreCache() OVERRIDE; + virtual void StopLoad() OVERRIDE; + virtual void SetFocus(bool enable) OVERRIDE; + virtual void ParentWindowWillClose() OVERRIDE; + virtual CefWindowHandle GetWindowHandle() OVERRIDE; + virtual CefWindowHandle GetOpenerWindowHandle() OVERRIDE + { return opener_window(); } + virtual bool IsPopup() OVERRIDE { return is_popup(); } + virtual bool HasDocument() OVERRIDE { return has_document(); } + virtual CefRefPtr GetClient() OVERRIDE { return client_; } + virtual CefRefPtr GetMainFrame() OVERRIDE; + virtual CefRefPtr GetFocusedFrame() OVERRIDE; + virtual CefRefPtr GetFrame(const CefString& name) OVERRIDE; + virtual void GetFrameNames(std::vector& names) OVERRIDE; + virtual void Find(int identifier, const CefString& searchText, + bool forward, bool matchCase, bool findNext) OVERRIDE; + virtual void StopFinding(bool clearSelection) OVERRIDE; + virtual double GetZoomLevel() OVERRIDE { return zoom_level(); } + virtual void SetZoomLevel(double zoomLevel) OVERRIDE; + virtual void ClearHistory() OVERRIDE; + virtual void ShowDevTools() OVERRIDE; + virtual void CloseDevTools() OVERRIDE; + virtual bool IsWindowRenderingDisabled() OVERRIDE; + virtual bool GetSize(PaintElementType type, int& width, int& height) OVERRIDE; + virtual void SetSize(PaintElementType type, int width, int height) OVERRIDE; + virtual bool IsPopupVisible() OVERRIDE; + virtual void HidePopup() OVERRIDE; + virtual void Invalidate(const CefRect& dirtyRect) OVERRIDE; + virtual bool GetImage(PaintElementType type, int width, int height, + void* buffer) OVERRIDE; + virtual void SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, + int modifiers) OVERRIDE; + virtual void SendMouseClickEvent(int x, int y, MouseButtonType type, + bool mouseUp, int clickCount) OVERRIDE; + virtual void SendMouseMoveEvent(int x, int y, bool mouseLeave) OVERRIDE; + virtual void SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) + OVERRIDE; + virtual void SendFocusEvent(bool setFocus) OVERRIDE; + virtual void SendCaptureLostEvent() OVERRIDE; + + // Frame-related methods + void Undo(CefRefPtr frame); + void Redo(CefRefPtr frame); + void Cut(CefRefPtr frame); + void Copy(CefRefPtr frame); + void Paste(CefRefPtr frame); + void Delete(CefRefPtr frame); + void SelectAll(CefRefPtr frame); + void Print(CefRefPtr frame); + void ViewSource(CefRefPtr frame); + CefString GetSource(CefRefPtr frame); + CefString GetText(CefRefPtr frame); + void LoadRequest(CefRefPtr frame, + CefRefPtr request); + void LoadURL(CefRefPtr frame, + const CefString& url); + void LoadString(CefRefPtr frame, + const CefString& string, + const CefString& url); + void LoadStream(CefRefPtr frame, + CefRefPtr stream, + const CefString& url); + void ExecuteJavaScript(CefRefPtr frame, + const CefString& jsCode, + const CefString& scriptUrl, + int startLine); + CefRefPtr GetParent(CefRefPtr frame); + + // CefFrames are light-weight objects managed by the browser and loosely + // coupled to a WebFrame object by id. If a CefFrame object does not already + // exist for the specified id one will be created. There is no guarantee that + // the same CefFrame object will be returned across different calls to this + // function. + CefRefPtr GetCefFrame(int64 id); + CefRefPtr GetOrCreateCefFrame(int64 id, const CefString& name, + const GURL& url); + void RemoveCefFrame(int64 id); + CefRefPtr GetMainCefFrame(int64 id, const GURL& url); + + //////////////////////////////////////////////////////////// + // ALL UIT_* METHODS MUST ONLY BE CALLED ON THE UI THREAD // + //////////////////////////////////////////////////////////// + + CefRefPtr UIT_GetCefFrame(WebKit::WebFrame* frame); + void UIT_UpdateCefFrame(WebKit::WebFrame* frame); + + // Return the main WebFrame object. + WebKit::WebFrame* UIT_GetMainWebFrame(); + + // Return the WebFrame object associated with the specified CefFrame. This + // may return NULL if no WebFrame with the CefFrame's name exists. + WebKit::WebFrame* UIT_GetWebFrame(CefRefPtr frame); + + WebKit::WebView* UIT_GetWebView() const { + REQUIRE_UIT(); + return webviewhost_.get() ? webviewhost_->webview() : NULL; + } + WebViewHost* UIT_GetWebViewHost() const { + REQUIRE_UIT(); + return webviewhost_.get(); + } + BrowserWebViewDelegate* UIT_GetWebViewDelegate() const { + REQUIRE_UIT(); + return delegate_.get(); + } + gfx::NativeView UIT_GetWebViewWndHandle() { + REQUIRE_UIT(); + DCHECK(!IsWindowRenderingDisabled()); + return webviewhost_->view_handle(); + } + WebKit::WebWidget* UIT_GetPopup() const { + REQUIRE_UIT(); + return popuphost_ ? popuphost_->webwidget() : NULL; + } + WebWidgetHost* UIT_GetPopupHost() const { + REQUIRE_UIT(); + return popuphost_; + } + BrowserWebViewDelegate* UIT_GetPopupDelegate() const { + REQUIRE_UIT(); + return popup_delegate_.get(); + } + gfx::NativeView UIT_GetPopupWndHandle() { + REQUIRE_UIT(); + DCHECK(!IsWindowRenderingDisabled()); + return popuphost_->view_handle(); + } + gfx::NativeView UIT_GetMainWndHandle(); + void UIT_ClearMainWndHandle(); + + BrowserNavigationController* UIT_GetNavigationController() { + REQUIRE_UIT(); + return nav_controller_.get(); + } + + // Return true to allow user editing such as entering text in form elements + bool UIT_AllowEditing() { return true; } + + bool UIT_IsModal() { + REQUIRE_UIT(); + return is_modal_; + } + void UIT_SetIsModal(bool val) { + REQUIRE_UIT(); + is_modal_ = val; + } + + CefString UIT_GetTitle() { + REQUIRE_UIT(); + return title_; + } + void UIT_SetTitle(const CefString& title) { + REQUIRE_UIT(); + title_ = title; + } + + // Create the native browser window and populate browser members. + bool UIT_CreateBrowser(const CefString& url); + + // Destroy the browser members. This method should only be called after the + // native browser window is not longer processing messages. + void UIT_DestroyBrowser(); + + // Sends a message via the OS to close the native browser window. + // UIT_DestroyBrowser will be called after the native window has closed. + void UIT_CloseBrowser(); + + void UIT_LoadURL(CefRefPtr frame, + const CefString& url); + void UIT_LoadURLForRequest(CefRefPtr frame, + const CefString& url, + const CefString& method, + const WebKit::WebHTTPBody& upload_data, + const CefRequest::HeaderMap& headers); + void UIT_LoadURLForRequestRef(CefRefPtr frame, + CefRefPtr request); + void UIT_LoadHTML(CefRefPtr frame, + const CefString& html, + const CefString& url); + void UIT_LoadHTMLForStreamRef(CefRefPtr frame, + CefRefPtr stream, + const CefString& url); + void UIT_ExecuteJavaScript(CefRefPtr frame, + const CefString& js_code, + const CefString& script_url, + int start_line); + void UIT_GoBackOrForward(int offset); + void UIT_Reload(bool ignoreCache); + bool UIT_Navigate(const BrowserNavigationEntry& entry, + bool reload, + bool ignoreCahce); + void UIT_SetFocus(WebWidgetHost* host, bool enable); + void UIT_SetSize(PaintElementType type, int width, int height); + void UIT_Invalidate(const CefRect& dirtyRect); + void UIT_SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, int modifiers); + void UIT_SendMouseClickEvent(int x, int y, MouseButtonType type, + bool mouseUp, int clickCount); + void UIT_SendMouseMoveEvent(int x, int y, bool mouseLeave); + void UIT_SendMouseWheelEvent(int x, int y, int deltaX, int deltaY); + void UIT_SendFocusEvent(bool setFocus); + void UIT_SendCaptureLostEvent(); + + CefRefPtr UIT_CreatePopupWindow(const CefString& url, + const CefPopupFeatures& features); + WebKit::WebWidget* UIT_CreatePopupWidget(); + void UIT_ClosePopupWidget(); + + void UIT_Show(WebKit::WebNavigationPolicy policy); + + // Handles most simple browser actions + void UIT_HandleActionView(cef_menu_id_t menuId); + void UIT_HandleAction(cef_menu_id_t menuId, CefRefPtr frame); + + // Save the document HTML to a temporary file and open in the default viewing + // application + bool UIT_ViewDocumentString(WebKit::WebFrame *frame); + + bool UIT_CanGoBack() { return !nav_controller_->IsAtStart(); } + bool UIT_CanGoForward() { return !nav_controller_->IsAtEnd(); } + + // Printing support + void UIT_PrintPages(WebKit::WebFrame* frame); + void UIT_PrintPage(int page_number, int total_pages, + const gfx::Size& canvas_size, WebKit::WebFrame* frame); + int UIT_GetPagesCount(WebKit::WebFrame* frame); + + void UIT_SetUniqueID(int id) { unique_id_ = id; } + int UIT_GetUniqueID() { return unique_id_; } + + void UIT_Find(int identifier, const CefString& search_text, + const WebKit::WebFindOptions& options); + void UIT_StopFinding(bool clear_selection); + void UIT_NotifyFindStatus(int identifier, int count, + const WebKit::WebRect& selection_rect, + int active_match_ordinal, bool final_update); + void UIT_SetZoomLevel(double zoomLevel); + void UIT_ShowDevTools(); + void UIT_CloseDevTools(); + + void UIT_VisitDOM(CefRefPtr frame, + CefRefPtr visitor); + + // Frame objects will be deleted immediately before the frame is closed. + void UIT_AddFrameObject(WebKit::WebFrame* frame, + CefTrackNode* tracked_object); + void UIT_BeforeFrameClosed(WebKit::WebFrame* frame); + + // These variables are read-only. + const CefBrowserSettings& settings() const { return settings_; } + const FilePath& file_system_root() const { return file_system_root_.path(); } + gfx::NativeView opener_window() { return opener_; } + bool is_popup() { return (opener_ != NULL); } + + // These variables may be read/written from multiple threads. + void set_zoom_level(double zoomLevel); + double zoom_level(); + void set_nav_state(bool can_go_back, bool can_go_forward); + bool can_go_back(); + bool can_go_forward(); + void set_has_document(bool has_document); + bool has_document(); + + // URL currently being loaded in the main frame. + void set_pending_url(const GURL& url); + GURL pending_url(); + + void set_is_dropping(bool is_dropping) { is_dropping_ = is_dropping; } + bool is_dropping() { return is_dropping_; } + +#if defined(OS_WIN) + void set_opener_was_disabled_by_modal_loop(bool disabled) { + opener_was_disabled_by_modal_loop_ = disabled; + } + void set_internal_modal_message_loop_is_active(bool active) { + internal_modal_message_loop_is_active_ = active; + } +#endif + + void set_popup_rect(const gfx::Rect& rect) { popup_rect_ = rect; } + + net::URLRequestContext* request_context_proxy(); + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + + protected: + static void UIT_CloseView(gfx::NativeView view); + static bool UIT_IsViewVisible(gfx::NativeView view); + + void UIT_CreateDevToolsClient(BrowserDevToolsAgent* agent); + void UIT_DestroyDevToolsClient(); + + CefWindowInfo window_info_; + CefBrowserSettings settings_; + // Handle of the browser window that opened this window. + gfx::NativeView opener_; + bool is_modal_; + CefRefPtr client_; + scoped_ptr webviewhost_; + WebWidgetHost* popuphost_; + gfx::Rect popup_rect_; + scoped_ptr delegate_; + scoped_ptr popup_delegate_; + scoped_ptr nav_controller_; + scoped_ptr paint_delegate_; + + scoped_ptr dev_tools_agent_; + scoped_ptr dev_tools_client_; + + scoped_ptr request_context_proxy_; + + CefString title_; + + double zoom_level_; + bool can_go_back_; + bool can_go_forward_; + bool has_document_; + GURL pending_url_; + + // True if a drop action is occuring. + bool is_dropping_; + + // True if currently in the OnSetFocus callback. Only accessed on the UI + // thread. + bool is_in_onsetfocus_; + +#if defined(OS_WIN) + // Context object used to manage printing. + printing::PrintingContext print_context_; + + // Used to re-enable the opener when a modal window gets closed. + bool opener_was_disabled_by_modal_loop_; + bool internal_modal_message_loop_is_active_; +#endif + + // Map of frame id to reference. + typedef std::map FrameMap; + FrameMap frames_; + + // Singleton main frame reference. + CefRefPtr main_frame_; + + typedef std::map > + FrameObjectMap; + FrameObjectMap frame_objects_; + + // Unique browser ID assigned by the context. + int unique_id_; + + // A temporary directory for FileSystem API. + ScopedTempDir file_system_root_; + + IMPLEMENT_REFCOUNTING(CefBrowserImpl); + IMPLEMENT_LOCKING(CefBrowserImpl); +}; + + +// Implementation of CefFrame. +class CefFrameImpl : public CefFrame { + public: + CefFrameImpl(CefBrowserImpl* browser, + int64 frame_id, + const CefString& name, + const CefString& url); + virtual ~CefFrameImpl(); + + // CefFrame methods + virtual void Undo() OVERRIDE { browser_->Undo(this); } + virtual void Redo() OVERRIDE { browser_->Redo(this); } + virtual void Cut() OVERRIDE { browser_->Cut(this); } + virtual void Copy() OVERRIDE { browser_->Copy(this); } + virtual void Paste() OVERRIDE { browser_->Paste(this); } + virtual void Delete() OVERRIDE { browser_->Delete(this); } + virtual void SelectAll() OVERRIDE { browser_->SelectAll(this); } + virtual void Print() OVERRIDE { browser_->Print(this); } + virtual void ViewSource() OVERRIDE { browser_->ViewSource(this); } + virtual CefString GetSource() OVERRIDE { return browser_->GetSource(this); } + virtual CefString GetText() OVERRIDE { return browser_->GetText(this); } + virtual void LoadRequest(CefRefPtr request) OVERRIDE { + return browser_->LoadRequest(this, request); + } + virtual void LoadURL(const CefString& url) OVERRIDE { + return browser_->LoadURL(this, url); + } + virtual void LoadString(const CefString& string, + const CefString& url) OVERRIDE { + return browser_->LoadString(this, string, url); + } + virtual void LoadStream(CefRefPtr stream, + const CefString& url) OVERRIDE { + return browser_->LoadStream(this, stream, url); + } + virtual void ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, + int startLine) OVERRIDE { + return browser_->ExecuteJavaScript(this, jsCode, scriptUrl, startLine); + } + virtual bool IsMain() OVERRIDE { return name_.empty(); } + virtual bool IsFocused() OVERRIDE; + virtual CefString GetName() OVERRIDE { return name_; } + virtual int64 GetIdentifier() OVERRIDE; + virtual CefRefPtr GetParent() OVERRIDE { + return browser_->GetParent(this); + } + virtual CefString GetURL() OVERRIDE; + virtual CefRefPtr GetBrowser() OVERRIDE { return browser_.get(); } + virtual void VisitDOM(CefRefPtr visitor) OVERRIDE; + virtual CefRefPtr GetV8Context() OVERRIDE; + + void set_id(int64 id); + void set_url(const CefString& url); + + private: + CefRefPtr browser_; + CefString name_; + + // The below values must be protected by the lock. + base::Lock lock_; + int64 id_; + CefString url_; + + IMPLEMENT_REFCOUNTING(CefFrameImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_IMPL_H_ diff --git a/cef1/libcef/browser_impl_gtk.cc b/cef1/libcef/browser_impl_gtk.cc new file mode 100644 index 000000000..cc69ad4a9 --- /dev/null +++ b/cef1/libcef/browser_impl_gtk.cc @@ -0,0 +1,202 @@ +// Copyright (c) 2012 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. + +#include + +#include "libcef/cef_context.h" +#include "libcef/browser_impl.h" +#include "libcef/browser_settings.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webpreferences.h" + +using WebKit::WebRect; +using WebKit::WebSize; + +namespace { + +void window_destroyed(GtkWidget* widget, CefBrowserImpl* browser) { + browser->UIT_DestroyBrowser(); +} + +} // namespace + +void CefBrowserImpl::ParentWindowWillClose() { + // TODO(port): Implement this method if necessary. +} + +CefWindowHandle CefBrowserImpl::GetWindowHandle() { + AutoLock lock_scope(this); + return window_info_.m_Widget; +} + +bool CefBrowserImpl::IsWindowRenderingDisabled() { + // TODO(port): Add support for off-screen rendering. + return false; +} + +gfx::NativeView CefBrowserImpl::UIT_GetMainWndHandle() { + REQUIRE_UIT(); + return window_info_.m_Widget; +} + +void CefBrowserImpl::UIT_ClearMainWndHandle() { + REQUIRE_UIT(); + window_info_.m_Widget = NULL; +} + +bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url) { + REQUIRE_UIT(); + Lock(); + + // Add a reference that will be released in UIT_DestroyBrowser(). + AddRef(); + + // Add the new browser to the list maintained by the context + _Context->AddBrowser(this); + + if (!settings_.developer_tools_disabled) + dev_tools_agent_.reset(new BrowserDevToolsAgent()); + + GtkWidget* window; + GtkWidget* parentView = window_info_.m_ParentWidget; + + if (parentView == NULL) { + // Create a new window. + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); + + parentView = gtk_vbox_new(FALSE, 0); + + gtk_container_add(GTK_CONTAINER(window), parentView); + gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); + gtk_widget_show_all(GTK_WIDGET(window)); + + window_info_.m_ParentWidget = parentView; + } + + webkit_glue::WebPreferences prefs; + BrowserToWebSettings(settings_, prefs); + + // Create the webview host object + webviewhost_.reset( + WebViewHost::Create(window_info_.m_ParentWidget, gfx::Rect(), + delegate_.get(), NULL, dev_tools_agent_.get(), + prefs)); + + if (!settings_.developer_tools_disabled) + dev_tools_agent_->SetWebView(webviewhost_->webview()); + + window_info_.m_Widget = webviewhost_->view_handle(); + g_signal_connect(G_OBJECT(window_info_.m_Widget), "destroy", + G_CALLBACK(window_destroyed), this); + + if (!settings_.drag_drop_disabled) + delegate_->RegisterDragDrop(); + + Unlock(); + + if (client_.get()) { + CefRefPtr handler = client_->GetLifeSpanHandler(); + if (handler.get()) { + // Notify the handler that we're done creating the new window + handler->OnAfterCreated(this); + } + } + + if (url.size() > 0) + UIT_LoadURL(GetMainFrame(), url); + + return true; +} + +void CefBrowserImpl::UIT_SetFocus(WebWidgetHost* host, bool enable) { + REQUIRE_UIT(); + if (!host) + return; + + if (enable) + gtk_widget_grab_focus(host->view_handle()); +} + +bool CefBrowserImpl::UIT_ViewDocumentString(WebKit::WebFrame *frame) { + REQUIRE_UIT(); + + char buff[] = "/tmp/CEFSourceXXXXXX"; + int fd = mkstemp(buff); + + if (fd == -1) + return false; + + FILE* srcOutput; + srcOutput = fdopen(fd, "w+"); + + if (!srcOutput) + return false; + + std::string markup = frame->contentAsMarkup().utf8(); + if (fputs(markup.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 CefBrowserImpl::UIT_PrintPage(int page_number, int total_pages, + const gfx::Size& canvas_size, + WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + // TODO(port): Add implementation. + NOTIMPLEMENTED(); +} + +void CefBrowserImpl::UIT_PrintPages(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + // TODO(port): Add implementation. + NOTIMPLEMENTED(); +} + +int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + // TODO(port): Add implementation. + NOTIMPLEMENTED(); + return 0; +} + +// static +void CefBrowserImpl::UIT_CloseView(gfx::NativeView view) { + GtkWidget* window = gtk_widget_get_toplevel(GTK_WIDGET(view)); + gtk_widget_destroy(window); +} + +// static +bool CefBrowserImpl::UIT_IsViewVisible(gfx::NativeView view) { + if (!view) + return false; + + if (view->window) + return gdk_window_is_visible(view->window)?true:false; + else + return false; +} diff --git a/cef1/libcef/browser_impl_mac.mm b/cef1/libcef/browser_impl_mac.mm new file mode 100644 index 000000000..df8736e67 --- /dev/null +++ b/cef1/libcef/browser_impl_mac.mm @@ -0,0 +1,213 @@ +// Copyright (c) 2010 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. + +#import + +#include "libcef/cef_context.h" +#include "libcef/browser_impl.h" +#include "libcef/browser_settings.h" +#include "libcef/browser_webview_mac.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webpreferences.h" + +using WebKit::WebRect; +using WebKit::WebSize; + +void CefBrowserImpl::ParentWindowWillClose() { + // TODO(port): Implement this method if necessary. +} + +CefWindowHandle CefBrowserImpl::GetWindowHandle() { + AutoLock lock_scope(this); + return window_info_.m_View; +} + +bool CefBrowserImpl::IsWindowRenderingDisabled() { + return (window_info_.m_bWindowRenderingDisabled ? true : false); +} + +gfx::NativeView CefBrowserImpl::UIT_GetMainWndHandle() { + REQUIRE_UIT(); + return window_info_.m_bWindowRenderingDisabled ? + window_info_.m_ParentView : window_info_.m_View; +} + +void CefBrowserImpl::UIT_ClearMainWndHandle() { + REQUIRE_UIT(); + if (!window_info_.m_bWindowRenderingDisabled) + window_info_.m_View = NULL; +} + +bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url) { + REQUIRE_UIT(); + Lock(); + + // Add a reference that will be released in UIT_DestroyBrowser(). + AddRef(); + + // Add the new browser to the list maintained by the context + _Context->AddBrowser(this); + + if (!settings_.developer_tools_disabled) + dev_tools_agent_.reset(new BrowserDevToolsAgent()); + + NSWindow* newWnd = nil; + + NSView* parentView = window_info_.m_ParentView; + gfx::Rect contentRect(window_info_.m_x, window_info_.m_y, + window_info_.m_nWidth, window_info_.m_nHeight); + if (!window_info_.m_bWindowRenderingDisabled) { + if (parentView == nil) { + // Create a new window. + NSRect screen_rect = [[NSScreen mainScreen] visibleFrame]; + NSRect window_rect = {{window_info_.m_x, + screen_rect.size.height - window_info_.m_y}, + {window_info_.m_nWidth, window_info_.m_nHeight}}; + if (window_rect.size.width == 0) + window_rect.size.width = 750; + if (window_rect.size.height == 0) + window_rect.size.height = 750; + contentRect.SetRect(0, 0, window_rect.size.width, + window_rect.size.height); + + newWnd = [[NSWindow alloc] + initWithContentRect:window_rect + styleMask:(NSTitledWindowMask | + NSClosableWindowMask | + NSMiniaturizableWindowMask | + NSResizableWindowMask | + NSUnifiedTitleAndToolbarWindowMask ) + backing:NSBackingStoreBuffered + defer:NO]; + parentView = [newWnd contentView]; + window_info_.m_ParentView = parentView; + } + } else { + // Create a new paint delegate. + paint_delegate_.reset(new PaintDelegate(this)); + } + + webkit_glue::WebPreferences prefs; + BrowserToWebSettings(settings_, prefs); + + // Create the webview host object + webviewhost_.reset( + WebViewHost::Create(parentView, contentRect, delegate_.get(), + paint_delegate_.get(), dev_tools_agent_.get(), + prefs)); + + if (window_info_.m_bTransparentPainting) + webviewhost_->webview()->setIsTransparent(true); + + if (!settings_.developer_tools_disabled) + dev_tools_agent_->SetWebView(webviewhost_->webview()); + + BrowserWebView* browserView = (BrowserWebView*)webviewhost_->view_handle(); + browserView.browser = this; + window_info_.m_View = browserView; + + if (!window_info_.m_bWindowRenderingDisabled) { + if (!settings_.drag_drop_disabled) + [browserView registerDragDrop]; + } + + Unlock(); + + if (newWnd != nil && !window_info_.m_bHidden) { + // Show the window. + [newWnd makeKeyAndOrderFront: nil]; + } + + if (client_.get()) { + CefRefPtr handler = client_->GetLifeSpanHandler(); + if(handler.get()) { + // Notify the handler that we're done creating the new window + handler->OnAfterCreated(this); + } + } + + if(url.size() > 0) + UIT_LoadURL(GetMainFrame(), url); + + return true; +} + +void CefBrowserImpl::UIT_SetFocus(WebWidgetHost* host, bool enable) { + REQUIRE_UIT(); + if (!host) + return; + + BrowserWebView* browserView = (BrowserWebView*)host->view_handle(); + if (!browserView) + return; + + if (enable) { + // Guard against calling OnSetFocus twice. + browserView.in_setfocus = true; + [[browserView window] makeFirstResponder:browserView]; + browserView.in_setfocus = false; + } +} + +bool CefBrowserImpl::UIT_ViewDocumentString(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + char sztmp[L_tmpnam+4]; + if (tmpnam(sztmp)) { + strcat(sztmp, ".txt"); + + FILE* fp = fopen(sztmp, "wb"); + if (fp) { + std::string markup = frame->contentAsMarkup().utf8(); + fwrite(markup.c_str(), 1, markup.size(), fp); + fclose(fp); + + char szopen[L_tmpnam + 14]; + snprintf(szopen, sizeof(szopen), "open -t \"%s\"", sztmp); + return (system(szopen) >= 0); + } + } + return false; +} + +void CefBrowserImpl::UIT_PrintPage(int page_number, int total_pages, + const gfx::Size& canvas_size, + WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + // TODO(port): Add implementation. + NOTIMPLEMENTED(); +} + +void CefBrowserImpl::UIT_PrintPages(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + // TODO(port): Add implementation. + NOTIMPLEMENTED(); +} + +int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + // TODO(port): Add implementation. + NOTIMPLEMENTED(); + return 0; +} + +// static +void CefBrowserImpl::UIT_CloseView(gfx::NativeView view) { + [[view window] performSelector:@selector(performClose:) + withObject:nil + afterDelay:0]; +} + +// static +bool CefBrowserImpl::UIT_IsViewVisible(gfx::NativeView view) { + return [[view window] isVisible]; +} diff --git a/cef1/libcef/browser_impl_win.cc b/cef1/libcef/browser_impl_win.cc new file mode 100644 index 000000000..f86cac7ff --- /dev/null +++ b/cef1/libcef/browser_impl_win.cc @@ -0,0 +1,596 @@ +// Copyright (c) 2008-2009 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. + +#include "libcef/browser_impl.h" + +#include +#include +#include +#include +#include + +#include "libcef/cef_context.h" +#include "libcef/browser_settings.h" + +#include "base/win/windows_version.h" +#include "printing/units.h" +#include "skia/ext/vector_canvas.h" +#include "skia/ext/vector_platform_device_emf_win.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPrintParams.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/base/win/hwnd_util.h" +#include "webkit/glue/webpreferences.h" + +#pragma comment(lib, "dwmapi.lib") + +using WebKit::WebRect; +using WebKit::WebSize; + +namespace { + +bool IsAeroGlassEnabled() { + if (base::win::GetVersion() < base::win::VERSION_VISTA) + return false; + + BOOL enabled = FALSE; + return SUCCEEDED(DwmIsCompositionEnabled(&enabled)) && enabled; +} + +void SetAeroGlass(HWND hWnd) { + if (!IsAeroGlassEnabled()) + return; + + // Make the whole window transparent. + MARGINS mgMarInset = { -1, -1, -1, -1 }; + DwmExtendFrameIntoClientArea(hWnd, &mgMarInset); +} + +} // namespace + +LPCTSTR CefBrowserImpl::GetWndClass() { + return L"CefBrowserWindow"; +} + +LRESULT CALLBACK CefBrowserImpl::WndProc(HWND hwnd, UINT message, + WPARAM wParam, LPARAM lParam) { + CefBrowserImpl* browser = + static_cast(ui::GetWindowUserData(hwnd)); + + switch (message) { + case WM_CLOSE: + if (browser) { + bool handled(false); + + if (browser->client_.get()) { + CefRefPtr handler = + browser->client_->GetLifeSpanHandler(); + if (handler.get()) { + // Give the client a chance to handle this one. + handled = handler->DoClose(browser); + } + } + + if (handled) + return 0; + + // We are our own parent in this case. + browser->ParentWindowWillClose(); + } + break; + + case WM_DESTROY: + if (browser) { + // Clear the user data pointer. + ui::SetWindowUserData(hwnd, NULL); + + BrowserWebViewDelegate* delegate = browser->UIT_GetWebViewDelegate(); + if (delegate && delegate->drag_delegate()) { + // Don't destroy the browser while a drag operation is pending. Instead, + // destroy the browser once the drag operation completes. + delegate->set_destroy_on_drag_end(true); + } else { + // Destroy the browser. + browser->UIT_DestroyBrowser(); + } + } + return 0; + + case WM_SIZE: + if (browser && browser->UIT_GetWebView()) { + // resize the web view window to the full size of the browser window + RECT rc; + GetClientRect(hwnd, &rc); + MoveWindow(browser->UIT_GetWebViewWndHandle(), 0, 0, rc.right, rc.bottom, + TRUE); + } + return 0; + + case WM_SETFOCUS: + if (browser) + browser->SetFocus(true); + return 0; + + case WM_ERASEBKGND: + return 0; + + case WM_DWMCOMPOSITIONCHANGED: + // Message sent to top-level windows when composition has been enabled or + // disabled. + if (browser->window_info_.m_bTransparentPainting) + SetAeroGlass(hwnd); + break; + } + + return DefWindowProc(hwnd, message, wParam, lParam); +} + +void CefBrowserImpl::ParentWindowWillClose() { + // We must re-enable the opener (owner of the modal window) before we close + // the popup to avoid focus/activation/z-order issues. + if (opener_ && opener_was_disabled_by_modal_loop_) { + HWND owner = ::GetAncestor(opener_, GA_ROOT); + ::EnableWindow(owner, TRUE); + } +} + +CefWindowHandle CefBrowserImpl::GetWindowHandle() { + AutoLock lock_scope(this); + return window_info_.m_hWnd; +} + +bool CefBrowserImpl::IsWindowRenderingDisabled() { + return (window_info_.m_bWindowRenderingDisabled ? true : false); +} + +gfx::NativeWindow CefBrowserImpl::UIT_GetMainWndHandle() { + REQUIRE_UIT(); + return window_info_.m_bWindowRenderingDisabled ? + window_info_.m_hWndParent : window_info_.m_hWnd; +} + +void CefBrowserImpl::UIT_ClearMainWndHandle() { + REQUIRE_UIT(); + if (!window_info_.m_bWindowRenderingDisabled) + window_info_.m_hWnd = NULL; +} + +bool CefBrowserImpl::UIT_CreateBrowser(const CefString& url) { + REQUIRE_UIT(); + Lock(); + + if (!window_info_.m_bWindowRenderingDisabled) { + std::wstring windowName(CefString(&window_info_.m_windowName)); + + // Create the new browser window + window_info_.m_hWnd = CreateWindowEx(window_info_.m_dwExStyle, + GetWndClass(), windowName.c_str(), window_info_.m_dwStyle, + window_info_.m_x, window_info_.m_y, window_info_.m_nWidth, + window_info_.m_nHeight, window_info_.m_hWndParent, window_info_.m_hMenu, + ::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_.m_hWnd != NULL); + if (!window_info_.m_hWnd) { + Unlock(); + return false; + } + + if (window_info_.m_bTransparentPainting && + !(window_info_.m_dwStyle & WS_CHILD)) { + // Transparent top-level windows will be given "sheet of glass" effect. + SetAeroGlass(window_info_.m_hWnd); + } + + // Set window user data to this object for future reference from the window + // procedure + ui::SetWindowUserData(window_info_.m_hWnd, this); + } else { + // Create a new paint delegate. + paint_delegate_.reset(new PaintDelegate(this)); + } + + if (!settings_.developer_tools_disabled) + dev_tools_agent_.reset(new BrowserDevToolsAgent()); + + // Add a reference that will be released in UIT_DestroyBrowser(). + AddRef(); + + // Add the new browser to the list maintained by the context + _Context->AddBrowser(this); + + webkit_glue::WebPreferences prefs; + BrowserToWebSettings(settings_, prefs); + + // Create the webview host object + webviewhost_.reset( + WebViewHost::Create(window_info_.m_hWnd, gfx::Rect(), delegate_.get(), + paint_delegate_.get(), dev_tools_agent_.get(), + prefs)); + + if (window_info_.m_bTransparentPainting) + webviewhost_->webview()->setIsTransparent(true); + + if (!settings_.developer_tools_disabled) + dev_tools_agent_->SetWebView(webviewhost_->webview()); + + Unlock(); + + if (!window_info_.m_bWindowRenderingDisabled) { + if (!settings_.drag_drop_disabled) + delegate_->RegisterDragDrop(); + + // Size the web view window to the browser window + RECT cr; + GetClientRect(window_info_.m_hWnd, &cr); + + // Respect the WS_VISIBLE window style when setting the window's position + UINT flags = SWP_NOZORDER; + if (window_info_.m_dwStyle & WS_VISIBLE) + flags |= SWP_SHOWWINDOW; + else + flags |= SWP_NOACTIVATE; + + SetWindowPos(UIT_GetWebViewWndHandle(), NULL, cr.left, cr.top, cr.right, + cr.bottom, flags); + } + + if (client_.get()) { + CefRefPtr handler = client_->GetLifeSpanHandler(); + if (handler.get()) { + // Notify the handler that we're done creating the new window + handler->OnAfterCreated(this); + } + } + + if (url.length() > 0) + UIT_LoadURL(GetMainFrame(), url); + + return true; +} + +void CefBrowserImpl::UIT_SetFocus(WebWidgetHost* host, bool enable) { + REQUIRE_UIT(); + if (!host) + return; + + if (enable) + ::SetFocus(host->view_handle()); + else if (::GetFocus() == host->view_handle()) + ::SetFocus(NULL); +} + +static void WriteTextToFile(const std::string& data, + const std::wstring& file_path) { + FILE* fp; + errno_t err = _wfopen_s(&fp, file_path.c_str(), L"wt"); + if (err) + return; + fwrite(data.c_str(), 1, data.size(), fp); + fclose(fp); +} + +bool CefBrowserImpl::UIT_ViewDocumentString(WebKit::WebFrame *frame) { + REQUIRE_UIT(); + + DWORD dwRetVal; + DWORD dwBufSize = 512; + TCHAR lpPathBuffer[512]; + UINT uRetVal; + TCHAR szTempName[512]; + + dwRetVal = GetTempPath(dwBufSize, // length of the buffer + lpPathBuffer); // buffer for path + if (dwRetVal > dwBufSize || (dwRetVal == 0)) + return false; + + // Create a temporary file. + uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files + TEXT("src"), // temp file name prefix + 0, // create unique name + szTempName); // buffer for name + if (uRetVal == 0) + return false; + + size_t len = wcslen(szTempName); + wcscpy(szTempName + len - 3, L"txt"); + std::string markup = frame->contentAsMarkup().utf8(); + WriteTextToFile(markup, szTempName); + + int errorCode = reinterpret_cast(ShellExecute(UIT_GetMainWndHandle(), + L"open", szTempName, NULL, NULL, SW_SHOWNORMAL)); + if (errorCode <= 32) + return false; + + return true; +} + +void CefBrowserImpl::UIT_PrintPage(int page_number, int total_pages, + const gfx::Size& canvas_size, + WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + printing::PrintParams params; + const printing::PrintSettings &settings = print_context_.settings(); + settings.RenderParams(¶ms); + + const int src_size_x = canvas_size.width(); + const int src_size_y = canvas_size.height(); + + const int dest_size_x = + settings.page_setup_pixels().printable_area().width(); + const int dest_size_y = + settings.page_setup_pixels().printable_area().height(); + + print_context_.NewPage(); + + HDC hDC = print_context_.context(); + BOOL res; + + // Save the state to make sure the context this function call does not modify + // the device context. + int saved_state = SaveDC(hDC); + DCHECK_NE(saved_state, 0); + + SkDevice* device = skia::VectorPlatformDeviceEmf::CreateDevice(dest_size_x, + dest_size_y, + true, hDC); + DCHECK(device); + skia::VectorCanvas canvas(device); + + // The hDC 0 coord is the left most printeable area and not physical area of + // the paper so subtract that out of our canvas translate. + const int left_margin_offset = + settings.page_setup_pixels().effective_margins().left - + settings.page_setup_pixels().printable_area().x(); + const int top_margin_offset = + settings.page_setup_pixels().effective_margins().top - + settings.page_setup_pixels().printable_area().y(); + + // Adjust for the margin offset. + canvas.translate(static_cast(left_margin_offset), + static_cast(top_margin_offset)); + + // Apply the print scaling factor. + const float print_scale_x = + static_cast(settings.page_setup_pixels().content_area().width()) + / src_size_x; + const float print_scale_y = + static_cast(settings.page_setup_pixels().content_area().height()) + / src_size_y; + canvas.scale(print_scale_x, print_scale_y); + + // Apply the WebKit scaling factor. + const float webkit_scale = frame->getPrintPageShrink(page_number); + if (webkit_scale <= 0) { + NOTREACHED() << "Printing page " << page_number << " failed."; + } + canvas.scale(webkit_scale, webkit_scale); + + frame->printPage(page_number, &canvas); + + res = RestoreDC(hDC, saved_state); + DCHECK_NE(res, 0); + + CefRefPtr handler; + if (client_.get()) + handler = client_->GetPrintHandler(); + + if (handler.get()) { + saved_state = SaveDC(hDC); + DCHECK_NE(saved_state, 0); + + // Gather print header state information + RECT rect; + rect.left = left_margin_offset; + rect.top = settings.page_setup_pixels().effective_margins().header - + settings.page_setup_pixels().printable_area().y(); + rect.right = left_margin_offset + + settings.page_setup_pixels().content_area().width(); + rect.bottom = settings.page_setup_pixels().printable_area().height() - + (settings.page_setup_pixels().effective_margins().footer - + (settings.page_setup_pixels().physical_size().height() - + settings.page_setup_pixels().printable_area().bottom())); + + const double scale = static_cast(settings.dpi()) / + static_cast(settings.desired_dpi); + + CefPrintInfo printInfo; + + printInfo.m_hDC = hDC; + printInfo.m_Rect = rect; + printInfo.m_Scale = scale; + + CefString url(frame->document().url().spec()); + CefString title = title_; + + CefString topLeft, topCenter, topRight; + CefString bottomLeft, bottomCenter, bottomRight; + + // Allow the handler to format print header and/or footer. + bool handled = handler->GetPrintHeaderFooter(this, UIT_GetCefFrame(frame), + printInfo, url, title, page_number+1, total_pages, topLeft, topCenter, + topRight, bottomLeft, bottomCenter, bottomRight); + + if (!handled) { + // Draw handler-defined headers and/or footers. + LOGFONT lf; + memset(&lf, 0, sizeof(lf)); + lf.lfHeight = static_cast(ceil(10. * scale)); + lf.lfPitchAndFamily = FF_SWISS; + HFONT hFont = CreateFontIndirect(&lf); + + HFONT hOldFont = (HFONT)SelectObject(hDC, hFont); + COLORREF hOldColor = SetTextColor(hDC, RGB(0, 0, 0)); + int hOldBkMode = SetBkMode(hDC, TRANSPARENT); + + // TODO(cef): Keep the header strings inside a reasonable bounding box + // so that they don't overlap each other. + if (topLeft.length() > 0) { + std::wstring topLeftStr(topLeft); + DrawText(hDC, topLeftStr.c_str(), topLeftStr.length(), &rect, + DT_LEFT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if (topCenter.length() > 0) { + std::wstring topCenterStr(topCenter); + DrawText(hDC, topCenterStr.c_str(), topCenterStr.length(), &rect, + DT_CENTER | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if (topRight.length() > 0) { + std::wstring topRightStr(topRight); + DrawText(hDC, topRightStr.c_str(), topRightStr.length(), &rect, + DT_RIGHT | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if (bottomLeft.length() > 0) { + std::wstring bottomLeftStr(bottomLeft); + DrawText(hDC, bottomLeftStr.c_str(), bottomLeftStr.length(), &rect, + DT_LEFT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if (bottomCenter.length() > 0) { + std::wstring bottomCenterStr(bottomCenter); + DrawText(hDC, bottomCenterStr.c_str(), bottomCenterStr.length(), &rect, + DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + if (bottomRight.length() > 0) { + std::wstring bottomRightStr(bottomRight); + DrawText(hDC, bottomRightStr.c_str(), bottomRightStr.length(), &rect, + DT_RIGHT | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS + | DT_EXPANDTABS | DT_NOPREFIX); + } + + SetTextColor(hDC, hOldColor); + SelectObject(hDC, hOldFont); + DeleteObject(hFont); + SetBkMode(hDC, hOldBkMode); + } + + res = RestoreDC(hDC, saved_state); + DCHECK_NE(res, 0); + } + + print_context_.PageDone(); +} + +void CefBrowserImpl::UIT_PrintPages(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + print_context_.Init(); + { + // Make a copy of settings. + printing::PrintSettings settings = print_context_.settings(); + CefPrintOptions print_options; + settings.UpdatePrintOptions(print_options); + + CefRefPtr handler; + if (client_.get()) + handler = client_->GetPrintHandler(); + + // Ask the handler if they want to update the print options. + if (handler.get() && handler->GetPrintOptions(this, print_options)) { + settings.UpdateFromPrintOptions(print_options); + print_context_.InitWithSettings(settings); + } + } + + if (print_context_.AskUserForSettings( + UIT_GetMainWndHandle(), UIT_GetPagesCount(frame), false) + != printing::PrintingContext::OK) + return; + + printing::PrintParams params; + const printing::PrintSettings &settings = print_context_.settings(); + + settings.RenderParams(¶ms); + + int page_count = 0; + gfx::Size canvas_size; + + canvas_size.set_width( + printing::ConvertUnit( + settings.page_setup_pixels().content_area().width(), + static_cast(params.dpi), + params.desired_dpi)); + canvas_size.set_height( + printing::ConvertUnit( + settings.page_setup_pixels().content_area().height(), + static_cast(params.dpi), + params.desired_dpi)); + WebKit::WebPrintParams printParams( + WebSize(canvas_size.width(), canvas_size.height())); + page_count = frame->printBegin(printParams); + + if (page_count) { + bool old_state = MessageLoop::current()->NestableTasksAllowed(); + MessageLoop::current()->SetNestableTasksAllowed(false); + + if (print_context_.NewDocument(title_) == printing::PrintingContext::OK) { + if (settings.ranges.size() > 0) { + for (unsigned x = 0; x < settings.ranges.size(); ++x) { + const printing::PageRange& range = settings.ranges[x]; + for (int i = range.from; i <= range.to; ++i) + UIT_PrintPage(i, page_count, canvas_size, frame); + } + } else { + for (int i = 0; i < page_count; ++i) + UIT_PrintPage(i, page_count, canvas_size, frame); + } + print_context_.DocumentDone(); + } + + MessageLoop::current()->SetNestableTasksAllowed(old_state); + } + + frame->printEnd(); +} + +int CefBrowserImpl::UIT_GetPagesCount(WebKit::WebFrame* frame) { + REQUIRE_UIT(); + + printing::PrintParams params; + const printing::PrintSettings &settings = print_context_.settings(); + + settings.RenderParams(¶ms); + + // The dbi will be 0 if no default printer is configured. + if (params.dpi == 0) + return 0; + + int page_count = 0; + gfx::Size canvas_size; + + canvas_size.set_width( + printing::ConvertUnit( + settings.page_setup_pixels().content_area().width(), + static_cast(params.dpi), + params.desired_dpi)); + canvas_size.set_height( + printing::ConvertUnit( + settings.page_setup_pixels().content_area().height(), + static_cast(params.dpi), + params.desired_dpi)); + page_count = frame->printBegin(WebSize(canvas_size)); + frame->printEnd(); + + return page_count; +} + +// static +void CefBrowserImpl::UIT_CloseView(gfx::NativeView view) { + PostMessage(view, WM_CLOSE, 0, 0); +} + +// static +bool CefBrowserImpl::UIT_IsViewVisible(gfx::NativeView view) { + return IsWindowVisible(view) ? true : false; +} diff --git a/cef1/libcef/browser_navigation_controller.cc b/cef1/libcef/browser_navigation_controller.cc new file mode 100644 index 000000000..d6cbeec74 --- /dev/null +++ b/cef1/libcef/browser_navigation_controller.cc @@ -0,0 +1,253 @@ +// Copyright (c) 2008 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. + +#include "libcef/browser_navigation_controller.h" +#include "libcef/browser_impl.h" + +#include "base/logging.h" +#include "net/base/upload_data.h" + +// ---------------------------------------------------------------------------- +// BrowserNavigationEntry + +BrowserNavigationEntry::BrowserNavigationEntry() + : page_id_(-1) { +} + +BrowserNavigationEntry::BrowserNavigationEntry(int page_id, + const GURL& url, + const CefString& title, + const CefString& target_frame, + const CefString& method, + const WebKit::WebHTTPBody& upload, + const CefRequest::HeaderMap& headers) + : page_id_(page_id), + url_(url), + title_(title), + method_(method), + headers_(headers), + target_frame_(target_frame) { + if (!upload.isNull()) + upload_ = upload; +} + +BrowserNavigationEntry::~BrowserNavigationEntry() { +} + +void BrowserNavigationEntry::SetContentState(const std::string& state) { + state_ = state; +} + +// ---------------------------------------------------------------------------- +// BrowserNavigationController + +BrowserNavigationController::BrowserNavigationController( + CefBrowserImpl* browser) + : pending_entry_(NULL), + last_committed_entry_index_(-1), + pending_entry_index_(-1), + browser_(browser), + max_page_id_(-1) { +} + +BrowserNavigationController::~BrowserNavigationController() { + DiscardPendingEntry(); +} + +void BrowserNavigationController::Reset() { + entries_.clear(); + DiscardPendingEntry(); + + last_committed_entry_index_ = -1; + UpdateMaxPageID(); +} + +void BrowserNavigationController::Reload(bool ignoreCache) { + // Base the navigation on where we are now... + int current_index = GetCurrentEntryIndex(); + + // If we are no where, then we can't reload. TODO(darin): We should add a + // CanReload method. + if (current_index == -1) + return; + + DiscardPendingEntry(); + + pending_entry_index_ = current_index; + NavigateToPendingEntry(true, ignoreCache); +} + +void BrowserNavigationController::GoToOffset(int offset) { + int index = last_committed_entry_index_ + offset; + if (index < 0 || index >= GetEntryCount()) + return; + + GoToIndex(index); +} + +void BrowserNavigationController::GoToIndex(int index) { + DCHECK_GE(index, 0); + DCHECK_LT(index, static_cast(entries_.size())); + + DiscardPendingEntry(); + + pending_entry_index_ = index; + NavigateToPendingEntry(false, false); +} + +void BrowserNavigationController::LoadEntry(BrowserNavigationEntry* entry) { + // When navigating to a new page, we don't know for sure if we will actually + // end up leaving the current page. The new page load could for example + // result in a download or a 'no content' response (e.g., a mailto: URL). + DiscardPendingEntry(); + pending_entry_ = entry; + NavigateToPendingEntry(false, false); +} + + +BrowserNavigationEntry* BrowserNavigationController::GetLastCommittedEntry() + const { + if (last_committed_entry_index_ == -1) + return NULL; + return entries_[last_committed_entry_index_].get(); +} + +BrowserNavigationEntry* BrowserNavigationController::GetActiveEntry() const { + BrowserNavigationEntry* entry = pending_entry_; + if (!entry) + entry = GetLastCommittedEntry(); + return entry; +} + +int BrowserNavigationController::GetCurrentEntryIndex() const { + if (pending_entry_index_ != -1) + return pending_entry_index_; + return last_committed_entry_index_; +} + + +BrowserNavigationEntry* BrowserNavigationController::GetEntryAtIndex( + int index) const { + if (index < 0 || index >= GetEntryCount()) + return NULL; + + return entries_[index].get(); +} + +BrowserNavigationEntry* BrowserNavigationController::GetEntryWithPageID( + int32 page_id) const { + int index = GetEntryIndexWithPageID(page_id); + return (index != -1) ? entries_[index].get() : NULL; +} + +void BrowserNavigationController::DidNavigateToEntry( + BrowserNavigationEntry* entry) { + // If the entry is that of a page with PageID larger than any this Tab has + // seen before, then consider it a new navigation. + if (entry->GetPageID() > GetMaxPageID()) { + InsertEntry(entry); + return; + } + + // Otherwise, we just need to update an existing entry with matching PageID. + // If the existing entry corresponds to the entry which is pending, then we + // must update the current entry index accordingly. When navigating to the + // same URL, a new PageID is not created. + + int existing_entry_index = GetEntryIndexWithPageID(entry->GetPageID()); + BrowserNavigationEntry* existing_entry = (existing_entry_index != -1) ? + entries_[existing_entry_index].get() : NULL; + if (!existing_entry) { + // No existing entry, then simply ignore this navigation! + DLOG(WARNING) << "ignoring navigation for page: " << entry->GetPageID(); + } else if (existing_entry == pending_entry_) { + // The given entry might provide a new URL... e.g., navigating back to a + // page in session history could have resulted in a new client redirect. + existing_entry->SetURL(entry->GetURL()); + existing_entry->SetContentState(entry->GetContentState()); + last_committed_entry_index_ = pending_entry_index_; + pending_entry_index_ = -1; + pending_entry_ = NULL; + } else if (pending_entry_ && pending_entry_->GetPageID() == -1 && + pending_entry_->GetURL() == existing_entry->GetURL()) { + // Not a new navigation + DiscardPendingEntry(); + } else { + // The given entry might provide a new URL... e.g., navigating to a page + // might result in a client redirect, which should override the URL of the + // existing entry. + existing_entry->SetURL(entry->GetURL()); + existing_entry->SetContentState(entry->GetContentState()); + + // The navigation could have been issued by the renderer, so be sure that + // we update our current index. + last_committed_entry_index_ = existing_entry_index; + } + + delete entry; + UpdateMaxPageID(); +} + +void BrowserNavigationController::DiscardPendingEntry() { + if (pending_entry_index_ == -1) + delete pending_entry_; + pending_entry_ = NULL; + pending_entry_index_ = -1; +} + +void BrowserNavigationController::InsertEntry(BrowserNavigationEntry* entry) { + DiscardPendingEntry(); + + const CefBrowserSettings& settings = browser_->settings(); + if (settings.history_disabled) { + // History is disabled. Remove any existing entries. + if (entries_.size() > 0) + entries_.clear(); + } else { + // Prune any entry which are in front of the current entry. + int current_size = static_cast(entries_.size()); + if (current_size > 0) { + while (last_committed_entry_index_ < (current_size - 1)) { + entries_.pop_back(); + current_size--; + } + } + } + + entries_.push_back(linked_ptr(entry)); + last_committed_entry_index_ = static_cast(entries_.size()) - 1; + UpdateMaxPageID(); +} + +int BrowserNavigationController::GetEntryIndexWithPageID(int32 page_id) const { + for (int i = static_cast(entries_.size())-1; i >= 0; --i) { + if (entries_[i]->GetPageID() == page_id) + return i; + } + return -1; +} + +void BrowserNavigationController::NavigateToPendingEntry(bool reload, + bool ignoreCache) { + // For session history navigations only the pending_entry_index_ is set. + if (!pending_entry_) { + DCHECK_NE(pending_entry_index_, -1); + pending_entry_ = entries_[pending_entry_index_].get(); + } + + if (browser_->UIT_Navigate(*pending_entry_, reload, ignoreCache)) { + // Note: this is redundant if navigation completed synchronously because + // DidNavigateToEntry call this as well. + UpdateMaxPageID(); + } else { + DiscardPendingEntry(); + } +} + +void BrowserNavigationController::UpdateMaxPageID() { + BrowserNavigationEntry* entry = GetActiveEntry(); + if (entry) + max_page_id_ = std::max(max_page_id_, entry->GetPageID()); +} diff --git a/cef1/libcef/browser_navigation_controller.h b/cef1/libcef/browser_navigation_controller.h new file mode 100644 index 000000000..d4b0642d3 --- /dev/null +++ b/cef1/libcef/browser_navigation_controller.h @@ -0,0 +1,213 @@ +// Copyright (c) 2008-2009 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. + +#ifndef CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_ +#define CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_ +#pragma once + +#include +#include + +#include "base/basictypes.h" +#include "base/memory/linked_ptr.h" +#include "base/memory/ref_counted.h" +#include "googleurl/src/gurl.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebHTTPBody.h" + +#include "include/cef_request.h" + +class GURL; +class CefBrowserImpl; + +// Associated with browser-initated navigations to hold tracking data. +class BrowserExtraData : public WebKit::WebDataSource::ExtraData { + public: + explicit BrowserExtraData(int32 pending_page_id) + : pending_page_id(pending_page_id), + request_committed(false) { + } + + // Contains the page_id for this navigation or -1 if there is none yet. + int32 pending_page_id; + + // True if we have already processed the "DidCommitLoad" event for this + // request. Used by session history. + bool request_committed; +}; + +// Stores one back/forward navigation state for the test shell. +class BrowserNavigationEntry { + public: + BrowserNavigationEntry(); + BrowserNavigationEntry(int page_id, + const GURL& url, + const CefString& title, + const CefString& target_frame, + const CefString& method, + const WebKit::WebHTTPBody& upload, + const CefRequest::HeaderMap& headers); + ~BrowserNavigationEntry(); + + // Set / Get the URI + void SetURL(const GURL& url) { url_ = url; } + const GURL& GetURL() const { return url_; } + + // Set / Get the title + void SetTitle(const CefString& a_title) { title_ = a_title; } + const CefString& GetTitle() const { return title_; } + + // Set / Get opaque state. + // WARNING: This state is saved to the database and used to restore previous + // states. If you use write a custom TabContents and provide your own + // state make sure you have the ability to modify the format in the future + // while being able to deal with older versions. + void SetContentState(const std::string& state); + const std::string& GetContentState() const { return state_; } + + // Get the page id corresponding to the tab's state. + void SetPageID(int page_id) { page_id_ = page_id; } + int32 GetPageID() const { return page_id_; } + + const CefString& GetTargetFrame() const { return target_frame_; } + + const CefString& GetMethod() const { return method_; } + const WebKit::WebHTTPBody& GetUploadData() const { return upload_; } + const CefRequest::HeaderMap& GetHeaders() const { return headers_; } + + private: + // Describes the current page that the tab represents. This is not relevant + // for all tab contents types. + int32 page_id_; + + GURL url_; + CefString title_; + std::string state_; + CefString method_; + WebKit::WebHTTPBody upload_; + CefRequest::HeaderMap headers_; + + CefString target_frame_; + + DISALLOW_COPY_AND_ASSIGN(BrowserNavigationEntry); +}; + +// Browser's NavigationController. The goal is to be as close to the Chrome +// version as possible. +class BrowserNavigationController { + public: + explicit BrowserNavigationController(CefBrowserImpl* browser); + ~BrowserNavigationController(); + + void Reset(); + + // Causes the controller to reload the current (or pending) entry. + void Reload(bool ignoreCache); + + // Causes the controller to go to the specified offset from current. Does + // nothing if out of bounds. + void GoToOffset(int offset); + + // Causes the controller to go to the specified index. + void GoToIndex(int index); + + // Causes the controller to load the specified entry. The controller + // assumes ownership of the entry. + // NOTE: Do not pass an entry that the controller already owns! + void LoadEntry(BrowserNavigationEntry* entry); + + // Returns the last committed entry, which may be null if there are no + // committed entries. + BrowserNavigationEntry* GetLastCommittedEntry() const; + + // Returns the number of entries in the NavigationControllerBase, excluding + // the pending entry if there is one. + int GetEntryCount() const { + return static_cast(entries_.size()); + } + + // Returns the active entry, which is the pending entry if a navigation is in + // progress or the last committed entry otherwise. NOTE: This can be NULL!! + // + // If you are trying to get the current state of the NavigationControllerBase, + // this is the method you will typically want to call. + BrowserNavigationEntry* GetActiveEntry() const; + + // Returns the index from which we would go back/forward or reload. This is + // the last_committed_entry_index_ if pending_entry_index_ is -1. Otherwise, + // it is the pending_entry_index_. + int GetCurrentEntryIndex() const; + + // Returns the entry at the specified index. Returns NULL if out of + // bounds. + BrowserNavigationEntry* GetEntryAtIndex(int index) const; + + // Return the entry with the corresponding type and page_id, or NULL if + // not found. + BrowserNavigationEntry* GetEntryWithPageID(int32 page_id) const; + + // Returns the index of the last committed entry. + int GetLastCommittedEntryIndex() const { + return last_committed_entry_index_; + } + + // Returns true if there are no entries before the last committed entry. + bool IsAtStart() const { + return (GetLastCommittedEntryIndex() == 0); + } + + // Returns true if there are no entries after the last committed entry. + bool IsAtEnd() const { + return (GetLastCommittedEntryIndex() == GetEntryCount()-1); + } + + // Used to inform us of a navigation being committed for a tab. We will take + // ownership of the entry. Any entry located forward to the current entry will + // be deleted. The new entry becomes the current entry. + void DidNavigateToEntry(BrowserNavigationEntry* entry); + + // Used to inform us to discard its pending entry. + void DiscardPendingEntry(); + + private: + // Inserts an entry after the current position, removing all entries after it. + // The new entry will become the active one. + void InsertEntry(BrowserNavigationEntry* entry); + + int GetMaxPageID() const { return max_page_id_; } + void NavigateToPendingEntry(bool reload, bool ignoreCache); + + // Return the index of the entry with the corresponding type and page_id, + // or -1 if not found. + int GetEntryIndexWithPageID(int32 page_id) const; + + // Updates the max page ID with that of the given entry, if is larger. + void UpdateMaxPageID(); + + // List of NavigationEntry for this tab + typedef std::vector< linked_ptr > NavigationEntryList; + typedef NavigationEntryList::iterator NavigationEntryListIterator; + NavigationEntryList entries_; + + // An entry we haven't gotten a response for yet. This will be discarded + // when we navigate again. It's used only so we know what the currently + // displayed tab is. + BrowserNavigationEntry* pending_entry_; + + // currently visible entry + int last_committed_entry_index_; + + // index of pending entry if it is in entries_, or -1 if pending_entry_ is a + // new entry (created by LoadURL). + int pending_entry_index_; + + CefBrowserImpl* browser_; + int max_page_id_; + + DISALLOW_EVIL_CONSTRUCTORS(BrowserNavigationController); +}; + +#endif // CEF_LIBCEF_BROWSER_NAVIGATION_CONTROLLER_H_ + diff --git a/cef1/libcef/browser_network_delegate.cc b/cef1/libcef/browser_network_delegate.cc new file mode 100644 index 000000000..547ffcb0b --- /dev/null +++ b/cef1/libcef/browser_network_delegate.cc @@ -0,0 +1,117 @@ +// 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_network_delegate.h" + +#include "net/base/net_errors.h" +#include "net/base/static_cookie_policy.h" +#include "net/url_request/url_request.h" + +BrowserNetworkDelegate::BrowserNetworkDelegate() + : accept_all_cookies_(true) { +} + +BrowserNetworkDelegate::~BrowserNetworkDelegate() { +} + +int BrowserNetworkDelegate::OnBeforeURLRequest( + net::URLRequest* request, + const net::CompletionCallback& callback, + GURL* new_url) { + return net::OK; +} + +int BrowserNetworkDelegate::OnBeforeSendHeaders( + net::URLRequest* request, + const net::CompletionCallback& callback, + net::HttpRequestHeaders* headers) { + return net::OK; +} + +void BrowserNetworkDelegate::OnSendHeaders( + net::URLRequest* request, + const net::HttpRequestHeaders& headers) { +} + +int BrowserNetworkDelegate::OnHeadersReceived( + net::URLRequest* request, + const net::CompletionCallback& callback, + net::HttpResponseHeaders* original_response_headers, + scoped_refptr*override_response_headers) { + return net::OK; +} + +void BrowserNetworkDelegate::OnBeforeRedirect(net::URLRequest* request, + const GURL& new_location) { +} + +void BrowserNetworkDelegate::OnResponseStarted(net::URLRequest* request) { +} + +void BrowserNetworkDelegate::OnRawBytesRead(const net::URLRequest& request, + int bytes_read) { +} +void BrowserNetworkDelegate::OnCompleted(net::URLRequest* request, + bool started) { +} + +void BrowserNetworkDelegate::OnURLRequestDestroyed(net::URLRequest* request) { +} + +void BrowserNetworkDelegate::OnPACScriptError(int line_number, + const string16& error) { +} + +net::NetworkDelegate::AuthRequiredResponse + BrowserNetworkDelegate::OnAuthRequired( + net::URLRequest* request, + const net::AuthChallengeInfo& auth_info, + const AuthCallback& callback, + net::AuthCredentials* credentials) { + return AUTH_REQUIRED_RESPONSE_NO_ACTION; +} + +bool BrowserNetworkDelegate::OnCanGetCookies( + const net::URLRequest& request, + const net::CookieList& cookie_list) { + net::StaticCookiePolicy::Type policy_type = accept_all_cookies_ ? + net::StaticCookiePolicy::ALLOW_ALL_COOKIES : + net::StaticCookiePolicy::BLOCK_SETTING_THIRD_PARTY_COOKIES; + + net::StaticCookiePolicy policy(policy_type); + int rv = policy.CanGetCookies( + request.url(), request.first_party_for_cookies()); + return rv == net::OK; +} + +bool BrowserNetworkDelegate::OnCanSetCookie( + const net::URLRequest& request, + const std::string& cookie_line, + net::CookieOptions* options) { + net::StaticCookiePolicy::Type policy_type = accept_all_cookies_ ? + net::StaticCookiePolicy::ALLOW_ALL_COOKIES : + net::StaticCookiePolicy::BLOCK_SETTING_THIRD_PARTY_COOKIES; + + net::StaticCookiePolicy policy(policy_type); + int rv = policy.CanSetCookie( + request.url(), request.first_party_for_cookies()); + return rv == net::OK; +} + +bool BrowserNetworkDelegate::OnCanAccessFile(const net::URLRequest& request, + const FilePath& path) const { + return true; +} + +bool BrowserNetworkDelegate::OnCanThrottleRequest( + const net::URLRequest& request) const { + return false; +} + +int BrowserNetworkDelegate::OnBeforeSocketStreamConnect( + net::SocketStream* stream, + const net::CompletionCallback& callback) { + return net::OK; +} diff --git a/cef1/libcef/browser_network_delegate.h b/cef1/libcef/browser_network_delegate.h new file mode 100644 index 000000000..e076afac4 --- /dev/null +++ b/cef1/libcef/browser_network_delegate.h @@ -0,0 +1,63 @@ +// 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_NETWORK_DELEGATE_H +#define CEF_LIBCEF_BROWSER_NETWORK_DELEGATE_H +#pragma once + +#include "net/base/network_delegate.h" + +class BrowserNetworkDelegate : public net::NetworkDelegate { + public: + BrowserNetworkDelegate(); + virtual ~BrowserNetworkDelegate(); + + private: + // net::NetworkDelegate implementation. + virtual int OnBeforeURLRequest(net::URLRequest* request, + const net::CompletionCallback& callback, + GURL* new_url) OVERRIDE; + virtual int OnBeforeSendHeaders(net::URLRequest* request, + const net::CompletionCallback& callback, + net::HttpRequestHeaders* headers) OVERRIDE; + virtual void OnSendHeaders(net::URLRequest* request, + const net::HttpRequestHeaders& headers) OVERRIDE; + virtual int OnHeadersReceived( + net::URLRequest* request, + const net::CompletionCallback& callback, + net::HttpResponseHeaders* original_response_headers, + scoped_refptr* + override_response_headers) OVERRIDE; + virtual void OnBeforeRedirect(net::URLRequest* request, + const GURL& new_location) OVERRIDE; + virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE; + virtual void OnRawBytesRead(const net::URLRequest& request, + int bytes_read) OVERRIDE; + virtual void OnCompleted(net::URLRequest* request, bool started) OVERRIDE; + virtual void OnURLRequestDestroyed(net::URLRequest* request) OVERRIDE; + virtual void OnPACScriptError(int line_number, + const string16& error) OVERRIDE; + virtual AuthRequiredResponse OnAuthRequired( + net::URLRequest* request, + const net::AuthChallengeInfo& auth_info, + const AuthCallback& callback, + net::AuthCredentials* credentials) OVERRIDE; + virtual bool OnCanGetCookies(const net::URLRequest& request, + const net::CookieList& cookie_list) OVERRIDE; + virtual bool OnCanSetCookie(const net::URLRequest& request, + const std::string& cookie_line, + net::CookieOptions* options) OVERRIDE; + virtual bool OnCanAccessFile(const net::URLRequest& request, + const FilePath& path) const OVERRIDE; + virtual bool OnCanThrottleRequest( + const net::URLRequest& request) const OVERRIDE; + virtual int OnBeforeSocketStreamConnect( + net::SocketStream* stream, + const net::CompletionCallback& callback) OVERRIDE; + + bool accept_all_cookies_; +}; + +#endif // CEF_LIBCEF_BROWSER_NETWORK_DELEGATE_H diff --git a/cef1/libcef/browser_request_context.cc b/cef1/libcef/browser_request_context.cc new file mode 100644 index 000000000..6e3d28308 --- /dev/null +++ b/cef1/libcef/browser_request_context.cc @@ -0,0 +1,320 @@ +// Copyright (c) 2008 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. + +#include "libcef/browser_request_context.h" + +#if defined(OS_WIN) +#include +#endif + +#include "libcef/browser_file_system.h" +#include "libcef/browser_resource_loader_bridge.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" + +#include "base/compiler_specific.h" +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/thread_task_runner_handle.h" +#include "base/threading/worker_pool.h" +#include "build/build_config.h" +#include "chrome/browser/net/sqlite_persistent_cookie_store.h" +#include "net/base/cert_verifier.h" +#include "net/cookies/cookie_monster.h" +#include "net/base/default_server_bound_cert_store.h" +#include "net/base/host_resolver.h" +#include "net/base/server_bound_cert_service.h" +#include "net/base/ssl_config_service_defaults.h" +#include "net/ftp/ftp_network_layer.h" +#include "net/http/http_auth_handler_factory.h" +#include "net/http/http_server_properties_impl.h" +#include "net/proxy/proxy_config_service.h" +#include "net/proxy/proxy_config_service_fixed.h" +#include "net/proxy/proxy_resolver.h" +#include "net/proxy/proxy_service.h" +#include "net/url_request/url_request_job_factory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebKitPlatformSupport.h" +#include "webkit/blob/blob_storage_controller.h" +#include "webkit/blob/blob_url_request_job_factory.h" +#include "webkit/fileapi/file_system_context.h" +#include "webkit/fileapi/file_system_url_request_job_factory.h" +#include "webkit/glue/webkit_glue.h" + +#if defined(OS_WIN) +#pragma comment(lib, "winhttp.lib") +#endif + +namespace { + +#if defined(OS_WIN) + +// ProxyConfigService implementation that does nothing. +class ProxyConfigServiceNull : public net::ProxyConfigService { + public: + ProxyConfigServiceNull() {} + virtual void AddObserver(Observer* observer) OVERRIDE {} + virtual void RemoveObserver(Observer* observer) OVERRIDE {} + virtual ProxyConfigService::ConfigAvailability + GetLatestProxyConfig(net::ProxyConfig* config) OVERRIDE + { return ProxyConfigService::CONFIG_VALID; } + virtual void OnLazyPoll() OVERRIDE {} +}; + +#endif // defined(OS_WIN) + +// ProxyResolver implementation that forewards resolution to a CefProxyHandler. +class CefProxyResolver : public net::ProxyResolver { + public: + explicit CefProxyResolver(CefRefPtr handler) + : ProxyResolver(false), + handler_(handler) {} + virtual ~CefProxyResolver() {} + + virtual int GetProxyForURL(const GURL& url, + net::ProxyInfo* results, + const net::CompletionCallback& callback, + RequestHandle* request, + const net::BoundNetLog& net_log) OVERRIDE { + CefProxyInfo proxy_info; + handler_->GetProxyForUrl(url.spec(), proxy_info); + if (proxy_info.IsDirect()) + results->UseDirect(); + else if (proxy_info.IsNamedProxy()) + results->UseNamedProxy(proxy_info.ProxyList()); + else if (proxy_info.IsPacString()) + results->UsePacString(proxy_info.ProxyList()); + + return net::OK; + } + + virtual int SetPacScript( + const scoped_refptr& pac_script, + const net::CompletionCallback& callback) OVERRIDE { + return net::OK; + } + + virtual void CancelRequest(RequestHandle request) OVERRIDE {} + virtual net::LoadState GetLoadState(RequestHandle request) const OVERRIDE { + return net::LOAD_STATE_IDLE; + } + virtual net::LoadState GetLoadStateThreadSafe(RequestHandle request) const + OVERRIDE { + return net::LOAD_STATE_IDLE; + } + virtual void CancelSetPacScript() OVERRIDE {} + + protected: + CefRefPtr handler_; +}; + +net::ProxyConfigService* CreateProxyConfigService() { +#if defined(OS_POSIX) && !defined(OS_MACOSX) + // Use no proxy to avoid ProxyConfigServiceLinux. + // Enabling use of the ProxyConfigServiceLinux requires: + // -Calling from a thread with a TYPE_UI MessageLoop, + // -If at all possible, passing in a pointer to the IO thread's MessageLoop, + // -Keep in mind that proxy auto configuration is also non-functional on linux + // in this context because of v8 threading issues. + // TODO(port): rename "linux" to some nonspecific unix. + return new net::ProxyConfigServiceFixed(net::ProxyConfig()); +#else + // Use the system proxy settings. + return net::ProxyService::CreateSystemProxyConfigService( + base::ThreadTaskRunnerHandle::Get(), NULL); +#endif +} + +} // namespace + + +BrowserRequestContext::BrowserRequestContext() + : ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) { + Init(FilePath(), net::HttpCache::NORMAL, false); +} + +BrowserRequestContext::BrowserRequestContext( + const FilePath& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy) + : ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) { + Init(cache_path, cache_mode, no_proxy); +} + +void BrowserRequestContext::Init( + const FilePath& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy) { + SetCookieStoragePath(cache_path); + + storage_.set_server_bound_cert_service(new net::ServerBoundCertService( + new net::DefaultServerBoundCertStore(NULL), + base::WorkerPool::GetTaskRunner(true))); + + // hard-code A-L and A-C for test shells + set_accept_language("en-us,en"); + set_accept_charset("iso-8859-1,*,utf-8"); + + CefRefPtr app = _Context->application(); + if (app.get()) { + CefRefPtr handler = app->GetProxyHandler(); + if (handler) { + // The client will provide proxy resolution. + storage_.set_proxy_service( + new net::ProxyService(CreateProxyConfigService(), + new CefProxyResolver(handler), NULL)); + } + } + +#if defined(OS_WIN) + if (!proxy_service()) { + const CefSettings& settings = _Context->settings(); + if (!settings.auto_detect_proxy_settings_enabled) { + // Using the system proxy resolver on Windows when "Automatically detect + // settings" (auto-detection) is checked under LAN Settings can hurt + // resource loading performance because the call to WinHttpGetProxyForUrl + // in proxy_resolver_winhttp.cc will block the IO thread. This is + // especially true for Windows 7 where auto-detection is checked by + // default. To avoid slow resource loading on Windows we only use the + // system proxy resolver if auto-detection is unchecked. + WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = {0}; + if (WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { + if (ie_config.fAutoDetect == TRUE) { + storage_.set_proxy_service( + net::ProxyService::CreateWithoutProxyResolver( + new ProxyConfigServiceNull(), NULL)); + } + + if (ie_config.lpszAutoConfigUrl) + GlobalFree(ie_config.lpszAutoConfigUrl); + if (ie_config.lpszProxy) + GlobalFree(ie_config.lpszProxy); + if (ie_config.lpszProxyBypass) + GlobalFree(ie_config.lpszProxyBypass); + } + } + } +#endif // defined(OS_WIN) + + if (!proxy_service()) { + storage_.set_proxy_service( + net::ProxyService::CreateUsingSystemProxyResolver( + CreateProxyConfigService(), 0, NULL)); + } + + storage_.set_host_resolver( + net::CreateSystemHostResolver(net::HostResolver::kDefaultParallelism, + net::HostResolver::kDefaultRetryAttempts, + NULL)); + storage_.set_cert_verifier(net::CertVerifier::CreateDefault()); + 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(), + host_resolver(), + std::string(), + false, + false)); + storage_.set_http_server_properties(new net::HttpServerPropertiesImpl); + + net::HttpCache::DefaultBackend* backend = new net::HttpCache::DefaultBackend( + cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE, + cache_path, 0, BrowserResourceLoaderBridge::GetCacheThread()); + + net::HttpCache* cache = + new net::HttpCache(host_resolver(), + cert_verifier(), + server_bound_cert_service(), + NULL, /* transport_security_state */ + proxy_service(), + "", /* ssl_session_cache_shard */ + ssl_config_service(), + http_auth_handler_factory(), + NULL, /* network_delegate */ + http_server_properties(), + NULL, /* netlog */ + backend, + "" /* trusted_spdy_proxy */ ); + + cache->set_mode(cache_mode); + storage_.set_http_transaction_factory(cache); + + storage_.set_ftp_transaction_factory( + new net::FtpNetworkLayer(host_resolver())); + + net::URLRequestJobFactory* job_factory = new net::URLRequestJobFactory; + + blob_storage_controller_.reset(new webkit_blob::BlobStorageController()); + job_factory->SetProtocolHandler( + "blob", + new webkit_blob::BlobProtocolHandler( + blob_storage_controller_.get(), + CefThread::GetMessageLoopProxyForThread(CefThread::FILE))); + + BrowserFileSystem* file_system = _Context->file_system(); + // Create the context if it doesn't already exist. + file_system->CreateContext(); + if (file_system->file_system_context()) { + job_factory->SetProtocolHandler( + "filesystem", + fileapi::CreateFileSystemProtocolHandler( + file_system->file_system_context())); + } + + storage_.set_job_factory(job_factory); + + url_request_interceptor_.reset( + BrowserResourceLoaderBridge::CreateRequestInterceptor()); +} + +BrowserRequestContext::~BrowserRequestContext() { +} + +void BrowserRequestContext::SetCookieStoragePath(const FilePath& path) { + REQUIRE_IOT(); + + if (cookie_store() && ((cookie_store_path_.empty() && path.empty()) || + cookie_store_path_ == path)) { + // The path has not changed so don't do anything. + return; + } + + FilePath new_path = path; + + scoped_refptr persistent_store; + if (!new_path.empty()) { + if (!file_util::PathExists(new_path) && + !file_util::CreateDirectory(new_path)) { + NOTREACHED() << "Failed to create cookie storage directory"; + new_path.clear(); + } else { + FilePath cookie_path = new_path.Append(FILE_PATH_LITERAL("Cookies")); + persistent_store = + new SQLitePersistentCookieStore(cookie_path, false, NULL); + } + } + + // 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. + storage_.set_cookie_store( + new net::CookieMonster(persistent_store.get(), NULL)); + cookie_store_path_ = new_path; +} + +const std::string& BrowserRequestContext::GetUserAgent( + const GURL& url) const { + return webkit_glue::GetUserAgent(url); +} diff --git a/cef1/libcef/browser_request_context.h b/cef1/libcef/browser_request_context.h new file mode 100644 index 000000000..e8b05a21a --- /dev/null +++ b/cef1/libcef/browser_request_context.h @@ -0,0 +1,60 @@ +// Copyright (c) 2008 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. + +#ifndef CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_H_ +#define CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_H_ +#pragma once + +#include + +#include "net/http/http_cache.h" +#include "net/http/url_security_manager.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" + +class FilePath; + +namespace webkit_blob { +class BlobStorageController; +} + +// A basic URLRequestContext that only provides an in-memory cookie store. +class BrowserRequestContext : public net::URLRequestContext { + public: + // Use an in-memory cache + BrowserRequestContext(); + virtual ~BrowserRequestContext(); + + // Use an on-disk cache at the specified location. Optionally, use the cache + // in playback or record mode. + BrowserRequestContext(const FilePath& cache_path, + net::HttpCache::Mode cache_mode, + bool no_proxy); + + virtual const std::string& GetUserAgent(const GURL& url) const OVERRIDE; + + // Set the path used for cookie storage. If |path| is empty memory only + // storage will be used. If the old cookie data is being stored on disk it + // will be flushed and closed. + void SetCookieStoragePath(const FilePath& path); + + webkit_blob::BlobStorageController* blob_storage_controller() const { + return blob_storage_controller_.get(); + } + + private: + void Init(const FilePath& cache_path, net::HttpCache::Mode cache_mode, + bool no_proxy); + + net::URLRequestContextStorage storage_; + scoped_ptr blob_storage_controller_; + scoped_ptr url_security_manager_; + scoped_ptr url_request_interceptor_; + FilePath cookie_store_path_; +}; + +#endif // CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_H_ + diff --git a/cef1/libcef/browser_request_context_proxy.cc b/cef1/libcef/browser_request_context_proxy.cc new file mode 100644 index 000000000..1346d88bd --- /dev/null +++ b/cef1/libcef/browser_request_context_proxy.cc @@ -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. + +#include "libcef/browser_request_context_proxy.h" +#include "libcef/browser_impl.h" +#include "libcef/browser_request_context.h" +#include "libcef/cookie_store_proxy.h" + +BrowserRequestContextProxy::BrowserRequestContextProxy( + BrowserRequestContext* context, + CefBrowserImpl* browser) + : context_(context), + browser_(browser) { + DCHECK(context_); + DCHECK(browser_); + + // Cookie store that proxies to the browser implementation. + set_cookie_store(new CefCookieStoreProxy(browser_)); + + // All other values refer to the global request context. + set_net_log(context->net_log()); + set_host_resolver(context->host_resolver()); + set_cert_verifier(context->cert_verifier()); + set_server_bound_cert_service(context->server_bound_cert_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_ftp_transaction_factory(context->ftp_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_accept_charset(context->accept_charset()); + set_accept_language(context->accept_language()); + set_referrer_charset(context->referrer_charset()); + set_job_factory(context->job_factory()); +} + +const std::string& + BrowserRequestContextProxy::GetUserAgent(const GURL& url) const { + return context_->GetUserAgent(url); +} diff --git a/cef1/libcef/browser_request_context_proxy.h b/cef1/libcef/browser_request_context_proxy.h new file mode 100644 index 000000000..8863a8040 --- /dev/null +++ b/cef1/libcef/browser_request_context_proxy.h @@ -0,0 +1,30 @@ +// 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_REQUEST_CONTEXT_PROXY_H_ +#define CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_ +#pragma once + +#include +#include "include/cef_base.h" +#include "net/url_request/url_request_context.h" + +class BrowserRequestContext; +class CefBrowserImpl; + +// A URLRequestContext implementation that proxies cookie requests to the +// client. +class BrowserRequestContextProxy : public net::URLRequestContext { + public: + BrowserRequestContextProxy(BrowserRequestContext* context, + CefBrowserImpl* browser); + + virtual const std::string& GetUserAgent(const GURL& url) const OVERRIDE; + + private: + BrowserRequestContext* context_; + CefRefPtr browser_; +}; + +#endif // CEF_LIBCEF_BROWSER_REQUEST_CONTEXT_PROXY_H_ diff --git a/cef1/libcef/browser_resource_loader_bridge.cc b/cef1/libcef/browser_resource_loader_bridge.cc new file mode 100644 index 000000000..c279eef5a --- /dev/null +++ b/cef1/libcef/browser_resource_loader_bridge.cc @@ -0,0 +1,1189 @@ +// 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. +// +// This file contains an implementation of the ResourceLoaderBridge class. +// The class is implemented using net::URLRequest, meaning it is a "simple" +// version that directly issues requests. The more complicated one used in the +// browser uses IPC. +// +// Because net::URLRequest only provides an asynchronous resource loading API, +// this file makes use of net::URLRequest from a background IO thread. Requests +// for cookies and synchronously loaded resources result in the main thread of +// the application blocking until the IO thread completes the operation. (See +// GetCookies and SyncLoad) +// +// Main thread IO thread +// ----------- --------- +// ResourceLoaderBridge <---o---------> RequestProxy (normal case) +// \ -> net::URLRequest +// o-------> SyncRequestProxy (synchronous case) +// -> net::URLRequest +// +// NOTE: The implementation in this file may be used to have WebKit fetch +// resources in-process. For example, it is handy for building a single- +// process WebKit embedding (e.g., test_shell) that can use net::URLRequest to +// perform URL loads. See renderer/resource_dispatcher.h for details on an +// alternate implementation that defers fetching to another process. + +#include "libcef/browser_resource_loader_bridge.h" +#include "libcef/browser_appcache_system.h" +#include "libcef/browser_request_context.h" +#include "libcef/browser_socket_stream_bridge.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/cef_process.h" +#include "libcef/cef_process_io_thread.h" +#include "libcef/external_protocol_handler.h" +#include "libcef/request_impl.h" +#include "libcef/response_impl.h" +#include "libcef/http_header_utils.h" + +#include "base/bind.h" +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/memory/ref_counted.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" +#include "base/time.h" +#include "base/timer.h" +#include "base/threading/thread.h" +#include "base/utf_string_conversions.h" +#include "net/base/auth.h" +#include "net/base/file_stream.h" +#include "net/base/io_buffer.h" +#include "net/base/load_flags.h" +#include "net/base/net_errors.h" +#include "net/base/net_util.h" +#include "net/base/static_cookie_policy.h" +#include "net/base/upload_data.h" +#include "net/http/http_cache.h" +#include "net/http/http_request_headers.h" +#include "net/http/http_response_headers.h" +#include "net/proxy/proxy_service.h" +#include "net/url_request/url_request.h" +#include "net/url_request/url_request_job_manager.h" +#include "net/url_request/url_request_redirect_job.h" +#include "webkit/appcache/appcache_interfaces.h" +#include "webkit/blob/blob_storage_controller.h" +#include "webkit/blob/shareable_file_reference.h" +#include "webkit/fileapi/file_system_context.h" +#include "webkit/fileapi/file_system_dir_url_request_job.h" +#include "webkit/fileapi/file_system_url_request_job.h" +#include "webkit/glue/resource_loader_bridge.h" +#include "webkit/glue/webkit_glue.h" + +#if defined(OS_MACOSX) || defined(OS_WIN) +#include "crypto/nss_util.h" +#endif + +using net::HttpResponseHeaders; +using net::StaticCookiePolicy; +using net::URLRequestStatus; +using webkit_blob::ShareableFileReference; +using webkit_glue::ResourceLoaderBridge; +using webkit_glue::ResourceResponseInfo; + + +namespace { + +static const char kCefUserData[] = "cef_userdata"; + +struct RequestParams { + std::string method; + GURL url; + GURL first_party_for_cookies; + GURL referrer; + WebKit::WebReferrerPolicy referrer_policy; + std::string headers; + int load_flags; + ResourceType::Type request_type; + int appcache_host_id; + bool download_to_file; + scoped_refptr upload; + net::RequestPriority priority; +}; + +// The interval for calls to RequestProxy::MaybeUpdateUploadProgress +static const int kUpdateUploadProgressIntervalMsec = 100; + +class ExtraRequestInfo : public net::URLRequest::Data { + public: + ExtraRequestInfo(CefBrowserImpl* browser, ResourceType::Type resource_type) + : browser_(browser), + resource_type_(resource_type), + allow_download_(resource_type == ResourceType::MAIN_FRAME || + resource_type == ResourceType::SUB_FRAME) { + } + + // The browser pointer is guaranteed to be valid for the lifespan of the + // request. The pointer will be NULL in cases where the request was + // initiated via the CefWebURLRequest API instead of by a browser window. + CefBrowserImpl* browser() const { return browser_; } + + // Identifies the type of resource, such as subframe, media, etc. + ResourceType::Type resource_type() const { return resource_type_; } + bool allow_download() const { return allow_download_; } + + private: + CefBrowserImpl* browser_; + ResourceType::Type resource_type_; + bool allow_download_; +}; + +// Used to intercept redirect requests. +class RequestInterceptor : public net::URLRequest::Interceptor { + public: + RequestInterceptor() { + REQUIRE_IOT(); + net::URLRequestJobManager::GetInstance()->RegisterRequestInterceptor(this); + } + ~RequestInterceptor() { + REQUIRE_IOT(); + net::URLRequestJobManager::GetInstance()-> + UnregisterRequestInterceptor(this); + } + + virtual net::URLRequestJob* MaybeIntercept(net::URLRequest* request) + OVERRIDE { + return NULL; + } + + virtual net::URLRequestJob* MaybeInterceptRedirect(net::URLRequest* request, + const GURL& location) OVERRIDE { + REQUIRE_IOT(); + + ExtraRequestInfo* info = + static_cast(request->GetUserData(kCefUserData)); + if (!info) + return NULL; + + CefRefPtr browser = info->browser(); + if (!browser.get()) + return NULL; + CefRefPtr client = browser->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetRequestHandler(); + if (!handler.get()) + return NULL; + + CefString newUrlStr = location.spec(); + handler->OnResourceRedirect(browser, 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, new_url); + } + + return NULL; + } + + DISALLOW_COPY_AND_ASSIGN(RequestInterceptor); +}; + +// The RequestProxy does most of its work on the IO thread. The Start and +// Cancel methods are proxied over to the IO thread, where an net::URLRequest +// object is instantiated. +class RequestProxy : public net::URLRequest::Delegate, + public base::RefCountedThreadSafe { + public: + // Takes ownership of the params. + explicit RequestProxy(CefRefPtr browser) + : download_to_file_(false), + file_stream_(NULL), + buf_(new net::IOBuffer(kDataSize)), + browser_(browser), + owner_loop_(NULL), + peer_(NULL), + last_upload_position_(0), + defers_loading_(false), + defers_loading_want_read_(false) { + } + + void DropPeer() { + DCHECK(MessageLoop::current() == owner_loop_); + peer_ = NULL; + } + + void Start(ResourceLoaderBridge::Peer* peer, RequestParams* params) { + peer_ = peer; + owner_loop_ = MessageLoop::current(); + + InitializeParams(params); + + // proxy over to the io thread + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncStart, this, params)); + } + + void Cancel() { + DCHECK(MessageLoop::current() == owner_loop_); + + if (download_handler_.get()) { + // WebKit will try to cancel the download but we won't allow it. + return; + } + + // proxy over to the io thread + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncCancel, this)); + } + + void SetDefersLoading(bool defer) { + DCHECK(MessageLoop::current() == owner_loop_); + + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncSetDefersLoading, this, defer)); + } + + protected: + friend class base::RefCountedThreadSafe; + + virtual ~RequestProxy() { + // If we have a request, then we'd better be on the io thread! + DCHECK(!request_.get() || CefThread::CurrentlyOn(CefThread::IO)); + } + + virtual void InitializeParams(RequestParams* params) { + params->priority = net::MEDIUM; + } + + // -------------------------------------------------------------------------- + // The following methods are called on the owner's thread in response to + // various net::URLRequest callbacks. The event hooks, defined below, trigger + // these methods asynchronously. + + void NotifyReceivedRedirect(const GURL& new_url, + const ResourceResponseInfo& info) { + DCHECK(MessageLoop::current() == owner_loop_); + + bool has_new_first_party_for_cookies = false; + GURL new_first_party_for_cookies; + if (peer_ && peer_->OnReceivedRedirect(new_url, info, + &has_new_first_party_for_cookies, + &new_first_party_for_cookies)) { + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncFollowDeferredRedirect, this, + has_new_first_party_for_cookies, new_first_party_for_cookies)); + } else { + Cancel(); + } + } + + void NotifyReceivedResponse(const ResourceResponseInfo& info, + const GURL& url, bool allow_download) { + DCHECK(MessageLoop::current() == owner_loop_); + + if (browser_.get() && info.headers.get()) { + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetRequestHandler(); + + if (handler.get()) { + CefRefPtr response = new CefResponseImpl(); + // Transfer response headers + if (info.headers) { + CefResponse::HeaderMap headerMap; + void* header_index = NULL; + std::string name, value; + while (info.headers->EnumerateHeaderLines(&header_index, &name, + &value)) { + if (!name.empty() && !value.empty()) + headerMap.insert(std::make_pair(name, value)); + } + response->SetHeaderMap(headerMap); + response->SetStatusText(info.headers->GetStatusText()); + response->SetStatus(info.headers->response_code()); + } + response->SetMimeType(info.mime_type); + handler->OnResourceResponse(browser_.get(), url.spec(), response, + content_filter_); + + std::string content_disposition; + info.headers->GetNormalizedHeader("Content-Disposition", + &content_disposition); + + if (allow_download && + webkit_glue::ShouldDownload(content_disposition, info.mime_type)) { + string16 filename = net::GetSuggestedFilename(url, + content_disposition, info.charset, "", info.mime_type, + "download"); + CefRefPtr dl_handler; + if (handler->GetDownloadHandler(browser_.get(), info.mime_type, + filename, info.content_length, + dl_handler)) { + download_handler_ = dl_handler; + } + } + } + } + + if (peer_) + peer_->OnReceivedResponse(info); + } + + void NotifyReceivedData(int bytes_read) { + DCHECK(MessageLoop::current() == owner_loop_); + + if (!peer_) + return; + + // Make a local copy of buf_, since AsyncReadData reuses it. + scoped_array buf_copy(new char[bytes_read]); + memcpy(buf_copy.get(), buf_->data(), bytes_read); + + // Continue reading more data into buf_ + // Note: Doing this before notifying our peer ensures our load events get + // dispatched in a manner consistent with DumpRenderTree (and also avoids a + // race condition). If the order of the next 2 functions were reversed, the + // peer could generate new requests in response to the received data, which + // when run on the io thread, could race against this function in doing + // another InvokeLater. See bug 769249. + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncReadData, this)); + + CefRefPtr resourceStream; + + if (content_filter_.get()) + content_filter_->ProcessData(buf_copy.get(), bytes_read, resourceStream); + + if (resourceStream.get()) { + // The filter made some changes to the data in the buffer. + resourceStream->Seek(0, SEEK_END); + bytes_read = resourceStream->Tell(); + resourceStream->Seek(0, SEEK_SET); + + buf_copy.reset(new char[bytes_read]); + resourceStream->Read(buf_copy.get(), 1, bytes_read); + } + + if (download_handler_.get() && + !download_handler_->ReceivedData(buf_copy.get(), bytes_read)) { + // Cancel loading by proxying over to the io thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncCancel, this)); + } + + peer_->OnReceivedData(buf_copy.get(), bytes_read, -1); + } + + void NotifyDownloadedData(int bytes_read) { + DCHECK(MessageLoop::current() == owner_loop_); + + if (!peer_) + return; + + // Continue reading more data, see the comment in NotifyReceivedData. + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncReadData, this)); + + peer_->OnDownloadedData(bytes_read); + } + + void NotifyCompletedRequest(const net::URLRequestStatus& status, + const std::string& security_info, + const base::TimeTicks& complete_time) { + DCHECK(MessageLoop::current() == owner_loop_); + + // Drain the content filter of all remaining data + if (content_filter_.get()) { + CefRefPtr remainder; + content_filter_->Drain(remainder); + + if (remainder.get()) { + remainder->Seek(0, SEEK_END); + int size = static_cast(remainder->Tell()); + if (size > 0) { + remainder->Seek(0, SEEK_SET); + scoped_array buf(new char[size]); + remainder->Read(buf.get(), 1, size); + + if (download_handler_.get() && + !download_handler_->ReceivedData(buf.get(), size)) { + // Cancel loading by proxying over to the io thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &RequestProxy::AsyncCancel, this)); + } + + if (peer_) + peer_->OnReceivedData(buf.get(), size, -1); + } + } + content_filter_ = NULL; + } + + if (download_handler_.get()) { + download_handler_->Complete(); + download_handler_ = NULL; + } + + if (peer_) { + peer_->OnCompletedRequest(status, security_info, complete_time); + DropPeer(); // ensure no further notifications + } + } + + void NotifyUploadProgress(uint64 position, uint64 size) { + DCHECK(MessageLoop::current() == owner_loop_); + + if (peer_) + peer_->OnUploadProgress(position, size); + } + + // -------------------------------------------------------------------------- + // The following methods are called on the io thread. They correspond to + // actions performed on the owner's thread. + + void AsyncStart(RequestParams* params) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + bool handled = false; + + if (browser_.get()) { + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetRequestHandler(); + + if (handler.get()) { + // Build the request object for passing to the handler + CefRefPtr request(new CefRequestImpl()); + CefRequestImpl* requestimpl = + static_cast(request.get()); + + std::string originalUrl(params->url.spec()); + requestimpl->SetURL(originalUrl); + requestimpl->SetMethod(params->method); + + // Transfer request headers + CefRequest::HeaderMap headerMap; + HttpHeaderUtils::ParseHeaders(params->headers, headerMap); + headerMap.insert(std::make_pair("Referer", params->referrer.spec())); + requestimpl->SetHeaderMap(headerMap); + + // Transfer post data, if any + scoped_refptr upload = params->upload; + if (upload.get()) { + CefRefPtr postdata(new CefPostDataImpl()); + static_cast(postdata.get())->Set(*upload.get()); + requestimpl->SetPostData(postdata); + } + + int loadFlags = params->load_flags; + + // Handler output will be returned in these variables + CefString redirectUrl; + CefRefPtr resourceStream; + CefRefPtr response(new CefResponseImpl()); + + handled = handler->OnBeforeResourceLoad(browser_.get(), request, + redirectUrl, resourceStream, response, loadFlags); + if (!handled) { + // Observe URL from request. + const std::string requestUrl(request->GetURL()); + if (requestUrl != originalUrl) + params->url = GURL(requestUrl); + else if (!redirectUrl.empty()) + params->url = GURL(std::string(redirectUrl)); + + // Observe method from request. + params->method = request->GetMethod(); + + // Observe headers from request. + request->GetHeaderMap(headerMap); + CefString referrerStr; + referrerStr.FromASCII("Referer"); + CefRequest::HeaderMap::iterator referrer = + headerMap.find(referrerStr); + if (referrer == headerMap.end()) { + params->referrer = GURL(); + } else { + params->referrer = GURL(std::string(referrer->second)); + headerMap.erase(referrer); + } + params->headers = HttpHeaderUtils::GenerateHeaders(headerMap); + + // Observe post data from request. + CefRefPtr postData = request->GetPostData(); + if (postData.get()) { + params->upload = new net::UploadData(); + static_cast(postData.get())->Get(*params->upload); + } + } + + if (handled) { + // cancel the resource load + OnCompletedRequest( + URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED), + std::string(), base::TimeTicks()); + } else if (resourceStream.get()) { + // load from the provided resource stream + handled = true; + + resourceStream->Seek(0, SEEK_END); + int64 offset = resourceStream->Tell(); + resourceStream->Seek(0, SEEK_SET); + + resource_stream_ = resourceStream; + + CefResponseImpl* responseImpl = + static_cast(response.get()); + + ResourceResponseInfo info; + info.content_length = offset; + info.mime_type = response->GetMimeType(); + info.headers = responseImpl->GetResponseHeaders(); + OnReceivedResponse(info, params->url); + AsyncReadData(); + } else if (response->GetStatus() != 0) { + // status set, but no resource stream + handled = true; + + CefResponseImpl* responseImpl = + static_cast(response.get()); + + ResourceResponseInfo info; + info.content_length = 0; + info.mime_type = response->GetMimeType(); + info.headers = responseImpl->GetResponseHeaders(); + OnReceivedResponse(info, params->url); + AsyncReadData(); + } + + if (!handled && ResourceType::IsFrame(params->request_type) && + !net::URLRequest::IsHandledProtocol(params->url.scheme())) { + bool allow_os_execution = false; + handled = handler->OnProtocolExecution(browser_.get(), + params->url.spec(), allow_os_execution); + if (!handled && allow_os_execution && + ExternalProtocolHandler::HandleExternalProtocol(params->url)) { + handled = true; + } + + if (handled) { + OnCompletedRequest( + URLRequestStatus(URLRequestStatus::HANDLED_EXTERNALLY, net::OK), + std::string(), base::TimeTicks()); + } + } + } + } + + if (!handled) { + // Might need to resolve the blob references in the upload data. + if (params->upload) { + _Context->request_context()->blob_storage_controller()-> + ResolveBlobReferencesInUploadData(params->upload.get()); + } + + request_.reset(new net::URLRequest(params->url, this)); + request_->set_priority(params->priority); + request_->set_method(params->method); + request_->set_first_party_for_cookies(params->first_party_for_cookies); + request_->set_referrer(params->referrer.spec()); + webkit_glue::ConfigureURLRequestForReferrerPolicy( + request_.get(), params->referrer_policy); + net::HttpRequestHeaders headers; + headers.AddHeadersFromString(params->headers); + request_->SetExtraRequestHeaders(headers); + request_->set_load_flags(params->load_flags); + request_->set_upload(params->upload.get()); + request_->set_context(browser_.get() ? browser_->request_context_proxy() : + _Context->request_context()); + request_->SetUserData(kCefUserData, + new ExtraRequestInfo(browser_.get(), params->request_type)); + BrowserAppCacheSystem::SetExtraRequestInfo( + request_.get(), params->appcache_host_id, params->request_type); + + download_to_file_ = params->download_to_file; + if (download_to_file_) { + FilePath path; + if (file_util::CreateTemporaryFile(&path)) { + downloaded_file_ = ShareableFileReference::GetOrCreate( + path, ShareableFileReference::DELETE_ON_FINAL_RELEASE, + base::MessageLoopProxy::current()); + file_stream_.OpenSync( + path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_WRITE); + } + } + + request_->Start(); + + if (request_.get() && request_->has_upload() && + params->load_flags & net::LOAD_ENABLE_UPLOAD_PROGRESS) { + upload_progress_timer_.Start(FROM_HERE, + base::TimeDelta::FromMilliseconds( + kUpdateUploadProgressIntervalMsec), + this, &RequestProxy::MaybeUpdateUploadProgress); + } + } + + delete params; + } + + void AsyncCancel() { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + // This can be null in cases where the request is already done. + if (!resource_stream_.get() && !request_.get()) + return; + + if (request_.get()) + request_->Cancel(); + Done(); + } + + void AsyncFollowDeferredRedirect(bool has_new_first_party_for_cookies, + const GURL& new_first_party_for_cookies) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + // This can be null in cases where the request is already done. + if (!request_.get()) + return; + + if (has_new_first_party_for_cookies) + request_->set_first_party_for_cookies(new_first_party_for_cookies); + request_->FollowDeferredRedirect(); + } + + void AsyncSetDefersLoading(bool defer) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (defers_loading_ != defer) { + defers_loading_ = defer; + if (!defers_loading_ && defers_loading_want_read_) { + // Perform the pending AsyncReadData now. + defers_loading_want_read_ = false; + AsyncReadData(); + } + } + } + + void AsyncReadData() { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + // Pause downloading if we're in deferred mode. + if (defers_loading_) { + defers_loading_want_read_ = true; + return; + } + + if (resource_stream_.get()) { + // Read from the handler-provided resource stream + int bytes_read = resource_stream_->Read(buf_->data(), 1, kDataSize); + if (bytes_read > 0) { + OnReceivedData(bytes_read); + } else { + Done(); + } + return; + } + + // This can be null in cases where the request is already done. + if (!request_.get()) + return; + + if (request_->status().is_success()) { + int bytes_read; + if (request_->Read(buf_, kDataSize, &bytes_read) && bytes_read) { + OnReceivedData(bytes_read); + } else if (!request_->status().is_io_pending()) { + Done(); + } // else wait for OnReadCompleted + } else { + Done(); + } + } + + // -------------------------------------------------------------------------- + // The following methods are event hooks (corresponding to net::URLRequest + // callbacks) that run on the IO thread. They are designed to be overridden + // by the SyncRequestProxy subclass. + + virtual void OnReceivedRedirect( + const GURL& new_url, + const ResourceResponseInfo& info, + bool* defer_redirect) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + *defer_redirect = true; // See AsyncFollowDeferredRedirect + owner_loop_->PostTask(FROM_HERE, base::Bind( + &RequestProxy::NotifyReceivedRedirect, this, new_url, info)); + } + + virtual void OnReceivedResponse( + const ResourceResponseInfo& info, + // only used when loading from a resource stream + const GURL& simulated_url) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + GURL url; + bool allow_download(false); + if (request_.get()) { + url = request_->url(); + ExtraRequestInfo* info = + static_cast(request_->GetUserData(kCefUserData)); + if (info) + allow_download = info->allow_download(); + } else if (!simulated_url.is_empty() && simulated_url.is_valid()) { + url = simulated_url; + } + + owner_loop_->PostTask(FROM_HERE, base::Bind( + &RequestProxy::NotifyReceivedResponse, this, info, url, + allow_download)); + } + + virtual void OnReceivedData(int bytes_read) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (download_to_file_) { + file_stream_.WriteSync(buf_->data(), bytes_read); + owner_loop_->PostTask(FROM_HERE, base::Bind( + &RequestProxy::NotifyDownloadedData, this, bytes_read)); + return; + } + + owner_loop_->PostTask(FROM_HERE, base::Bind( + &RequestProxy::NotifyReceivedData, this, bytes_read)); + } + + virtual void OnCompletedRequest(const net::URLRequestStatus& status, + const std::string& security_info, + const base::TimeTicks& complete_time) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (download_to_file_) + file_stream_.CloseSync(); + + owner_loop_->PostTask(FROM_HERE, base::Bind( + &RequestProxy::NotifyCompletedRequest, this, status, security_info, + complete_time)); + } + + // -------------------------------------------------------------------------- + // net::URLRequest::Delegate implementation: + + virtual void OnReceivedRedirect(net::URLRequest* request, + const GURL& new_url, + bool* defer_redirect) OVERRIDE { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + DCHECK(request->status().is_success()); + ResourceResponseInfo info; + PopulateResponseInfo(request, &info); + OnReceivedRedirect(new_url, info, defer_redirect); + } + + virtual void OnResponseStarted(net::URLRequest* request) OVERRIDE { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (request->status().is_success()) { + ResourceResponseInfo info; + PopulateResponseInfo(request, &info); + OnReceivedResponse(info, GURL::EmptyGURL()); + AsyncReadData(); // start reading + } else { + Done(); + } + } + + virtual void OnAuthRequired(net::URLRequest* request, + net::AuthChallengeInfo* auth_info) OVERRIDE { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (browser_.get()) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + CefString username, password; + if (handler->GetAuthCredentials(browser_.get(), + auth_info->is_proxy, + auth_info->challenger.host(), + auth_info->challenger.port(), + auth_info->realm, + auth_info->scheme, + username, password)) { + request->SetAuth(net::AuthCredentials(username, password)); + return; + } + } + } + } + + request->CancelAuth(); + } + + virtual void OnSSLCertificateError(net::URLRequest* request, + const net::SSLInfo& ssl_info, + bool fatal) OVERRIDE { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + // Allow all certificate errors. + request->ContinueDespiteLastError(); + } + + virtual void OnReadCompleted(net::URLRequest* request, + int bytes_read) OVERRIDE { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (request->status().is_success() && bytes_read > 0) { + OnReceivedData(bytes_read); + } else { + Done(); + } + } + + // -------------------------------------------------------------------------- + // Helpers and data: + + void Done() { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (resource_stream_.get()) { + // Resource stream reads always complete successfully + OnCompletedRequest(URLRequestStatus(URLRequestStatus::SUCCESS, 0), + std::string(), base::TimeTicks()); + resource_stream_ = NULL; + } else if (request_.get()) { + if (upload_progress_timer_.IsRunning()) { + MaybeUpdateUploadProgress(); + upload_progress_timer_.Stop(); + } + DCHECK(request_.get()); + OnCompletedRequest(request_->status(), std::string(), base::TimeTicks()); + request_.reset(); // destroy on the io thread + } + } + + void MaybeUpdateUploadProgress() { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + // If a redirect is received upload is cancelled in net::URLRequest, we + // should try to stop the |upload_progress_timer_| timer and return. + if (!request_->has_upload()) { + if (upload_progress_timer_.IsRunning()) + upload_progress_timer_.Stop(); + return; + } + + // GetContentLengthSync() may perform file IO, but it's ok here, as file + // IO is not prohibited in IOThread defined in the file. + uint64 size = request_->get_upload()->GetContentLengthSync(); + uint64 position = request_->GetUploadProgress(); + if (position == last_upload_position_) + return; // no progress made since last time + + const uint64 kHalfPercentIncrements = 200; + const base::TimeDelta kOneSecond = base::TimeDelta::FromMilliseconds(1000); + + uint64 amt_since_last = position - last_upload_position_; + base::TimeDelta time_since_last = base::TimeTicks::Now() - + last_upload_ticks_; + + bool is_finished = (size == position); + bool enough_new_progress = (amt_since_last > (size / + kHalfPercentIncrements)); + bool too_much_time_passed = time_since_last > kOneSecond; + + if (is_finished || enough_new_progress || too_much_time_passed) { + owner_loop_->PostTask(FROM_HERE, base::Bind( + &RequestProxy::NotifyUploadProgress, this, position, size)); + last_upload_ticks_ = base::TimeTicks::Now(); + last_upload_position_ = position; + } + } + + void PopulateResponseInfo(net::URLRequest* request, + ResourceResponseInfo* info) const { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + info->request_time = request->request_time(); + info->response_time = request->response_time(); + info->headers = request->response_headers(); + request->GetMimeType(&info->mime_type); + request->GetCharset(&info->charset); + info->content_length = request->GetExpectedContentSize(); + if (downloaded_file_) + info->download_file_path = downloaded_file_->path(); + BrowserAppCacheSystem::GetExtraResponseInfo( + request, + &info->appcache_id, + &info->appcache_manifest_url); + } + + scoped_ptr request_; + CefRefPtr resource_stream_; + + // Support for request.download_to_file behavior. + bool download_to_file_; + net::FileStream file_stream_; + scoped_refptr downloaded_file_; + + // Size of our async IO data buffers. Limited by the sanity check in + // URLRequestJob::Read(). + static const int kDataSize = 1000000-1; + + // read buffer for async IO + scoped_refptr buf_; + + CefRefPtr browser_; + + MessageLoop* owner_loop_; + + // This is our peer in WebKit (implemented as ResourceHandleInternal). We do + // not manage its lifetime, and we may only access it from the owner's + // message loop (owner_loop_). + ResourceLoaderBridge::Peer* peer_; + + // Timer used to pull upload progress info. + base::RepeatingTimer upload_progress_timer_; + + // Info used to determine whether or not to send an upload progress update. + uint64 last_upload_position_; + base::TimeTicks last_upload_ticks_; + + CefRefPtr download_handler_; + CefRefPtr content_filter_; + + // True if loading of data is currently deferred. + bool defers_loading_; + + // True if an AsyncReadData was scheduled while we were deferred. + bool defers_loading_want_read_; +}; + +//----------------------------------------------------------------------------- + +class SyncRequestProxy : public RequestProxy { + public: + explicit SyncRequestProxy(CefRefPtr browser, + ResourceLoaderBridge::SyncLoadResponse* result) + : RequestProxy(browser), result_(result), event_(true, false) { + } + + void WaitForCompletion() { + event_.Wait(); + } + + // -------------------------------------------------------------------------- + // Event hooks that run on the IO thread: + + virtual void OnReceivedRedirect( + const GURL& new_url, + const ResourceResponseInfo& info, + bool* defer_redirect) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + // TODO(darin): It would be much better if this could live in WebCore, but + // doing so requires API changes at all levels. Similar code exists in + // WebCore/platform/network/cf/ResourceHandleCFNet.cpp :-( + if (new_url.GetOrigin() != result_->url.GetOrigin()) { + DLOG(WARNING) << "Cross origin redirect denied"; + Cancel(); + return; + } + result_->url = new_url; + } + + virtual void OnReceivedResponse(const ResourceResponseInfo& info, + const GURL&) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + *static_cast(result_) = info; + } + + virtual void OnReceivedData(int bytes_read) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (download_to_file_) + file_stream_.WriteSync(buf_->data(), bytes_read); + else + result_->data.append(buf_->data(), bytes_read); + AsyncReadData(); // read more (may recurse) + } + + virtual void OnCompletedRequest(const net::URLRequestStatus& status, + const std::string& security_info, + const base::TimeTicks& complete_time) { + DCHECK(CefThread::CurrentlyOn(CefThread::IO)); + + if (download_to_file_) + file_stream_.CloseSync(); + + result_->status = status; + event_.Signal(); + } + + protected: + virtual void InitializeParams(RequestParams* params) { + // For synchronous requests ignore load limits to avoid a deadlock problem + // in SyncRequestProxy (issue #192). + params->load_flags |= net::LOAD_IGNORE_LIMITS; + params->priority = net::HIGHEST; + } + + private: + ResourceLoaderBridge::SyncLoadResponse* result_; + base::WaitableEvent event_; +}; + +//----------------------------------------------------------------------------- + +class ResourceLoaderBridgeImpl : public ResourceLoaderBridge, + public base::NonThreadSafe { + public: + ResourceLoaderBridgeImpl(CefRefPtr browser, + const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) + : browser_(browser), + params_(new RequestParams), + proxy_(NULL) { + params_->method = request_info.method; + params_->url = request_info.url; + params_->first_party_for_cookies = request_info.first_party_for_cookies; + params_->referrer = request_info.referrer; + params_->referrer_policy = request_info.referrer_policy; + params_->headers = request_info.headers; + params_->load_flags = request_info.load_flags; + params_->request_type = request_info.request_type; + params_->appcache_host_id = request_info.appcache_host_id; + params_->download_to_file = request_info.download_to_file; + } + + virtual ~ResourceLoaderBridgeImpl() { + if (proxy_) { + proxy_->DropPeer(); + // Let the proxy die on the IO thread + CefThread::ReleaseSoon(CefThread::IO, FROM_HERE, proxy_.release()); + } + } + + // -------------------------------------------------------------------------- + // ResourceLoaderBridge implementation: + + virtual void AppendDataToUpload(const char* data, int data_len) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->AppendBytes(data, data_len); + } + + virtual void AppendFileRangeToUpload( + const FilePath& file_path, + uint64 offset, + uint64 length, + const base::Time& expected_modification_time) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->AppendFileRange(file_path, offset, length, + expected_modification_time); + } + + virtual void AppendBlobToUpload(const GURL& blob_url) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->AppendBlob(blob_url); + } + + virtual void SetUploadIdentifier(int64 identifier) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(params_.get()); + if (!params_->upload) + params_->upload = new net::UploadData(); + params_->upload->set_identifier(identifier); + } + + virtual bool Start(Peer* peer) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(!proxy_); + + proxy_ = new RequestProxy(browser_); + proxy_->Start(peer, params_.release()); + + return true; // Any errors will be reported asynchronously. + } + + virtual void Cancel() OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(proxy_); + proxy_->Cancel(); + } + + virtual void SetDefersLoading(bool value) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(proxy_); + proxy_->SetDefersLoading(value); + } + + virtual void SyncLoad(SyncLoadResponse* response) OVERRIDE { + DCHECK(CalledOnValidThread()); + DCHECK(!proxy_); + + // this may change as the result of a redirect + response->url = params_->url; + + proxy_ = new SyncRequestProxy(browser_, response); + proxy_->Start(NULL, params_.release()); + + static_cast(proxy_.get())->WaitForCompletion(); + } + + private: + CefRefPtr browser_; + + // Ownership of params_ is transfered to the proxy when the proxy is created. + scoped_ptr params_; + + // The request proxy is allocated when we start the request, and then it + // sticks around until this ResourceLoaderBridge is destroyed. + scoped_refptr proxy_; +}; + +} // anonymous namespace + +//----------------------------------------------------------------------------- + +// static +webkit_glue::ResourceLoaderBridge* BrowserResourceLoaderBridge::Create( + const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + + CefRefPtr browser = + _Context->GetBrowserByID(request_info.routing_id); + return new ResourceLoaderBridgeImpl(browser.get(), request_info); +} + +//----------------------------------------------------------------------------- + +// static +CefRefPtr BrowserResourceLoaderBridge::GetBrowserForRequest( + net::URLRequest* request) { + REQUIRE_IOT(); + ExtraRequestInfo* extra_info = + static_cast(request->GetUserData(kCefUserData)); + if (extra_info) + return extra_info->browser(); + return NULL; +} + +// static +scoped_refptr +BrowserResourceLoaderBridge::GetCacheThread() { + return CefThread::GetMessageLoopProxyForThread(CefThread::FILE); +} + +// static +net::URLRequest::Interceptor* +BrowserResourceLoaderBridge::CreateRequestInterceptor() { + return new RequestInterceptor(); +} diff --git a/cef1/libcef/browser_resource_loader_bridge.h b/cef1/libcef/browser_resource_loader_bridge.h new file mode 100644 index 000000000..d8ac3acb2 --- /dev/null +++ b/cef1/libcef/browser_resource_loader_bridge.h @@ -0,0 +1,40 @@ +// Copyright (c) 2008 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. + +#ifndef CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_ +#define CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_ +#pragma once + +#include + +#include "include/cef_base.h" +#include "base/message_loop_proxy.h" +#include "net/url_request/url_request.h" +#include "webkit/glue/resource_loader_bridge.h" + +class CefBrowserImpl; +class GURL; + +class BrowserResourceLoaderBridge { + public: + // Return the CefBrowser associated with the specified request. The browser + // will be NULL in cases where the request was initiated using the + // CefWebURLRequest API. + static CefRefPtr GetBrowserForRequest( + net::URLRequest* request); + + // Creates a ResourceLoaderBridge instance. + static webkit_glue::ResourceLoaderBridge* Create( + const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info); + + static scoped_refptr GetCacheThread(); + + // Used for intercepting URL redirects. Only one interceptor will be created + // and its lifespan is controlled by the BrowserRequestContext. + static net::URLRequest::Interceptor* CreateRequestInterceptor(); +}; + +#endif // CEF_LIBCEF_BROWSER_RESOURCE_LOADER_BRIDGE_H_ + diff --git a/cef1/libcef/browser_settings.cc b/cef1/libcef/browser_settings.cc new file mode 100644 index 000000000..f208e0236 --- /dev/null +++ b/cef1/libcef/browser_settings.cc @@ -0,0 +1,155 @@ +// 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_settings.h" +#include "include/internal/cef_types_wrappers.h" +#include "base/utf_string_conversions.h" +#include "webkit/glue/webpreferences.h" + +using webkit_glue::WebPreferences; + +void BrowserToWebSettings(const CefBrowserSettings& cef, WebPreferences& web) { + if (cef.standard_font_family.length > 0) { + web.standard_font_family_map[WebPreferences::kCommonScript] = + CefString(&cef.standard_font_family); + } else { + web.standard_font_family_map[WebPreferences::kCommonScript] = + ASCIIToUTF16("Times"); + } + + if (cef.fixed_font_family.length > 0) { + web.fixed_font_family_map[WebPreferences::kCommonScript] = + CefString(&cef.fixed_font_family); + } else { + web.fixed_font_family_map[WebPreferences::kCommonScript] = + ASCIIToUTF16("Courier"); + } + + if (cef.serif_font_family.length > 0) { + web.serif_font_family_map[WebPreferences::kCommonScript] = + CefString(&cef.serif_font_family); + } else { + web.serif_font_family_map[WebPreferences::kCommonScript] = + ASCIIToUTF16("Times"); + } + + if (cef.sans_serif_font_family.length > 0) { + web.sans_serif_font_family_map[WebPreferences::kCommonScript] = + CefString(&cef.sans_serif_font_family); + } else { + web.sans_serif_font_family_map[WebPreferences::kCommonScript] = + ASCIIToUTF16("Helvetica"); + } + + // These two fonts below are picked from the intersection of + // Win XP font list and Vista font list : + // http://www.microsoft.com/typography/fonts/winxp.htm + // http://blogs.msdn.com/michkap/archive/2006/04/04/567881.aspx + // Some of them are installed only with CJK and complex script + // support enabled on Windows XP and are out of consideration here. + // (although we enabled both on our buildbots.) + // They (especially Impact for fantasy) are not typical cursive + // and fantasy fonts, but it should not matter for layout tests + // as long as they're available. + + if (cef.cursive_font_family.length > 0) { + web.cursive_font_family_map[WebPreferences::kCommonScript] = + CefString(&cef.cursive_font_family); + } else { + web.cursive_font_family_map[WebPreferences::kCommonScript] = +#if defined(OS_MACOSX) + ASCIIToUTF16("Apple Chancery"); +#else + ASCIIToUTF16("Comic Sans MS"); +#endif + } + + if (cef.fantasy_font_family.length > 0) { + web.fantasy_font_family_map[WebPreferences::kCommonScript] = + CefString(&cef.fantasy_font_family); + } else { + web.fantasy_font_family_map[WebPreferences::kCommonScript] = +#if defined(OS_MACOSX) + ASCIIToUTF16("Papyrus"); +#else + ASCIIToUTF16("Impact"); +#endif + } + + if (cef.default_font_size > 0) + web.default_font_size = cef.default_font_size; + else + web.default_font_size = 16; + + if (cef.default_fixed_font_size > 0) + web.default_fixed_font_size = cef.default_fixed_font_size; + else + web.default_fixed_font_size = 13; + + if (cef.minimum_font_size > 0) + web.minimum_font_size = cef.minimum_font_size; + else + web.minimum_font_size = 1; + + if (cef.minimum_logical_font_size > 0) + web.minimum_logical_font_size = cef.minimum_logical_font_size; + else + web.minimum_logical_font_size = 9; + + if (cef.default_encoding.length > 0) + web.default_encoding = CefString(&cef.default_encoding); + else + web.default_encoding = "ISO-8859-1"; + + web.javascript_enabled = !cef.javascript_disabled; + web.web_security_enabled = !cef.web_security_disabled; + web.javascript_can_open_windows_automatically = + !cef.javascript_open_windows_disallowed; + web.loads_images_automatically = !cef.image_load_disabled; + web.plugins_enabled = !cef.plugins_disabled; + web.dom_paste_enabled = !cef.dom_paste_disabled; + web.developer_extras_enabled = !cef.developer_tools_disabled; + web.inspector_settings.clear(); + web.site_specific_quirks_enabled = !cef.site_specific_quirks_disabled; + web.shrinks_standalone_images_to_fit = cef.shrink_standalone_images_to_fit; + web.uses_universal_detector = cef.encoding_detector_enabled; + web.text_areas_are_resizable = !cef.text_area_resize_disabled; + web.java_enabled = !cef.java_disabled; + web.allow_scripts_to_close_windows = !cef.javascript_close_windows_disallowed; + web.uses_page_cache = !cef.page_cache_disabled; + web.remote_fonts_enabled = !cef.remote_fonts_disabled; + web.javascript_can_access_clipboard = + !cef.javascript_access_clipboard_disallowed; + web.xss_auditor_enabled = cef.xss_auditor_enabled; + web.local_storage_enabled = !cef.local_storage_disabled; + web.databases_enabled = !cef.databases_disabled; + web.application_cache_enabled = !cef.application_cache_disabled; + web.tabs_to_links = !cef.tab_to_links_disabled; + web.caret_browsing_enabled = cef.caret_browsing_enabled; + web.hyperlink_auditing_enabled = !cef.hyperlink_auditing_disabled; + + web.user_style_sheet_enabled = cef.user_style_sheet_enabled; + + if (cef.user_style_sheet_location.length > 0) { + web.user_style_sheet_location = + GURL(std::string(CefString(&cef.user_style_sheet_location))); + } + + web.author_and_user_styles_enabled = !cef.author_and_user_styles_disabled; + web.allow_universal_access_from_file_urls = + cef.universal_access_from_file_urls_allowed; + web.allow_file_access_from_file_urls = cef.file_access_from_file_urls_allowed; + web.experimental_webgl_enabled = !cef.webgl_disabled; + web.show_composited_layer_borders = false; + web.accelerated_compositing_enabled = cef.accelerated_compositing_enabled; + web.accelerated_layers_enabled = !cef.accelerated_layers_disabled; + web.accelerated_animation_enabled = !cef.accelerated_layers_disabled; + web.accelerated_video_enabled = !cef.accelerated_video_disabled; + web.accelerated_2d_canvas_enabled = !cef.accelerated_2d_canvas_disabled; + web.accelerated_painting_enabled = !cef.accelerated_painting_disabled; + web.accelerated_filters_enabled = !cef.accelerated_filters_disabled; + web.accelerated_plugins_enabled = !cef.accelerated_plugins_disabled; + web.memory_info_enabled = false; + web.fullscreen_enabled = cef.fullscreen_enabled; +} diff --git a/cef1/libcef/browser_settings.h b/cef1/libcef/browser_settings.h new file mode 100644 index 000000000..7a04da48f --- /dev/null +++ b/cef1/libcef/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_SETTINGS_H_ +#define CEF_LIBCEF_BROWSER_SETTINGS_H_ +#pragma once + +#include "include/internal/cef_types_wrappers.h" + +namespace webkit_glue { +struct WebPreferences; +} + +void BrowserToWebSettings(const CefBrowserSettings& cef, + webkit_glue::WebPreferences& web); + +#endif // CEF_LIBCEF_BROWSER_SETTINGS_H_ diff --git a/cef1/libcef/browser_socket_stream_bridge.cc b/cef1/libcef/browser_socket_stream_bridge.cc new file mode 100644 index 000000000..0d96d8ee1 --- /dev/null +++ b/cef1/libcef/browser_socket_stream_bridge.cc @@ -0,0 +1,239 @@ +// 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 "libcef/browser_socket_stream_bridge.h" + +#include "base/atomicops.h" +#include "base/bind.h" +#include "base/memory/ref_counted.h" +#include "base/message_loop.h" +#include "googleurl/src/gurl.h" +#include "net/socket_stream/socket_stream_job.h" +#include "net/websockets/websocket_job.h" +#include "net/url_request/url_request_context.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSocketStreamHandle.h" +#include "webkit/glue/websocketstreamhandle_bridge.h" +#include "webkit/glue/websocketstreamhandle_delegate.h" + +using webkit_glue::WebSocketStreamHandleBridge; + +const int kNoSocketId = 0; + +namespace { + +MessageLoop* g_io_thread; +net::URLRequestContext* g_request_context; + +class WebSocketStreamHandleBridgeImpl + : public WebSocketStreamHandleBridge, + public net::SocketStream::Delegate { + public: + WebSocketStreamHandleBridgeImpl( + WebKit::WebSocketStreamHandle* handle, + webkit_glue::WebSocketStreamHandleDelegate* delegate); + + // WebSocketStreamHandleBridge methods. + virtual void Connect(const GURL& url); + virtual bool Send(const std::vector& data); + virtual void Close(); + + // net::SocketStream::Delegate methods. + virtual void OnConnected(net::SocketStream* req, + int max_pending_send_allowed); + virtual void OnSentData(net::SocketStream* req, + int amount_sent); + virtual void OnReceivedData(net::SocketStream* req, + const char* data, int len); + virtual void OnClose(net::SocketStream* req); + + private: + virtual ~WebSocketStreamHandleBridgeImpl(); + + // Runs on |g_io_thread|; + void DoConnect(const GURL& url); + void DoSend(std::vector* data); + void DoClose(); + + // Runs on |message_loop_|; + void DoOnConnected(int max_amount_send_allowed); + void DoOnSentData(int amount_sent); + void DoOnReceivedData(std::vector* data); + void DoOnClose(); + + int socket_id_; + MessageLoop* message_loop_; + WebKit::WebSocketStreamHandle* handle_; + webkit_glue::WebSocketStreamHandleDelegate* delegate_; + + scoped_refptr socket_; + // Number of pending tasks to handle net::SocketStream::Delegate methods. + base::subtle::Atomic32 num_pending_tasks_; + + DISALLOW_COPY_AND_ASSIGN(WebSocketStreamHandleBridgeImpl); +}; + +WebSocketStreamHandleBridgeImpl::WebSocketStreamHandleBridgeImpl( + WebKit::WebSocketStreamHandle* handle, + webkit_glue::WebSocketStreamHandleDelegate* delegate) + : socket_id_(kNoSocketId), + message_loop_(MessageLoop::current()), + handle_(handle), + delegate_(delegate), + num_pending_tasks_(0) { + net::WebSocketJob::EnsureInit(); +} + +WebSocketStreamHandleBridgeImpl::~WebSocketStreamHandleBridgeImpl() { + DCHECK_EQ(socket_id_, kNoSocketId); +} + +void WebSocketStreamHandleBridgeImpl::Connect(const GURL& url) { + DCHECK(g_io_thread); + AddRef(); // Released in DoOnClose(). + g_io_thread->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoConnect, this, url)); + if (delegate_) + delegate_->WillOpenStream(handle_, url); +} + +bool WebSocketStreamHandleBridgeImpl::Send( + const std::vector& data) { + DCHECK(g_io_thread); + g_io_thread->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoSend, this, + new std::vector(data))); + return true; +} + +void WebSocketStreamHandleBridgeImpl::Close() { + DCHECK(g_io_thread); + g_io_thread->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoClose, this)); +} + +void WebSocketStreamHandleBridgeImpl::OnConnected( + net::SocketStream* socket, int max_pending_send_allowed) { + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, 1); + message_loop_->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoOnConnected, this, + max_pending_send_allowed)); +} + +void WebSocketStreamHandleBridgeImpl::OnSentData( + net::SocketStream* socket, int amount_sent) { + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, 1); + message_loop_->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoOnSentData, this, + amount_sent)); +} + +void WebSocketStreamHandleBridgeImpl::OnReceivedData( + net::SocketStream* socket, const char* data, int len) { + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, 1); + message_loop_->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoOnReceivedData, this, + new std::vector(data, data + len))); +} + +void WebSocketStreamHandleBridgeImpl::OnClose(net::SocketStream* socket) { + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, 1); + // Release socket_ on IO thread. + socket_ = NULL; + socket_id_ = kNoSocketId; + message_loop_->PostTask( + FROM_HERE, + base::Bind(&WebSocketStreamHandleBridgeImpl::DoOnClose, this)); +} + +void WebSocketStreamHandleBridgeImpl::DoConnect(const GURL& url) { + DCHECK(MessageLoop::current() == g_io_thread); + socket_ = net::SocketStreamJob::CreateSocketStreamJob( + url, this, g_request_context->transport_security_state(), + g_request_context->ssl_config_service()); + socket_->set_context(g_request_context); + socket_->Connect(); +} + +void WebSocketStreamHandleBridgeImpl::DoSend(std::vector* data) { + DCHECK(MessageLoop::current() == g_io_thread); + scoped_ptr > scoped_data(data); + if (!socket_) + return; + if (!socket_->SendData(&(data->at(0)), data->size())) + socket_->Close(); +} + +void WebSocketStreamHandleBridgeImpl::DoClose() { + DCHECK(MessageLoop::current() == g_io_thread); + if (!socket_) + return; + socket_->Close(); +} + +void WebSocketStreamHandleBridgeImpl::DoOnConnected( + int max_pending_send_allowed) { + DCHECK(MessageLoop::current() == message_loop_); + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, -1); + if (delegate_) + delegate_->DidOpenStream(handle_, max_pending_send_allowed); +} + +void WebSocketStreamHandleBridgeImpl::DoOnSentData(int amount_sent) { + DCHECK(MessageLoop::current() == message_loop_); + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, -1); + if (delegate_) + delegate_->DidSendData(handle_, amount_sent); +} + +void WebSocketStreamHandleBridgeImpl::DoOnReceivedData( + std::vector* data) { + DCHECK(MessageLoop::current() == message_loop_); + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, -1); + scoped_ptr > scoped_data(data); + if (delegate_) + delegate_->DidReceiveData(handle_, &(data->at(0)), data->size()); +} + +void WebSocketStreamHandleBridgeImpl::DoOnClose() { + DCHECK(MessageLoop::current() == message_loop_); + base::subtle::NoBarrier_AtomicIncrement(&num_pending_tasks_, -1); + // Don't handle OnClose if there are pending tasks. + DCHECK_EQ(num_pending_tasks_, 0); + DCHECK(!socket_); + DCHECK_EQ(socket_id_, kNoSocketId); + webkit_glue::WebSocketStreamHandleDelegate* delegate = delegate_; + delegate_ = NULL; + if (delegate) + delegate->DidClose(handle_); + Release(); +} + +} // namespace + +/* static */ +void BrowserSocketStreamBridge::InitializeOnIOThread( + net::URLRequestContext* request_context) { + g_io_thread = MessageLoop::current(); + g_request_context = request_context; +} + +void BrowserSocketStreamBridge::Cleanup() { + g_io_thread = NULL; + g_request_context = NULL; +} + +/* static */ +webkit_glue::WebSocketStreamHandleBridge* BrowserSocketStreamBridge::Create( + WebKit::WebSocketStreamHandle* handle, + webkit_glue::WebSocketStreamHandleDelegate* delegate) { + return new WebSocketStreamHandleBridgeImpl(handle, delegate); +} diff --git a/cef1/libcef/browser_socket_stream_bridge.h b/cef1/libcef/browser_socket_stream_bridge.h new file mode 100644 index 000000000..a59ac09a4 --- /dev/null +++ b/cef1/libcef/browser_socket_stream_bridge.h @@ -0,0 +1,36 @@ +// 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_SOCKET_STREAM_BRIDGE_H_ +#define CEF_LIBCEF_BROWSER_SOCKET_STREAM_BRIDGE_H_ +#pragma once + +#include "base/basictypes.h" + +namespace net { +class URLRequestContext; +} // namespace net + +namespace WebKit { +class WebSocketStreamHandle; +} // namespace WebKit + +namespace webkit_glue { +class WebSocketStreamHandleDelegate; +class WebSocketStreamHandleBridge; +} // namespace webkit_glue + +class BrowserSocketStreamBridge { + public: + static void InitializeOnIOThread(net::URLRequestContext* request_context); + static void Cleanup(); + static webkit_glue::WebSocketStreamHandleBridge* Create( + WebKit::WebSocketStreamHandle* handle, + webkit_glue::WebSocketStreamHandleDelegate* delegate); + + private: + DISALLOW_IMPLICIT_CONSTRUCTORS(BrowserSocketStreamBridge); +}; + +#endif // CEF_LIBCEF_BROWSER_SOCKET_STREAM_BRIDGE_H_ diff --git a/cef1/libcef/browser_thread_stub.cc b/cef1/libcef/browser_thread_stub.cc new file mode 100644 index 000000000..7aff3e4d1 --- /dev/null +++ b/cef1/libcef/browser_thread_stub.cc @@ -0,0 +1,68 @@ +// 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 "content/public/browser/browser_thread.h" +#include "libcef/cef_thread.h" + +// Stub implementations to convert BrowserThread calls to CefThread. + +namespace content { + +namespace { + +int GetCefId(BrowserThread::ID browser_id) { + switch (browser_id) { + case BrowserThread::UI: + return CefThread::UI; + case BrowserThread::IO: + return CefThread::IO; + case BrowserThread::DB: + case BrowserThread::FILE: + return CefThread::FILE; + default: + break; + } + + // The specified BrowserThread ID is not supported. + NOTREACHED(); + return -1; +} + +} // namespace + +// static +bool BrowserThread::PostTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task) { + int cef_id = GetCefId(identifier); + if (cef_id < 0) + return false; + + return CefThread::PostTask(static_cast(cef_id), from_here, + task); +} + +// static +bool BrowserThread::PostDelayedTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) { + int cef_id = GetCefId(identifier); + if (cef_id < 0) + return false; + + return CefThread::PostDelayedTask(static_cast(cef_id), + from_here, task, delay); +} + +// static +bool BrowserThread::CurrentlyOn(ID identifier) { + int cef_id = GetCefId(identifier); + if (cef_id < 0) + return false; + + return CefThread::CurrentlyOn(static_cast(cef_id)); +} + +} // namespace content diff --git a/cef1/libcef/browser_webblobregistry_impl.cc b/cef1/libcef/browser_webblobregistry_impl.cc new file mode 100644 index 000000000..626f64b82 --- /dev/null +++ b/cef1/libcef/browser_webblobregistry_impl.cc @@ -0,0 +1,87 @@ +// 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_webblobregistry_impl.h" + +#include "base/bind.h" +#include "base/message_loop.h" +#include "googleurl/src/gurl.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebBlobData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" +#include "webkit/blob/blob_data.h" +#include "webkit/blob/blob_storage_controller.h" + +using WebKit::WebBlobData; +using WebKit::WebURL; +using webkit_blob::BlobData; + +namespace { + +MessageLoop* g_io_thread; +webkit_blob::BlobStorageController* g_blob_storage_controller; + +} // namespace + +/* static */ +void BrowserWebBlobRegistryImpl::InitializeOnIOThread( + webkit_blob::BlobStorageController* blob_storage_controller) { + g_io_thread = MessageLoop::current(); + g_blob_storage_controller = blob_storage_controller; +} + +/* static */ +void BrowserWebBlobRegistryImpl::Cleanup() { + g_io_thread = NULL; + g_blob_storage_controller = NULL; +} + +BrowserWebBlobRegistryImpl::BrowserWebBlobRegistryImpl() { +} + +void BrowserWebBlobRegistryImpl::registerBlobURL( + const WebURL& url, WebBlobData& data) { + DCHECK(g_io_thread); + GURL thread_safe_url = url; // WebURL uses refcounted strings. + g_io_thread->PostTask(FROM_HERE, base::Bind( + &BrowserWebBlobRegistryImpl::AddFinishedBlob, this, + thread_safe_url, make_scoped_refptr(new BlobData(data)))); +} + +void BrowserWebBlobRegistryImpl::registerBlobURL( + const WebURL& url, const WebURL& src_url) { + DCHECK(g_io_thread); + GURL thread_safe_url = url; + GURL thread_safe_src_url = src_url; + g_io_thread->PostTask(FROM_HERE, base::Bind( + &BrowserWebBlobRegistryImpl::CloneBlob, this, + thread_safe_url, thread_safe_src_url)); +} + +void BrowserWebBlobRegistryImpl::unregisterBlobURL(const WebURL& url) { + DCHECK(g_io_thread); + GURL thread_safe_url = url; + g_io_thread->PostTask(FROM_HERE, base::Bind( + &BrowserWebBlobRegistryImpl::RemoveBlob, this, + thread_safe_url)); +} + +BrowserWebBlobRegistryImpl::~BrowserWebBlobRegistryImpl() { +} + +void BrowserWebBlobRegistryImpl::AddFinishedBlob( + const GURL& url, BlobData* blob_data) { + DCHECK(g_blob_storage_controller); + g_blob_storage_controller->AddFinishedBlob(url, blob_data); +} + +void BrowserWebBlobRegistryImpl::CloneBlob( + const GURL& url, const GURL& src_url) { + DCHECK(g_blob_storage_controller); + g_blob_storage_controller->CloneBlob(url, src_url); +} + +void BrowserWebBlobRegistryImpl::RemoveBlob(const GURL& url) { + DCHECK(g_blob_storage_controller); + g_blob_storage_controller->RemoveBlob(url); +} diff --git a/cef1/libcef/browser_webblobregistry_impl.h b/cef1/libcef/browser_webblobregistry_impl.h new file mode 100644 index 000000000..09f92bd6f --- /dev/null +++ b/cef1/libcef/browser_webblobregistry_impl.h @@ -0,0 +1,50 @@ +// 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_WEBBLOBREGISTRY_IMPL_H_ +#define CEF_LIBCEF_BROWSER_WEBBLOBREGISTRY_IMPL_H_ +#pragma once + +#include "base/memory/ref_counted.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebBlobRegistry.h" + +class GURL; + +namespace webkit_blob { +class BlobData; +class BlobStorageController; +} + +class BrowserWebBlobRegistryImpl + : public WebKit::WebBlobRegistry, + public base::RefCountedThreadSafe { + public: + static void InitializeOnIOThread( + webkit_blob::BlobStorageController* blob_storage_controller); + static void Cleanup(); + + BrowserWebBlobRegistryImpl(); + + // See WebBlobRegistry.h for documentation on these functions. + virtual void registerBlobURL(const WebKit::WebURL& url, + WebKit::WebBlobData& data); + virtual void registerBlobURL(const WebKit::WebURL& url, + const WebKit::WebURL& src_url); + virtual void unregisterBlobURL(const WebKit::WebURL& url); + + protected: + virtual ~BrowserWebBlobRegistryImpl(); + + private: + friend class base::RefCountedThreadSafe; + + // Run on I/O thread. + void AddFinishedBlob(const GURL& url, webkit_blob::BlobData* blob_data); + void CloneBlob(const GURL& url, const GURL& src_url); + void RemoveBlob(const GURL& url); + + DISALLOW_COPY_AND_ASSIGN(BrowserWebBlobRegistryImpl); +}; + +#endif // CEF_LIBCEF_BROWSER_WEBBLOBREGISTRY_IMPL_H_ diff --git a/cef1/libcef/browser_webcookiejar_impl.cc b/cef1/libcef/browser_webcookiejar_impl.cc new file mode 100644 index 000000000..9a99fe1e3 --- /dev/null +++ b/cef1/libcef/browser_webcookiejar_impl.cc @@ -0,0 +1,139 @@ +// Copyright (c) 2012 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. + +#include "libcef/browser_webcookiejar_impl.h" + +#include + +#include "libcef/browser_resource_loader_bridge.h" +#include "libcef/browser_impl.h" +#include "libcef/cookie_manager_impl.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" + +#include "base/synchronization/waitable_event.h" +#include "net/cookies/cookie_store.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" + +using WebKit::WebString; +using WebKit::WebURL; + +namespace { + +net::CookieStore* GetCookieStore(CefRefPtr browser) { + scoped_refptr cookie_store; + if (browser) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + // Get the manager from the handler. + CefRefPtr manager = + handler->GetCookieManager(browser.get(), + browser->pending_url().spec()); + if (manager.get()) { + cookie_store = + reinterpret_cast( + manager.get())->cookie_monster(); + } + } + } + } + + if (!cookie_store) { + // Use the global cookie store. + cookie_store = _Context->request_context()->cookie_store(); + } + + DCHECK(cookie_store); + return cookie_store; +} + +class CookieSetter : public base::RefCountedThreadSafe { + public: + void Set(CefRefPtr browser, + const GURL& url, + const std::string& cookie) { + REQUIRE_IOT(); + + scoped_refptr cookie_store = GetCookieStore(browser); + cookie_store->SetCookieWithOptionsAsync( + url, cookie, net::CookieOptions(), + net::CookieStore::SetCookiesCallback()); + } + + private: + friend class base::RefCountedThreadSafe; + + ~CookieSetter() {} +}; + +class CookieGetter : public base::RefCountedThreadSafe { + public: + CookieGetter() : event_(false, false) { + } + + void Get(CefRefPtr browser, const GURL& url) { + REQUIRE_IOT(); + + scoped_refptr cookie_store = GetCookieStore(browser); + cookie_store->GetCookiesWithOptionsAsync( + url, net::CookieOptions(), + base::Bind(&CookieGetter::OnGetCookies, this)); + } + + std::string GetResult() { + event_.Wait(); + return result_; + } + + private: + void OnGetCookies(const std::string& cookie_line) { + result_ = cookie_line; + event_.Signal(); + } + friend class base::RefCountedThreadSafe; + + ~CookieGetter() {} + + base::WaitableEvent event_; + std::string result_; +}; + +} // namespace + +BrowserWebCookieJarImpl::BrowserWebCookieJarImpl() + : browser_(NULL) { +} + +BrowserWebCookieJarImpl::BrowserWebCookieJarImpl(CefBrowserImpl* browser) + : browser_(browser) { +} + +void BrowserWebCookieJarImpl::setCookie(const WebURL& url, + const WebURL& first_party_for_cookies, + const WebString& value) { + GURL gurl = url; + std::string cookie = value.utf8(); + + // Proxy to IO thread to synchronize w/ network loading. + scoped_refptr cookie_setter = new CookieSetter(); + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &CookieSetter::Set, cookie_setter.get(), browser_, gurl, cookie)); +} + +WebString BrowserWebCookieJarImpl::cookies( + const WebURL& url, + const WebURL& first_party_for_cookies) { + GURL gurl = url; + + // Proxy to IO thread to synchronize w/ network loading. + scoped_refptr cookie_getter = new CookieGetter(); + CefThread::PostTask(CefThread::IO, FROM_HERE, base::Bind( + &CookieGetter::Get, cookie_getter.get(), browser_, gurl)); + + // Blocks until the result is available. + return WebString::fromUTF8(cookie_getter->GetResult()); +} diff --git a/cef1/libcef/browser_webcookiejar_impl.h b/cef1/libcef/browser_webcookiejar_impl.h new file mode 100644 index 000000000..6508b465d --- /dev/null +++ b/cef1/libcef/browser_webcookiejar_impl.h @@ -0,0 +1,36 @@ +// Copyright (c) 2012 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. + +#ifndef CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_ +#define CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_ +#pragma once + +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCookieJar.h" + +namespace net { +class CookieStore; +} + +class CefBrowserImpl; + +// Handles cookie requests from the renderer. +class BrowserWebCookieJarImpl : public WebKit::WebCookieJar { + public: + BrowserWebCookieJarImpl(); + explicit BrowserWebCookieJarImpl(CefBrowserImpl* browser); + + // WebKit::WebCookieJar methods. + virtual void setCookie( + const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies, + const WebKit::WebString& cookie); + virtual WebKit::WebString cookies( + const WebKit::WebURL& url, const WebKit::WebURL& first_party_for_cookies); + + private: + // May be NULL for the global implementation. + CefBrowserImpl* browser_; +}; + +#endif // CEF_LIBCEF_BROWSER_WEBCOOKIEJAR_IMPL_H_ diff --git a/cef1/libcef/browser_webkit_glue.cc b/cef1/libcef/browser_webkit_glue.cc new file mode 100644 index 000000000..3300c59da --- /dev/null +++ b/cef1/libcef/browser_webkit_glue.cc @@ -0,0 +1,168 @@ +// Copyright (c) 2008-2009 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. + +#include "libcef/browser_webkit_glue.h" + +#include "third_party/WebKit/Source/WebCore/config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "ApplicationCacheStorage.h" // NOLINT(build/include) +#include "CrossOriginPreflightResultCache.h" // NOLINT(build/include) +#include "DocumentLoader.h" // NOLINT(build/include) +#include "MemoryCache.h" // NOLINT(build/include) +#include "TextEncoding.h" // NOLINT(build/include) +#include "third_party/WebKit/Source/WebKit/chromium/src/WebFrameImpl.h" +MSVC_POP_WARNING(); +#undef LOG + +#include "base/logging.h" +#include "base/string_util.h" +#include "net/base/mime_util.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "webkit/glue/user_agent.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h" +#include "webkit/gpu/webgraphicscontext3d_in_process_impl.h" +#include "webkit/plugins/npapi/plugin_list.h" + +// Generated by GRIT +#include "grit/webkit_resources.h" + +using WebKit::WebFrameImpl; + +namespace webkit_glue { + +bool IsMediaPlayerAvailable() { + return true; +} + +void InitializeTextEncoding() { + WebCore::UTF8Encoding(); +} + +v8::Handle GetV8Context(WebKit::WebFrame* frame) { + WebFrameImpl* webFrameImpl = static_cast(frame); + WebCore::Frame* core_frame = webFrameImpl->frame(); + return WebCore::V8Proxy::context(core_frame); +} + +void ClearCache() { + if (WebCore::memoryCache()->disabled()) + return; + + // Clear the memory cache by disabling and then re-enabling it. + WebCore::memoryCache()->setDisabled(true); + WebCore::memoryCache()->setDisabled(false); + + // Empty the Cross-Origin Preflight cache + WebCore::CrossOriginPreflightResultCache::shared().empty(); +} + +#if defined(OS_LINUX) +int MatchFontWithFallback(const std::string& face, bool bold, + bool italic, int charset) { + return -1; +} + +bool GetFontTable(int fd, uint32_t table, uint8_t* output, + size_t* output_length) { + return false; +} +#endif + +// Adapted from Chromium's BufferedResourceHandler::ShouldDownload +bool ShouldDownload(const std::string& content_disposition, + const std::string& mime_type) { + std::string type = StringToLowerASCII(mime_type); + std::string disposition = StringToLowerASCII(content_disposition); + + // First, examine content-disposition. + if (!disposition.empty()) { + bool should_download = true; + + // Some broken sites just send ... + // Content-Disposition: ; filename="file" + // ... screen those out here. + if (disposition[0] == ';') + should_download = false; + + if (disposition.compare(0, 6, "inline") == 0) + should_download = false; + + // Some broken sites just send ... + // Content-Disposition: filename="file" + // ... without a disposition token... Screen those out. + if (disposition.compare(0, 8, "filename") == 0) + should_download = false; + + // Also in use is Content-Disposition: name="file" + if (disposition.compare(0, 4, "name") == 0) + should_download = false; + + // We have a content-disposition of "attachment" or unknown. + // RFC 2183, section 2.8 says that an unknown disposition + // value should be treated as "attachment". + if (should_download) + return true; + } + + // Mirrors WebViewImpl::CanShowMIMEType() + if (type.empty() || net::IsSupportedMimeType(type)) + return false; + + // Finally, check the plugin list. + bool allow_wildcard = false; + std::vector plugins; + webkit::npapi::PluginList::Singleton()->GetPluginInfoArray( + GURL(), type, allow_wildcard, NULL, &plugins, NULL); + + // If any associated plugins exist and are enabled don't allow the download. + if (!plugins.empty()) { + std::vector::const_iterator it = plugins.begin(); + for (; it != plugins.end(); ++it) { + if (webkit_glue::IsPluginEnabled(*it)) + return false; + } + } + + return true; +} + +bool IsPluginEnabled(const webkit::WebPluginInfo& plugin) { + return true; +} + +WebKit::WebGraphicsContext3D* CreateGraphicsContext3D( + cef_graphics_implementation_t graphics_implementation, + const WebKit::WebGraphicsContext3D::Attributes& attributes, + WebKit::WebView* web_view, + bool renderDirectlyToWebView) { +#if defined(OS_WIN) + bool use_command_buffer = + (graphics_implementation == ANGLE_IN_PROCESS_COMMAND_BUFFER || + graphics_implementation == DESKTOP_IN_PROCESS_COMMAND_BUFFER); +#else + bool use_command_buffer = + (graphics_implementation == DESKTOP_IN_PROCESS_COMMAND_BUFFER); +#endif + + if (use_command_buffer) { + WebKit::WebGraphicsContext3D* view_context = NULL; + if (!renderDirectlyToWebView) + view_context = web_view->graphicsContext3D(); + scoped_ptr + context( + new webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl()); + if (!context->Initialize(attributes, view_context)) + return NULL; + return context.release(); + } else { + return webkit::gpu::WebGraphicsContext3DInProcessImpl::CreateForWebView( + attributes, renderDirectlyToWebView); + } +} + +} // namespace webkit_glue diff --git a/cef1/libcef/browser_webkit_glue.h b/cef1/libcef/browser_webkit_glue.h new file mode 100644 index 000000000..146b4e7e8 --- /dev/null +++ b/cef1/libcef/browser_webkit_glue.h @@ -0,0 +1,66 @@ +// 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_WEBKIT_GLUE_H_ +#define CEF_LIBCEF_BROWSER_WEBKIT_GLUE_H_ +#pragma once + +#include + +#include "include/internal/cef_types.h" + +#include "base/compiler_specific.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebGraphicsContext3D.h" +#include "v8/include/v8.h" + +#if defined(OS_WIN) +#include // NOLINT(build/include_order) +#endif + +namespace WebKit { +class WebFrame; +class WebView; +} +namespace webkit { +struct WebPluginInfo; +} + +namespace webkit_glue { + +#if defined(OS_WIN) +// Capture a bitmap of the web view. +void CaptureWebViewBitmap(HWND mainWnd, WebKit::WebView* webview, + HBITMAP& bitmap, SIZE& size); + +// Save a bitmap image to file, providing optional alternative data in |lpBits| +BOOL SaveBitmapToFile(HBITMAP hBmp, HDC hDC, LPCTSTR file, LPBYTE lpBits); +#endif + +// Text encoding objects must be initialized on the main thread. +void InitializeTextEncoding(); + +// Retrieve the V8 context associated with the frame. +v8::Handle GetV8Context(WebKit::WebFrame* frame); + +// Clear all cached data. +void ClearCache(); + +// Returns true if the request represents a download based on +// the supplied Content-Type and Content-Disposition headers. +bool ShouldDownload(const std::string& content_disposition, + const std::string& mime_type); + +// Checks whether a plugin is enabled either by the user or by policy. +bool IsPluginEnabled(const webkit::WebPluginInfo& plugin); + +// Create a new WebGraphicsContext3D object. +WebKit::WebGraphicsContext3D* CreateGraphicsContext3D( + cef_graphics_implementation_t graphics_implementation, + const WebKit::WebGraphicsContext3D::Attributes& attributes, + WebKit::WebView* web_view, + bool renderDirectlyToWebView); + +} // namespace webkit_glue + +#endif // CEF_LIBCEF_BROWSER_WEBKIT_GLUE_H_ diff --git a/cef1/libcef/browser_webkit_glue_win.cc b/cef1/libcef/browser_webkit_glue_win.cc new file mode 100644 index 000000000..0c540767e --- /dev/null +++ b/cef1/libcef/browser_webkit_glue_win.cc @@ -0,0 +1,258 @@ +// Copyright (c) 2008 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. + +#include "libcef/browser_webkit_glue.h" + +#include +#include +#include + +#include "third_party/WebKit/Source/WebCore/config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "PlatformContextSkia.h" // NOLINT(build/include) +MSVC_POP_WARNING(); + +#undef LOG +#include "base/logging.h" +#include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/gfx/gdi_util.h" +#include "webkit/glue/webkit_glue.h" + +using WebKit::WebRect; +using WebKit::WebSize; +using WebKit::WebView; + +namespace webkit_glue { + +bool EnsureFontLoaded(HFONT font) { + return true; +} + +void CaptureWebViewBitmap(HWND mainWnd, WebView* webview, HBITMAP& bitmap, + SIZE& size) { + WebKit::WebSize webSize = webview->size(); + size.cx = webSize.width; + size.cy = webSize.height; + + skia::PlatformCanvas canvas(size.cx, size.cy, true); + canvas.drawARGB(255, 255, 255, 255, SkXfermode::kSrc_Mode); + WebCore::PlatformContextSkia context(&canvas); + WebKit::WebRect rect(0, 0, size.cx, size.cy); + webview->layout(); + webview->paint(&canvas, rect); + + HDC hRefDC = GetDC(mainWnd); + HDC hDC = CreateCompatibleDC(hRefDC); + bitmap = CreateCompatibleBitmap(hRefDC, size.cx, size.cy); + DCHECK(bitmap != NULL); + HBITMAP hOldBmp = (HBITMAP)SelectObject(hDC, bitmap); + + // Create a BMP v4 header that we can serialize. + BITMAPV4HEADER bitmap_header; + gfx::CreateBitmapV4Header(size.cx, size.cy, &bitmap_header); + const SkBitmap& src_bmp = canvas.getDevice()->accessBitmap(true); + SkAutoLockPixels src_lock(src_bmp); + int retval = StretchDIBits(hDC, + 0, + 0, + size.cx, size.cy, + 0, 0, + size.cx, size.cy, + src_bmp.getPixels(), + reinterpret_cast(&bitmap_header), + DIB_RGB_COLORS, + SRCCOPY); + DCHECK(retval != GDI_ERROR); + + SelectObject(hDC, hOldBmp); + DeleteDC(hDC); + ReleaseDC(mainWnd, hRefDC); +} + + +static PBITMAPINFO BmpCreateInfo(HBITMAP hBmp) { + BITMAP bmp; + PBITMAPINFO pbmi; + WORD cClrBits; + + // Retrieve the bitmap color format, width, and height. + if (!GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp)) { + NOTREACHED(); + return NULL; + } + + // Convert the color format to a count of bits. + cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel); + if (cClrBits == 1) + cClrBits = 1; + else if (cClrBits <= 4) + cClrBits = 4; + else if (cClrBits <= 8) + cClrBits = 8; + else if (cClrBits <= 16) + cClrBits = 16; + else if (cClrBits <= 24) + cClrBits = 24; + else + cClrBits = 32; + + // Allocate memory for the BITMAPINFO structure. (This structure + // contains a BITMAPINFOHEADER structure and an array of RGBQUAD + // data structures.) + if (cClrBits != 24) { + pbmi = (PBITMAPINFO) LocalAlloc(LPTR, + sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1<< cClrBits)); + } else { // There is no RGBQUAD array for the 24-bit-per-pixel format. + pbmi = (PBITMAPINFO) LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER)); + } + + // Initialize the fields in the BITMAPINFO structure. + pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + pbmi->bmiHeader.biWidth = bmp.bmWidth; + pbmi->bmiHeader.biHeight = bmp.bmHeight; + pbmi->bmiHeader.biPlanes = bmp.bmPlanes; + pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel; + if (cClrBits < 24) { + pbmi->bmiHeader.biClrUsed = (1<bmiHeader.biCompression = BI_RGB; + + // Compute the number of bytes in the array of color + // indices and store the result in biSizeImage. + // For Windows NT, the width must be DWORD aligned unless + // the bitmap is RLE compressed. This example shows this. + // For Windows 95/98/Me, the width must be WORD aligned unless the + // bitmap is RLE compressed. + pbmi->bmiHeader.biSizeImage = + ((pbmi->bmiHeader.biWidth * cClrBits +31) & ~31) /8 + * pbmi->bmiHeader.biHeight; + + // Set biClrImportant to 0, indicating that all of the + // device colors are important. + pbmi->bmiHeader.biClrImportant = 0; + return pbmi; +} + +static BOOL BmpSaveFile(LPCTSTR pszFile, PBITMAPINFO pbi, HBITMAP hBMP, + HDC hDC, LPBYTE lpBits = NULL) { + HANDLE hf = INVALID_HANDLE_VALUE; // file handle + BITMAPFILEHEADER hdr; // bitmap file-header + PBITMAPINFOHEADER pbih; // bitmap info-header + DWORD dwTotal; // total count of bytes + DWORD cb; // incremental count of bytes + BYTE* hp; // byte pointer + DWORD dwTmp; + BOOL ret = FALSE; + BOOL bitsAlloc = FALSE; + + pbih = (PBITMAPINFOHEADER) pbi; + + if (!lpBits) { + // The bits have not been provided, so retrieve from the bitmap file + lpBits = (LPBYTE) GlobalAlloc(GMEM_FIXED, pbih->biSizeImage); + if (!lpBits) { + // Memory could not be allocated + NOTREACHED(); + return FALSE; + } + + bitsAlloc = TRUE; + + // Retrieve the color table (RGBQUAD array) and the bits + // (array of palette indices) from the DIB. + if (!GetDIBits(hDC, hBMP, 0, (WORD) pbih->biHeight, lpBits, pbi, + DIB_RGB_COLORS)) { + NOTREACHED(); + goto end; + } + } + + // Create the bitmap file. + hf = CreateFile(pszFile, + GENERIC_READ | GENERIC_WRITE, + (DWORD) 0, + NULL, + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + (HANDLE) NULL); + if (hf == INVALID_HANDLE_VALUE) { + // Could not create the bitmap file + NOTREACHED(); + goto end; + } + + hdr.bfType = 0x4d42; // 0x42 = "B", 0x4d = "M" + + // Compute the size of the entire file. + hdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + + pbih->biSize + pbih->biClrUsed + * sizeof(RGBQUAD) + pbih->biSizeImage); + hdr.bfReserved1 = 0; + hdr.bfReserved2 = 0; + + // Compute the offset to the array of color indices. + hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) + + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD); + + // Copy the BITMAPFILEHEADER into the bitmap file. + if (!WriteFile(hf, (LPVOID) &hdr, sizeof(BITMAPFILEHEADER), + (LPDWORD) &dwTmp, NULL)) { + // Could not write bitmap file header to file + NOTREACHED(); + goto end; + } + + // Copy the BITMAPINFOHEADER and RGBQUAD array into the file. + if (!WriteFile(hf, (LPVOID) pbih, sizeof(BITMAPINFOHEADER) + + pbih->biClrUsed * sizeof(RGBQUAD), + (LPDWORD) &dwTmp, NULL)) { + // Could not write bitmap info header to file + NOTREACHED(); + goto end; + } + + // Copy the array of color indices into the .BMP file. + dwTotal = cb = pbih->biSizeImage; + hp = lpBits; + if (!WriteFile(hf, (LPSTR) hp, (DWORD) cb, (LPDWORD) &dwTmp, NULL)) { + // Could not write bitmap data to file + NOTREACHED(); + goto end; + } + + ret = TRUE; + +end: // NOLINT(whitespace/labels) + // Close the bitmap file. + if (hf != INVALID_HANDLE_VALUE) { + CloseHandle(hf); + if (!ret) + DeleteFile(pszFile); + } + + if (bitsAlloc) { + // Free memory. + GlobalFree((HGLOBAL)lpBits); + } + + return ret; +} + +BOOL SaveBitmapToFile(HBITMAP hBmp, HDC hDC, LPCTSTR file, LPBYTE lpBits) { + PBITMAPINFO pbmi = BmpCreateInfo(hBmp); + BOOL ret = FALSE; + if (pbmi) { + ret = BmpSaveFile(file, pbmi, hBmp, hDC, lpBits); + LocalFree(pbmi); + } + return ret; +} + +} // namespace webkit_glue diff --git a/cef1/libcef/browser_webkit_init.cc b/cef1/libcef/browser_webkit_init.cc new file mode 100644 index 000000000..7174a8720 --- /dev/null +++ b/cef1/libcef/browser_webkit_init.cc @@ -0,0 +1,329 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. +// Portions copyright (c) 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_webkit_init.h" +#include "libcef/browser_resource_loader_bridge.h" +#include "libcef/browser_socket_stream_bridge.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/cef_context.h" + +#include "base/metrics/stats_counters.h" +#include "base/path_service.h" +#include "base/utf_string_conversions.h" +#include "media/base/media.h" +#include "third_party/WebKit/Source/Platform/chromium/public/WebPrerenderingSupport.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDatabase.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebRuntimeFeatures.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBFactory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBKey.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebIDBKeyPath.h" +#include "v8/include/v8.h" +#include "webkit/plugins/npapi/plugin_list.h" + + +// Stub implementation of WebKit::WebPrerenderingSupport. +class BrowserPrerenderingSupport : public WebKit::WebPrerenderingSupport { + public: + virtual ~BrowserPrerenderingSupport() {} + + private: + virtual void add(const WebKit::WebPrerender& prerender) OVERRIDE {} + virtual void cancel(const WebKit::WebPrerender& prerender) OVERRIDE {} + virtual void abandon(const WebKit::WebPrerender& prerender) OVERRIDE {} +}; + + +BrowserWebKitInit::BrowserWebKitInit() + : clipboard_(&clipboard_client_) { + v8::V8::SetCounterFunction(base::StatsTable::FindLocation); + + WebKit::initialize(this); + WebKit::setLayoutTestMode(false); + WebKit::WebRuntimeFeatures::enableSockets(true); + WebKit::WebRuntimeFeatures::enableApplicationCache(true); + WebKit::WebRuntimeFeatures::enableDatabase(true); + WebKit::WebRuntimeFeatures::enablePushState(true); + WebKit::WebRuntimeFeatures::enableIndexedDatabase(true); + WebKit::WebRuntimeFeatures::enableFileSystem(true); + + // TODO(cef): Enable these once the implementation supports it. + WebKit::WebRuntimeFeatures::enableNotifications(false); + WebKit::WebRuntimeFeatures::enableGeolocation(false); + WebKit::WebRuntimeFeatures::enableSpeechInput(false); + WebKit::WebRuntimeFeatures::enableTouch(false); + WebKit::WebRuntimeFeatures::enableDeviceMotion(false); + WebKit::WebRuntimeFeatures::enableDeviceOrientation(false); + + prerendering_support_.reset(new BrowserPrerenderingSupport); + WebKit::WebPrerenderingSupport::initialize(prerendering_support_.get()); + + // Load libraries for media and enable the media player. + FilePath module_path; + WebKit::WebRuntimeFeatures::enableMediaPlayer( + PathService::Get(base::DIR_MODULE, &module_path) && + media::InitializeMediaLibrary(module_path)); + + FilePath appcache_path; + FilePath cache_path = _Context->cache_path(); + if (!cache_path.empty()) { + appcache_path = cache_path.Append(FILE_PATH_LITERAL("AppCache")); + if (!file_util::PathExists(appcache_path) && + !file_util::CreateDirectory(appcache_path)) { + LOG(WARNING) << "Failed to create appcache storage directory"; + appcache_path.clear(); + } + } + BrowserAppCacheSystem::InitializeOnUIThread(appcache_path); + + WebKit::WebDatabase::setObserver(&database_system_); + + blob_registry_ = new BrowserWebBlobRegistryImpl(); + + file_utilities_.set_sandbox_enabled(sandboxEnabled()); +} + +BrowserWebKitInit::~BrowserWebKitInit() { + WebKit::shutdown(); +} + +WebKit::WebMimeRegistry* BrowserWebKitInit::mimeRegistry() { + return &mime_registry_; +} + +WebKit::WebClipboard* BrowserWebKitInit::clipboard() { + return &clipboard_; +} + +WebKit::WebFileUtilities* BrowserWebKitInit::fileUtilities() { + return &file_utilities_; +} + +WebKit::WebSandboxSupport* BrowserWebKitInit::sandboxSupport() { + return NULL; +} + +WebKit::WebBlobRegistry* BrowserWebKitInit::blobRegistry() { + return blob_registry_.get(); +} + +WebKit::WebCookieJar* BrowserWebKitInit::cookieJar() { + return &cookie_jar_; +} + +WebKit::WebFileSystem* BrowserWebKitInit::fileSystem() { + BrowserFileSystem* file_system = _Context->file_system(); + // Create the context if it doesn't already exist. + file_system->CreateContext(); + return file_system; +} + +bool BrowserWebKitInit::sandboxEnabled() { + return false; +} + +WebKit::WebKitPlatformSupport::FileHandle +BrowserWebKitInit::databaseOpenFile( + const WebKit::WebString& vfs_file_name, int desired_flags) { + return BrowserDatabaseSystem::GetInstance()->OpenFile( + vfs_file_name, desired_flags); +} + +int BrowserWebKitInit::databaseDeleteFile( + const WebKit::WebString& vfs_file_name, bool sync_dir) { + return BrowserDatabaseSystem::GetInstance()->DeleteFile( + vfs_file_name, sync_dir); +} + +long BrowserWebKitInit::databaseGetFileAttributes( // NOLINT(runtime/int) + const WebKit::WebString& vfs_file_name) { + return BrowserDatabaseSystem::GetInstance()->GetFileAttributes( + vfs_file_name); +} + +long long BrowserWebKitInit::databaseGetFileSize( // NOLINT(runtime/int) + const WebKit::WebString& vfs_file_name) { + return BrowserDatabaseSystem::GetInstance()->GetFileSize(vfs_file_name); +} + +long long // NOLINT(runtime/int) +BrowserWebKitInit::databaseGetSpaceAvailableForOrigin( + const WebKit::WebString& origin_identifier) { + return BrowserDatabaseSystem::GetInstance()->GetSpaceAvailable( + origin_identifier); +} + +unsigned long long BrowserWebKitInit::visitedLinkHash( // NOLINT(runtime/int) + const char* canonicalURL, size_t length) { + return 0; +} + +bool BrowserWebKitInit::isLinkVisited( + unsigned long long linkHash) { // NOLINT(runtime/int) + return false; +} + +WebKit::WebMessagePortChannel* +BrowserWebKitInit::createMessagePortChannel() { + return NULL; +} + +void BrowserWebKitInit::prefetchHostName(const WebKit::WebString&) { +} + +void BrowserWebKitInit::decrementStatsCounter(const char* name) { +} + +void BrowserWebKitInit::incrementStatsCounter(const char* name) { +} + +void BrowserWebKitInit::histogramCustomCounts(const char* name, int sample, + int min, int max, + int bucket_count) { +} + +void BrowserWebKitInit::histogramEnumeration(const char* name, int sample, + int boundary_value) { +} + +WebKit::WebData BrowserWebKitInit::loadResource(const char* name) { + if (!strcmp(name, "deleteButton")) { + // Create a red 30x30 square. + const char red_square[] = + "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52" + "\x00\x00\x00\x1e\x00\x00\x00\x1e\x04\x03\x00\x00\x00\xc9\x1e\xb3" + "\x91\x00\x00\x00\x30\x50\x4c\x54\x45\x00\x00\x00\x80\x00\x00\x00" + "\x80\x00\x80\x80\x00\x00\x00\x80\x80\x00\x80\x00\x80\x80\x80\x80" + "\x80\xc0\xc0\xc0\xff\x00\x00\x00\xff\x00\xff\xff\x00\x00\x00\xff" + "\xff\x00\xff\x00\xff\xff\xff\xff\xff\x7b\x1f\xb1\xc4\x00\x00\x00" + "\x09\x70\x48\x59\x73\x00\x00\x0b\x13\x00\x00\x0b\x13\x01\x00\x9a" + "\x9c\x18\x00\x00\x00\x17\x49\x44\x41\x54\x78\x01\x63\x98\x89\x0a" + "\x18\x50\xb9\x33\x47\xf9\xa8\x01\x32\xd4\xc2\x03\x00\x33\x84\x0d" + "\x02\x3a\x91\xeb\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60" + "\x82"; + return WebKit::WebData(red_square, arraysize(red_square)); + } + return webkit_glue::WebKitPlatformSupportImpl::loadResource(name); +} + +WebKit::WebString BrowserWebKitInit::defaultLocale() { + return ASCIIToUTF16(_Context->locale()); +} + +WebKit::WebStorageNamespace* BrowserWebKitInit::createLocalStorageNamespace( + const WebKit::WebString& path, unsigned quota) { + return dom_storage_system_.CreateLocalStorageNamespace(); +} + +WebKit::WebIDBFactory* BrowserWebKitInit::idbFactory() { + return WebKit::WebIDBFactory::create(); +} + +void BrowserWebKitInit::createIDBKeysFromSerializedValuesAndKeyPath( + const WebKit::WebVector& values, + const WebKit::WebIDBKeyPath& keyPath, + WebKit::WebVector& keys_out) { + WebKit::WebVector keys(values.size()); + for (size_t i = 0; i < values.size(); ++i) + keys[i] = WebKit::WebIDBKey::createFromValueAndKeyPath(values[i], keyPath); + keys_out.swap(keys); +} + +WebKit::WebSerializedScriptValue +BrowserWebKitInit::injectIDBKeyIntoSerializedValue( + const WebKit::WebIDBKey& key, + const WebKit::WebSerializedScriptValue& value, + const WebKit::WebIDBKeyPath& keyPath) { + return WebKit::WebIDBKey::injectIDBKeyIntoSerializedValue( + key, value, keyPath); +} + +WebKit::WebGraphicsContext3D* +BrowserWebKitInit::createOffscreenGraphicsContext3D( + const WebKit::WebGraphicsContext3D::Attributes& attributes) { + const CefSettings& settings = _Context->settings(); + return webkit_glue::CreateGraphicsContext3D(settings.graphics_implementation, + attributes, NULL, false); +} + +void BrowserWebKitInit::GetPlugins( + bool refresh, std::vector* plugins) { + if (refresh) + webkit::npapi::PluginList::Singleton()->RefreshPlugins(); + webkit::npapi::PluginList::Singleton()->GetPlugins(plugins); +} + +string16 BrowserWebKitInit::GetLocalizedString(int message_id) { + return _Context->GetLocalizedString(message_id); +} + +base::StringPiece BrowserWebKitInit::GetDataResource( + int resource_id, + ui::ScaleFactor scale_factor) { + return _Context->GetDataResource(resource_id); +} + +webkit_glue::ResourceLoaderBridge* BrowserWebKitInit::CreateResourceLoader( + const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) { + return BrowserResourceLoaderBridge::Create(request_info); +} + +webkit_glue::WebSocketStreamHandleBridge* +BrowserWebKitInit::CreateWebSocketBridge( + WebKit::WebSocketStreamHandle* handle, + webkit_glue::WebSocketStreamHandleDelegate* delegate) { + return BrowserSocketStreamBridge::Create(handle, delegate); +} + +WebKit::WebString BrowserWebKitInit::queryLocalizedString( + WebKit::WebLocalizedString::Name name) { + switch (name) { + case WebKit::WebLocalizedString::ValidationValueMissing: + case WebKit::WebLocalizedString::ValidationValueMissingForCheckbox: + case WebKit::WebLocalizedString::ValidationValueMissingForFile: + case WebKit::WebLocalizedString::ValidationValueMissingForMultipleFile: + case WebKit::WebLocalizedString::ValidationValueMissingForRadio: + case WebKit::WebLocalizedString::ValidationValueMissingForSelect: + return ASCIIToUTF16("value missing"); + case WebKit::WebLocalizedString::ValidationTypeMismatch: + case WebKit::WebLocalizedString::ValidationTypeMismatchForEmail: + case WebKit::WebLocalizedString::ValidationTypeMismatchForMultipleEmail: + case WebKit::WebLocalizedString::ValidationTypeMismatchForURL: + return ASCIIToUTF16("type mismatch"); + case WebKit::WebLocalizedString::ValidationPatternMismatch: + return ASCIIToUTF16("pattern mismatch"); + case WebKit::WebLocalizedString::ValidationTooLong: + return ASCIIToUTF16("too long"); + case WebKit::WebLocalizedString::ValidationRangeUnderflow: + return ASCIIToUTF16("range underflow"); + case WebKit::WebLocalizedString::ValidationRangeOverflow: + return ASCIIToUTF16("range overflow"); + case WebKit::WebLocalizedString::ValidationStepMismatch: + return ASCIIToUTF16("step mismatch"); + default: + return WebKitPlatformSupportImpl::queryLocalizedString(name); + } +} + +WebKit::WebString BrowserWebKitInit::queryLocalizedString( + WebKit::WebLocalizedString::Name name, const WebKit::WebString& value) { + if (name == WebKit::WebLocalizedString::ValidationRangeUnderflow) + return ASCIIToUTF16("range underflow"); + if (name == WebKit::WebLocalizedString::ValidationRangeOverflow) + return ASCIIToUTF16("range overflow"); + return WebKitPlatformSupportImpl::queryLocalizedString(name, value); +} + +WebKit::WebString BrowserWebKitInit::queryLocalizedString( + WebKit::WebLocalizedString::Name name, + const WebKit::WebString& value1, + const WebKit::WebString& value2) { + if (name == WebKit::WebLocalizedString::ValidationTooLong) + return ASCIIToUTF16("too long"); + if (name == WebKit::WebLocalizedString::ValidationStepMismatch) + return ASCIIToUTF16("step mismatch"); + return WebKitPlatformSupportImpl::queryLocalizedString( + name, value1, value2); +} diff --git a/cef1/libcef/browser_webkit_init.h b/cef1/libcef/browser_webkit_init.h new file mode 100644 index 000000000..3f0c1c439 --- /dev/null +++ b/cef1/libcef/browser_webkit_init.h @@ -0,0 +1,115 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. +// Portions copyright (c) 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_WEBKIT_INIT_H_ +#define CEF_LIBCEF_BROWSER_WEBKIT_INIT_H_ +#pragma once + +#include + +#include "libcef/browser_appcache_system.h" +#include "libcef/browser_database_system.h" +#include "libcef/browser_dom_storage_system.h" +#include "libcef/browser_file_system.h" +#include "libcef/browser_webblobregistry_impl.h" +#include "libcef/browser_webcookiejar_impl.h" +#include "libcef/simple_clipboard_impl.h" + +#include "base/scoped_temp_dir.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebGraphicsContext3D.h" +#include "webkit/glue/simple_webmimeregistry_impl.h" +#include "webkit/glue/webclipboard_impl.h" +#include "webkit/glue/webfileutilities_impl.h" +#include "webkit/glue/webkitplatformsupport_impl.h" + +class BrowserPrerenderingSupport; + +class BrowserWebKitInit : public webkit_glue::WebKitPlatformSupportImpl { + public: + BrowserWebKitInit(); + virtual ~BrowserWebKitInit(); + + virtual WebKit::WebMimeRegistry* mimeRegistry() OVERRIDE; + virtual WebKit::WebClipboard* clipboard() OVERRIDE; + virtual WebKit::WebFileUtilities* fileUtilities() OVERRIDE; + virtual WebKit::WebSandboxSupport* sandboxSupport() OVERRIDE; + virtual WebKit::WebBlobRegistry* blobRegistry() OVERRIDE; + virtual WebKit::WebCookieJar* cookieJar() OVERRIDE; + virtual WebKit::WebFileSystem* fileSystem() OVERRIDE; + virtual bool sandboxEnabled() OVERRIDE; + virtual WebKit::WebKitPlatformSupport::FileHandle databaseOpenFile( + const WebKit::WebString& vfs_file_name, int desired_flags) OVERRIDE; + virtual int databaseDeleteFile(const WebKit::WebString& vfs_file_name, + bool sync_dir) OVERRIDE; + virtual long databaseGetFileAttributes( // NOLINT(runtime/int) + const WebKit::WebString& vfs_file_name) OVERRIDE; + virtual long long databaseGetFileSize( // NOLINT(runtime/int) + const WebKit::WebString& vfs_file_name) OVERRIDE; + virtual long long databaseGetSpaceAvailableForOrigin( // NOLINT(runtime/int) + const WebKit::WebString& origin_identifier) OVERRIDE; + virtual unsigned long long visitedLinkHash( // NOLINT(runtime/int) + const char* canonicalURL, + size_t length) OVERRIDE; + virtual bool isLinkVisited( + unsigned long long linkHash) OVERRIDE; // NOLINT(runtime/int) + virtual WebKit::WebMessagePortChannel* createMessagePortChannel() OVERRIDE; + virtual void prefetchHostName(const WebKit::WebString&) OVERRIDE; + virtual void decrementStatsCounter(const char* name) OVERRIDE; + virtual void incrementStatsCounter(const char* name) OVERRIDE; + virtual void histogramCustomCounts(const char* name, int sample, int min, + int max, int bucket_count) OVERRIDE; + virtual void histogramEnumeration(const char* name, int sample, + int boundary_value) OVERRIDE; + virtual WebKit::WebData loadResource(const char* name) OVERRIDE; + virtual WebKit::WebString defaultLocale() OVERRIDE; + virtual WebKit::WebStorageNamespace* createLocalStorageNamespace( + const WebKit::WebString& path, unsigned quota) OVERRIDE; + virtual WebKit::WebIDBFactory* idbFactory() OVERRIDE; + virtual void createIDBKeysFromSerializedValuesAndKeyPath( + const WebKit::WebVector& values, + const WebKit::WebIDBKeyPath& keyPath, + WebKit::WebVector& keys_out) OVERRIDE; + virtual WebKit::WebSerializedScriptValue injectIDBKeyIntoSerializedValue( + const WebKit::WebIDBKey& key, + const WebKit::WebSerializedScriptValue& value, + const WebKit::WebIDBKeyPath& keyPath) OVERRIDE; + virtual WebKit::WebGraphicsContext3D* createOffscreenGraphicsContext3D( + const WebKit::WebGraphicsContext3D::Attributes& attributes) OVERRIDE; + virtual string16 GetLocalizedString(int message_id) OVERRIDE; + virtual base::StringPiece GetDataResource( + int resource_id, + ui::ScaleFactor scale_factor) OVERRIDE; + virtual void GetPlugins(bool refresh, + std::vector* plugins) OVERRIDE; + virtual webkit_glue::ResourceLoaderBridge* CreateResourceLoader( + const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info) + OVERRIDE; + virtual webkit_glue::WebSocketStreamHandleBridge* CreateWebSocketBridge( + WebKit::WebSocketStreamHandle* handle, + webkit_glue::WebSocketStreamHandleDelegate* delegate) OVERRIDE; + virtual WebKit::WebString queryLocalizedString( + WebKit::WebLocalizedString::Name name) OVERRIDE; + virtual WebKit::WebString queryLocalizedString( + WebKit::WebLocalizedString::Name name, const WebKit::WebString& value) + OVERRIDE; + virtual WebKit::WebString queryLocalizedString( + WebKit::WebLocalizedString::Name name, + const WebKit::WebString& value1, + const WebKit::WebString& value2) OVERRIDE; + + private: + webkit_glue::SimpleWebMimeRegistryImpl mime_registry_; + webkit_glue::WebClipboardImpl clipboard_; + SimpleClipboardClient clipboard_client_; + webkit_glue::WebFileUtilitiesImpl file_utilities_; + BrowserAppCacheSystem appcache_system_; + BrowserDatabaseSystem database_system_; + BrowserDomStorageSystem dom_storage_system_; + BrowserWebCookieJarImpl cookie_jar_; + scoped_refptr blob_registry_; + scoped_ptr prerendering_support_; +}; + +#endif // CEF_LIBCEF_BROWSER_WEBKIT_INIT_H_ diff --git a/cef1/libcef/browser_webview_delegate.cc b/cef1/libcef/browser_webview_delegate.cc new file mode 100644 index 000000000..f816e9e6e --- /dev/null +++ b/cef1/libcef/browser_webview_delegate.cc @@ -0,0 +1,1352 @@ +// Copyright (c) 2008-2009 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. + +// This file contains the implementation of BrowserWebViewDelegate, which serves +// as the WebViewDelegate for the BrowserWebHost. The host is expected to +// have initialized a MessageLoop before these methods are called. + +#include "libcef/browser_webview_delegate.h" + +#include + +#include "libcef/browser_appcache_system.h" +#include "libcef/browser_dom_storage_system.h" +#include "libcef/browser_file_system.h" +#include "libcef/browser_impl.h" +#include "libcef/browser_navigation_controller.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/browser_zoom_map.h" +#include "libcef/cef_context.h" +#include "libcef/cef_process_ui_thread.h" +#include "libcef/dom_document_impl.h" +#include "libcef/request_impl.h" +#include "libcef/v8_impl.h" + +#include "base/debug/trace_event.h" +#include "base/file_util.h" +#include "base/message_loop.h" +#include "base/process_util.h" +#include "base/string_util.h" +#include "base/stringprintf.h" +#include "media/audio/null_audio_sink.h" +#include "media/base/filter_collection.h" +#include "media/base/media_log.h" +#include "media/base/message_loop_factory.h" +#include "media/filters/audio_renderer_impl.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebConsoleMessage.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebCString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileError.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileSystemCallbacks.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebHistoryItem.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebKitPlatformSupport.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPluginParams.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebRange.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebStorageNamespace.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLError.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebVector.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebWindowFeatures.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/point.h" +#include "webkit/appcache/web_application_cache_host_impl.h" +#include "webkit/glue/glue_serialize.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/weburlrequest_extradata_impl.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/window_open_disposition.h" +#include "webkit/media/webmediaplayer_impl.h" +#include "webkit/plugins/npapi/plugin_list.h" +#include "webkit/plugins/npapi/webplugin_delegate_impl.h" +#include "webkit/plugins/npapi/webplugin_impl.h" + +#if defined(OS_WIN) +#include "libcef/browser_drag_delegate_win.h" +#include "libcef/web_drop_target_win.h" +#endif + +#if defined(OS_LINUX) +#include "libcef/web_drag_source_gtk.h" +#include "libcef/web_drop_target_gtk.h" +#endif + +using appcache::WebApplicationCacheHostImpl; +using WebKit::WebApplicationCacheHost; +using WebKit::WebApplicationCacheHostClient; +using WebKit::WebConsoleMessage; +using WebKit::WebContextMenuData; +using WebKit::WebCookieJar; +using WebKit::WebData; +using WebKit::WebDataSource; +using WebKit::WebEditingAction; +using WebKit::WebFileChooserParams; +using WebKit::WebFileSystem; +using WebKit::WebFileSystemCallbacks; +using WebKit::WebFormElement; +using WebKit::WebFrame; +using WebKit::WebHistoryItem; +using WebKit::WebMediaPlayer; +using WebKit::WebMediaPlayerClient; +using WebKit::WebNavigationType; +using WebKit::WebNavigationPolicy; +using WebKit::WebNode; +using WebKit::WebPlugin; +using WebKit::WebPluginParams; +using WebKit::WebPoint; +using WebKit::WebPopupType; +using WebKit::WebRange; +using WebKit::WebRect; +using WebKit::WebScreenInfo; +using WebKit::WebSecurityOrigin; +using WebKit::WebSize; +using WebKit::WebStorageNamespace; +using WebKit::WebString; +using WebKit::WebTextAffinity; +using WebKit::WebTextDirection; +using WebKit::WebURL; +using WebKit::WebURLError; +using WebKit::WebURLRequest; +using WebKit::WebURLResponse; +using WebKit::WebVector; +using WebKit::WebView; +using WebKit::WebWidget; +using WebKit::WebWindowFeatures; +using WebKit::WebKeyboardEvent; + +namespace { + +int next_page_id_ = 1; + +void TranslatePopupFeatures(const 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 = string16(webKitFeatures.additionalFeatures[i]); + cef_string_list_append(features.additionalFeatures, str.GetStruct()); + } +} + +} // namespace + +// WebViewClient ------------------------------------------------------------- + +WebView* BrowserWebViewDelegate::createView(WebFrame* creator, + const WebURLRequest& request, const WebWindowFeatures& features, + const WebString& name, WebKit::WebNavigationPolicy policy) { + CefString url; + if (!request.isNull()) + url = request.url().spec().utf16(); + CefPopupFeatures cefFeatures; + TranslatePopupFeatures(features, cefFeatures); + CefRefPtr browser = + browser_->UIT_CreatePopupWindow(url, cefFeatures); + return browser.get() ? browser->UIT_GetWebView() : NULL; +} + +WebWidget* BrowserWebViewDelegate::createPopupMenu(WebPopupType popup_type) { + // TODO(darin): Should we take into account |popup_type| (for activation + // purpose)? + return browser_->UIT_CreatePopupWidget(); +} + +WebStorageNamespace* BrowserWebViewDelegate::createSessionStorageNamespace( + unsigned quota) { + return BrowserDomStorageSystem::instance().CreateSessionStorageNamespace(); +} + +WebKit::WebGraphicsContext3D* BrowserWebViewDelegate::createGraphicsContext3D( + const WebKit::WebGraphicsContext3D::Attributes& attributes) { + WebKit::WebView* web_view = browser_->UIT_GetWebView(); + if (!web_view) + return NULL; + + const CefSettings& settings = _Context->settings(); + return webkit_glue::CreateGraphicsContext3D(settings.graphics_implementation, + attributes, web_view, true); +} + +void BrowserWebViewDelegate::didAddMessageToConsole( + const WebConsoleMessage& message, const WebString& source_name, + unsigned source_line) { + std::string messageStr = message.text.utf8(); + std::string sourceStr = source_name.utf8(); + + bool handled = false; + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) { + handled = handler->OnConsoleMessage(browser_, messageStr, sourceStr, + source_line); + } + } + + if (!handled) { + logging::LogMessage("CONSOLE", 0).stream() << "\"" + << messageStr + << ",\" source: " + << sourceStr + << "(" + << source_line + << ")"; + } +} + +void BrowserWebViewDelegate::printPage(WebFrame* frame) { + if (!frame) { + WebView* view = browser_->UIT_GetWebView(); + if (view) + frame = view->mainFrame(); + } + if (frame) + browser_->UIT_PrintPages(frame); +} + +bool BrowserWebViewDelegate::shouldBeginEditing(const WebRange& range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::shouldEndEditing(const WebRange& range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::shouldInsertNode(const WebNode& node, + const WebRange& range, + WebEditingAction action) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::shouldInsertText(const WebString& text, + const WebRange& range, + WebEditingAction action) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::shouldChangeSelectedRange( + const WebRange& from_range, const WebRange& to_range, + WebTextAffinity affinity, bool still_selecting) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::shouldDeleteRange(const WebRange& range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::shouldApplyStyle(const WebString& style, + const WebRange& range) { + return browser_->UIT_AllowEditing(); +} + +bool BrowserWebViewDelegate::isSmartInsertDeleteEnabled() { + return smart_insert_delete_enabled_; +} + +bool BrowserWebViewDelegate::isSelectTrailingWhitespaceEnabled() { + return select_trailing_whitespace_enabled_; +} + +bool BrowserWebViewDelegate::handleCurrentKeyboardEvent() { + WebWidgetHost* host = GetWidgetHost(); + if (host && OnKeyboardEvent(host->GetLastKeyEvent(), true)) + return true; + + if (edit_command_name_.empty()) + return false; + + WebView* view = browser_->UIT_GetWebView(); + WebFrame* frame = NULL; + if (view) + frame = view->focusedFrame(); + if (!frame) + return false; + + return frame->executeCommand(WebString::fromUTF8(edit_command_name_), + WebString::fromUTF8(edit_command_value_)); +} + +bool BrowserWebViewDelegate::runFileChooser( + const WebFileChooserParams& params, + WebKit::WebFileChooserCompletion* chooser_completion) { + // Support file open dialog. + std::vector file_names; + + if (!ShowFileChooser(file_names, params.multiSelect, params.title, + webkit_glue::WebStringToFilePath(params.initialValue))) { + return false; + } + + WebVector ws_file_names(file_names.size()); + for (size_t i = 0; i < file_names.size(); ++i) { + ws_file_names[i] = webkit_glue::FilePathToWebString(file_names[i]); + } + + chooser_completion->didChooseFile(ws_file_names); + + return true; +} + +void BrowserWebViewDelegate::runModalAlertDialog( + WebFrame* frame, const WebString& message) { + CefString messageStr = string16(message); + bool handled = false; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetJSDialogHandler(); + + if (handler.get()) { + handled = handler->OnJSAlert(browser_, browser_->UIT_GetCefFrame(frame), + messageStr); + } + if (!handled) + ShowJavaScriptAlert(frame, messageStr); +} + +bool BrowserWebViewDelegate::runModalConfirmDialog( + WebFrame* frame, const WebString& message) { + CefString messageStr = string16(message); + bool retval = false; + bool handled = false; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetJSDialogHandler(); + + if (handler.get()) { + handled = handler->OnJSConfirm(browser_, browser_->UIT_GetCefFrame(frame), + messageStr, retval); + } + if (!handled) + retval = ShowJavaScriptConfirm(frame, messageStr); + return retval; +} + +bool BrowserWebViewDelegate::runModalPromptDialog( + WebFrame* frame, const WebString& message, const WebString& default_value, + WebString* actual_value) { + CefString messageStr = string16(message); + CefString defaultValueStr = string16(default_value); + CefString actualValueStr; + if (actual_value) + actualValueStr = string16(*actual_value); + + bool retval = false; + bool handled = false; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetJSDialogHandler(); + + if (handler.get()) { + handled = handler->OnJSPrompt(browser_, browser_->UIT_GetCefFrame(frame), + messageStr, defaultValueStr, retval, actualValueStr); + } + if (!handled) { + retval = ShowJavaScriptPrompt(frame, messageStr, defaultValueStr, + &actualValueStr); + } + if (actual_value) + *actual_value = string16(actualValueStr); + + return retval; +} + +bool BrowserWebViewDelegate::runModalBeforeUnloadDialog( + WebFrame* frame, const WebString& message) { + return true; // Allow window closure. +} + +void BrowserWebViewDelegate::setStatusText(const WebString& text) { + ShowStatus(text, STATUSTYPE_TEXT); +} + +void BrowserWebViewDelegate::setMouseOverURL(const WebURL& url) { + ShowStatus(url.spec().utf16(), STATUSTYPE_MOUSEOVER_URL); +} + +void BrowserWebViewDelegate::setKeyboardFocusURL(const WebKit::WebURL& url) { + ShowStatus(url.spec().utf16(), STATUSTYPE_KEYBOARD_FOCUS_URL); +} + +void BrowserWebViewDelegate::setToolTipText( + const WebString& text, WebTextDirection hint) { + CefString tooltipStr = string16(text); + bool handled = false; + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) + handled = handler->OnTooltip(browser_, tooltipStr); + } + + if (!handled) + GetWidgetHost()->SetTooltipText(tooltipStr); +} + +bool BrowserWebViewDelegate::acceptsLoadDrops() { + return !browser_->settings().load_drops_disabled; +} + +void BrowserWebViewDelegate::focusNext() { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetFocusHandler(); + if (handler.get()) { + // Notify the handler that it should take a focus + handler->OnTakeFocus(browser_, true); + } + } +} + +void BrowserWebViewDelegate::focusPrevious() { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetFocusHandler(); + if (handler.get()) { + // Notify the handler that it should take a focus + handler->OnTakeFocus(browser_, false); + } + } +} + +void BrowserWebViewDelegate::focusedNodeChanged(const WebKit::WebNode& node) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetFocusHandler(); + if (handler.get()) { + if (node.isNull()) { + handler->OnFocusedNodeChanged(browser_, browser_->GetFocusedFrame(), + NULL); + } else { + const WebKit::WebDocument& document = node.document(); + if (!document.isNull()) { + WebKit::WebFrame* frame = document.frame(); + CefRefPtr documentImpl = + new CefDOMDocumentImpl(browser_, frame); + handler->OnFocusedNodeChanged(browser_, + browser_->UIT_GetCefFrame(frame), + documentImpl->GetOrCreateNode(node)); + documentImpl->Detach(); + } + } + } + } +} + +void BrowserWebViewDelegate::navigateBackForwardSoon(int offset) { + browser_->UIT_GetNavigationController()->GoToOffset(offset); +} + +int BrowserWebViewDelegate::historyBackListCount() { + int current_index = + browser_->UIT_GetNavigationController()->GetLastCommittedEntryIndex(); + return current_index; +} + +int BrowserWebViewDelegate::historyForwardListCount() { + int current_index = + browser_->UIT_GetNavigationController()->GetLastCommittedEntryIndex(); + return browser_->UIT_GetNavigationController()->GetEntryCount() + - current_index - 1; +} + +// WebPermissionClient ------------------------------------------------------- + +bool BrowserWebViewDelegate::allowScriptExtension( + WebKit::WebFrame* frame, + const WebKit::WebString& extensionName, + int extensionGroup) { + bool allowExtension = true; + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetPermissionHandler(); + if (handler.get()) { + CefString extensionNameStr = string16(extensionName); + allowExtension = !handler->OnBeforeScriptExtensionLoad( + browser_, browser_->UIT_GetCefFrame(frame), extensionNameStr); + } + } + return allowExtension; +} + +// WebPrerendererClient ------------------------------------------------------ + +void BrowserWebViewDelegate::willAddPrerender(WebKit::WebPrerender* prerender) { +} + +// WebPluginPageDelegate ----------------------------------------------------- + +WebKit::WebPlugin* BrowserWebViewDelegate::CreatePluginReplacement( + const FilePath& file_path) { + return NULL; +} + +WebCookieJar* BrowserWebViewDelegate::GetCookieJar() { + return &cookie_jar_; +} + +// WebWidgetClient ----------------------------------------------------------- + +void BrowserWebViewDelegate::didInvalidateRect(const WebRect& rect) { + if (WebWidgetHost* host = GetWidgetHost()) + host->DidInvalidateRect(rect); +} + +void BrowserWebViewDelegate::didScrollRect(int dx, int dy, + const WebRect& clip_rect) { + if (WebWidgetHost* host = GetWidgetHost()) + host->DidScrollRect(dx, dy, clip_rect); +} + +void BrowserWebViewDelegate::scheduleComposite() { + if (WebWidgetHost* host = GetWidgetHost()) + host->ScheduleComposite(); +} + +void BrowserWebViewDelegate::scheduleAnimation() { + if (WebWidgetHost* host = GetWidgetHost()) + host->ScheduleAnimation(); +} + +// This method is called when: +// A. A request is loaded in a window other than the source window +// (FrameLoader::loadFrameRequest), or +// B. A request is loaded in an already existing popup window +// (FrameLoader::createWindow), or +// C. A DOM window receives a focus event (DOMWindow::focus) +void BrowserWebViewDelegate::didFocus() { + if (WebWidgetHost* host = GetWidgetHost()) { + bool handled = false; + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetFocusHandler(); + if (handler.get()) + handled = handler->OnSetFocus(browser_, FOCUS_SOURCE_WIDGET); + } + + if (!handled) + browser_->UIT_SetFocus(host, true); + } +} + +// This method is called when a DOM window receives a blur event +// (DOMWindow::blur). +void BrowserWebViewDelegate::didBlur() { + if (WebWidgetHost* host = GetWidgetHost()) + browser_->UIT_SetFocus(host, false); +} + +void BrowserWebViewDelegate::closeWidgetSoon() { + if (this == browser_->UIT_GetWebViewDelegate()) { + browser_->UIT_CloseBrowser(); + } else if (this == browser_->UIT_GetPopupDelegate()) { + browser_->UIT_ClosePopupWidget(); + } +} + +WebScreenInfo BrowserWebViewDelegate::screenInfo() { + if (WebWidgetHost* host = GetWidgetHost()) { + WebScreenInfo info = host->GetScreenInfo(); + + if (browser_->IsWindowRenderingDisabled()) { + // Retrieve the screen rectangle from the handler. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) { + CefRect rect(info.rect.x, info.rect.y, info.rect.width, + info.rect.height); + if (handler->GetScreenRect(browser_, rect)) { + info.rect = WebRect(rect.x, rect.y, rect.width, rect.height); + info.availableRect = info.rect; + } + } + } + } + + return info; + } + + return WebScreenInfo(); +} + +// WebFrameClient ------------------------------------------------------------ + +WebPlugin* BrowserWebViewDelegate::createPlugin( + WebFrame* frame, const WebPluginParams& params) { + bool allow_wildcard = true; + std::vector plugins; + std::vector mime_types; + webkit::npapi::PluginList::Singleton()->GetPluginInfoArray( + params.url, params.mimeType.utf8(), allow_wildcard, + NULL, &plugins, &mime_types); + if (plugins.empty()) + return NULL; + +#if defined(OS_MACOSX) + // Mac does not supported windowed plugins. + bool force_windowless = true; +#else + bool force_windowless = browser_->IsWindowRenderingDisabled(); +#endif + + if (force_windowless) { + DCHECK_EQ(params.attributeNames.size(), params.attributeValues.size()); + + std::string mime_type = mime_types.front(); + 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) { + WebPluginParams params_copy = params; + params_copy.mimeType = WebString::fromUTF8(mime_type); + + // Force Flash and Silverlight plugins to use windowless mode. + size_t size = params_copy.attributeNames.size(); + + WebVector new_names(size+1), new_values(size+1); + + for (size_t i = 0; i < size; ++i) { + new_names[i] = params_copy.attributeNames[i]; + new_values[i] = params_copy.attributeValues[i]; + } + + if (flash) { + new_names[size] = "wmode"; + new_values[size] = "opaque"; + } else if (silverlight) { + new_names[size] = "windowless"; + new_values[size] = "true"; + } + + params_copy.attributeNames.swap(new_names); + params_copy.attributeValues.swap(new_values); + + return new webkit::npapi::WebPluginImpl( + frame, params_copy, plugins.front().path, AsWeakPtr()); + } + } + + return new webkit::npapi::WebPluginImpl( + frame, params, plugins.front().path, AsWeakPtr()); +} + +WebMediaPlayer* BrowserWebViewDelegate::createMediaPlayer( + WebFrame* frame, WebMediaPlayerClient* client) { + scoped_ptr message_loop_factory( + new media::MessageLoopFactory()); + + scoped_ptr collection( + new media::FilterCollection()); + + // Add the audio renderer. + // TODO(vrk): Re-enable audio. (crbug.com/112159) + collection->AddAudioRenderer( + new media::AudioRendererImpl(new media::NullAudioSink())); + + return new webkit_media::WebMediaPlayerImpl( + frame, + client, + base::WeakPtr(), + collection.release(), + NULL, + message_loop_factory.release(), + NULL, + new media::MediaLog()); +} + +WebApplicationCacheHost* BrowserWebViewDelegate::createApplicationCacheHost( + WebFrame* frame, WebApplicationCacheHostClient* client) { + return BrowserAppCacheSystem::CreateApplicationCacheHost(client); +} + +WebKit::WebCookieJar* BrowserWebViewDelegate::cookieJar(WebFrame* frame) { + return &cookie_jar_; +} + +void BrowserWebViewDelegate::willClose(WebFrame* frame) { + browser_->UIT_BeforeFrameClosed(frame); +} + +void BrowserWebViewDelegate::loadURLExternally( + WebFrame* frame, const WebURLRequest& request, + WebNavigationPolicy policy) { + DCHECK_NE(policy, WebKit::WebNavigationPolicyCurrentTab); + std::string url = request.url().spec().data(); + CefRefPtr newBrowser = + browser_->UIT_CreatePopupWindow(url, CefPopupFeatures()); + if (newBrowser.get() && !url.empty()) + newBrowser->GetMainFrame()->LoadURL(url); +} + +WebNavigationPolicy BrowserWebViewDelegate::decidePolicyForNavigation( + WebFrame* frame, const WebURLRequest& request, + WebNavigationType type, const WebNode& originating_node, + WebNavigationPolicy default_policy, bool is_redirect) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + // Gather browse request information + CefRefPtr req(CefRequest::CreateRequest()); + + GURL request_url = request.url(); + if (!request_url.is_valid()) + return WebKit::WebNavigationPolicyIgnore; + + req->SetURL(request_url.spec()); + req->SetMethod(string16(request.httpMethod())); + + const WebKit::WebHTTPBody& httpBody = request.httpBody(); + if (!httpBody.isNull()) { + CefRefPtr postdata(CefPostData::CreatePostData()); + static_cast(postdata.get())->Set(httpBody); + req->SetPostData(postdata); + } + + CefRequest::HeaderMap map; + CefRequestImpl::GetHeaderMap(request, map); + if (map.size() > 0) + static_cast(req.get())->SetHeaderMap(map); + + cef_handler_navtype_t navType; + if (browser_->is_dropping()) + navType = NAVTYPE_LINKDROPPED; + else + navType = (cef_handler_navtype_t)type; + + // Notify the handler of a browse request + bool handled = handler->OnBeforeBrowse(browser_, + browser_->UIT_GetCefFrame(frame), req, navType, + is_redirect); + if (handled) + return WebKit::WebNavigationPolicyIgnore; + } + } + + WebNavigationPolicy result; + if (policy_delegate_enabled_) { + if (policy_delegate_is_permissive_) { + result = WebKit::WebNavigationPolicyCurrentTab; + } else { + result = WebKit::WebNavigationPolicyIgnore; + } + } else { + result = default_policy; + } + return result; +} + +WebURLError BrowserWebViewDelegate::cannotHandleRequestError( + WebFrame* frame, const WebURLRequest& request) { + WebURLError error; + error.domain = WebString::fromUTF8(net::kErrorDomain); + error.reason = net::ERR_ABORTED; + error.unreachableURL = request.url(); + return error; +} + +WebURLError BrowserWebViewDelegate::cancelledError( + WebFrame* frame, const WebURLRequest& request) { + WebURLError error; + error.domain = WebString::fromUTF8(net::kErrorDomain); + error.reason = net::ERR_ABORTED; + error.unreachableURL = request.url(); + return error; +} + +void BrowserWebViewDelegate::didCreateDataSource( + WebFrame* frame, WebDataSource* ds) { + ds->setExtraData(pending_extra_data_.release()); + + if (frame->parent() == 0) { + GURL url = ds->request().url(); + if (!url.is_empty()) + browser_->set_pending_url(url); + } +} + +void BrowserWebViewDelegate::didStartProvisionalLoad(WebFrame* frame) { +} + +void BrowserWebViewDelegate::didReceiveServerRedirectForProvisionalLoad( + WebFrame* frame) { +} + +void BrowserWebViewDelegate::didFailProvisionalLoad( + WebFrame* frame, const WebURLError& error) { + // error codes are defined in net\base\net_error_list.h + + // Don't display an error page if this is simply a cancelled load. Aside + // from being dumb, WebCore doesn't expect it and it will cause a crash. + if (error.reason == net::ERR_ABORTED) + return; + + const WebDataSource* failed_ds = frame->provisionalDataSource(); + BrowserExtraData* extra_data = + static_cast(failed_ds->extraData()); + + if (extra_data && !extra_data->request_committed) { + // Set the pending extra_data for our error page as the same pending_page_id + // to keep the history from getting messed up. + set_pending_extra_data(new BrowserExtraData(extra_data->pending_page_id)); + } + + std::string error_text; + CefString errorStr; + + bool handled = false; + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetLoadHandler(); + if (handler.get()) { + // give the handler an opportunity to generate a custom error message + handled = handler->OnLoadError(browser_, + browser_->UIT_GetCefFrame(frame), + static_cast(error.reason), + std::string(failed_ds->request().url().spec().data()), errorStr); + } + } + + if (handled && !errorStr.empty()) { + error_text = errorStr; + } else { + error_text = base::StringPrintf("Error %d when loading url %s", + error.reason, failed_ds->request().url().spec().data()); + } + + // Make sure we never show errors in view source mode. + frame->enableViewSourceMode(false); + + frame->loadHTMLString( + error_text, GURL("cef-error:"), error.unreachableURL, false); + + // In case loadHTMLString failed before DidCreateDataSource was called. + set_pending_extra_data(NULL); +} + +void BrowserWebViewDelegate::didCommitProvisionalLoad( + WebFrame* frame, bool is_new_navigation) { + bool is_main_frame = (frame->parent() == 0); + if (is_main_frame) { + // Clear the title so we can tell if it wasn't provided by the page. + browser_->UIT_SetTitle(std::wstring()); + } + + UpdateForCommittedLoad(frame, is_new_navigation); + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetLoadHandler(); + if (handler.get()) { + // Notify the handler that loading has started. + handler->OnLoadStart(browser_, browser_->UIT_GetCefFrame(frame)); + } + } + + // Apply zoom settings only on top-level frames. + if (is_main_frame) { + // Restore the zoom value that we have for this URL, if any. + double zoomLevel = 0.0; + ZoomMap::GetInstance()->get(frame->document().url(), zoomLevel); + frame->view()->setZoomLevel(false, zoomLevel); + browser_->set_zoom_level(zoomLevel); + } +} + +void BrowserWebViewDelegate::didCreateScriptContext( + WebFrame* frame, v8::Handle context, int extensionGroup, + int worldId) { + CefRefPtr client = browser_->GetClient(); + if (!client.get()) + return; + + CefRefPtr handler = client->GetV8ContextHandler(); + if (!handler.get()) + return; + + v8::HandleScope handle_scope; + v8::Context::Scope scope(context); + + CefRefPtr framePtr(browser_->UIT_GetCefFrame(frame)); + CefRefPtr contextPtr(new CefV8ContextImpl(context)); + + handler->OnContextCreated(browser_, framePtr, contextPtr); +} + +void BrowserWebViewDelegate::willReleaseScriptContext( + WebFrame* frame, v8::Handle context, int worldId) { + CefRefPtr client = browser_->GetClient(); + if (!client.get()) + return; + + CefRefPtr handler = client->GetV8ContextHandler(); + if (!handler.get()) + return; + + v8::HandleScope handle_scope; + v8::Context::Scope scope(context); + + CefRefPtr framePtr(browser_->UIT_GetCefFrame(frame)); + CefRefPtr contextPtr(new CefV8ContextImpl(context)); + + handler->OnContextReleased(browser_, framePtr, contextPtr); +} + +void BrowserWebViewDelegate::didReceiveTitle( + WebFrame* frame, const WebString& title, WebTextDirection direction) { + bool is_main_frame = (frame->parent() == 0); + if (is_main_frame) { + CefString titleStr = string16(title); + browser_->UIT_SetTitle(titleStr); + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) { + // Notify the handler of a page title change + handler->OnTitleChange(browser_, titleStr); + } + } + } +} + +void BrowserWebViewDelegate::didFailLoad( + WebFrame* frame, const WebURLError& error) { + LocationChangeDone(frame); +} + +void BrowserWebViewDelegate::didFinishLoad(WebFrame* frame) { + LocationChangeDone(frame); +} + +void BrowserWebViewDelegate::didNavigateWithinPage( + WebFrame* frame, bool is_new_navigation) { + frame->dataSource()->setExtraData(pending_extra_data_.release()); + UpdateForCommittedLoad(frame, is_new_navigation); +} + +void BrowserWebViewDelegate::willSendRequest( + WebFrame* frame, unsigned identifier, WebURLRequest& request, + const WebURLResponse& redirect_response) { + if (!redirect_response.isNull() && block_redirects_) { + // To block the request, we set its URL to an empty one. + request.setURL(WebURL()); + return; + } + + // The requestor ID is used by the resource loader bridge to locate the + // browser that originated the request. + request.setRequestorID(browser_->UIT_GetUniqueID()); +} + +void BrowserWebViewDelegate::didChangeContentsSize( + WebFrame* frame, const WebSize& size) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) { + handler->OnContentsSizeChange(browser_, browser_->UIT_GetCefFrame(frame), + size.width, size.height); + } + } +} + +void BrowserWebViewDelegate::reportFindInPageMatchCount( + int request_id, int count, bool final_update) { + browser_->UIT_NotifyFindStatus(request_id, count, gfx::Rect(), + -1, // Don't update active match ordinal. + final_update); +} + +void BrowserWebViewDelegate::reportFindInPageSelection( + int request_id, int active_match_ordinal, const WebKit::WebRect& sel) { + browser_->UIT_NotifyFindStatus(request_id, -1, sel, active_match_ordinal, + false); +} + +void BrowserWebViewDelegate::openFileSystem( + WebFrame* frame, WebFileSystem::Type type, + long long size, // NOLINT(runtime/int) + bool create, + WebFileSystemCallbacks* callbacks) { + BrowserFileSystem* fileSystem = static_cast( + WebKit::webKitPlatformSupport()->fileSystem()); + fileSystem->OpenFileSystem(frame, type, size, create, callbacks); +} + +// Public methods ------------------------------------------------------------ + +BrowserWebViewDelegate::BrowserWebViewDelegate(CefBrowserImpl* browser) + : policy_delegate_enabled_(false), + policy_delegate_is_permissive_(false), + policy_delegate_should_notify_done_(false), + browser_(browser), + page_id_(-1), + last_page_id_updated_(-1), +#if defined(OS_WIN) + destroy_on_drag_end_(false), +#endif + smart_insert_delete_enabled_(true), +#if defined(OS_WIN) + select_trailing_whitespace_enabled_(true), +#else + select_trailing_whitespace_enabled_(false), +#endif + block_redirects_(false), + cookie_jar_(browser) { +} + +BrowserWebViewDelegate::~BrowserWebViewDelegate() { +} + +void BrowserWebViewDelegate::Reset() { + // Do a little placement new dance... + CefBrowserImpl* browser = browser_; + this->~BrowserWebViewDelegate(); + new (this)BrowserWebViewDelegate(browser); // NOLINT(whitespace/parens) +} + +void BrowserWebViewDelegate::SetSmartInsertDeleteEnabled(bool enabled) { + smart_insert_delete_enabled_ = enabled; + // In upstream WebKit, smart insert/delete is mutually exclusive with select + // trailing whitespace, however, we allow both because Chromium on Windows + // allows both. +} + +void BrowserWebViewDelegate::SetSelectTrailingWhitespaceEnabled(bool enabled) { + select_trailing_whitespace_enabled_ = enabled; + // In upstream WebKit, smart insert/delete is mutually exclusive with select + // trailing whitespace, however, we allow both because Chromium on Windows + // allows both. +} + +void BrowserWebViewDelegate::SetCustomPolicyDelegate(bool is_custom, + bool is_permissive) { + policy_delegate_enabled_ = is_custom; + policy_delegate_is_permissive_ = is_permissive; +} + +void BrowserWebViewDelegate::WaitForPolicyDelegate() { + policy_delegate_enabled_ = true; + policy_delegate_should_notify_done_ = true; +} + +// Private methods ----------------------------------------------------------- + +bool BrowserWebViewDelegate::OnKeyboardEvent( + const WebKit::WebKeyboardEvent& event, bool isAfterJavaScript) { + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetKeyboardHandler(); + if (!handler.get()) + return false; + + CefKeyboardHandler::KeyEventType eventType; + switch (event.type) { + case WebKeyboardEvent::RawKeyDown: + eventType = KEYEVENT_RAWKEYDOWN; + break; + case WebKeyboardEvent::KeyDown: + eventType = KEYEVENT_KEYDOWN; + break; + case WebKeyboardEvent::KeyUp: + eventType = KEYEVENT_KEYUP; + break; + case WebKeyboardEvent::Char: + eventType = KEYEVENT_CHAR; + break; + default: + return false; + } + + return handler->OnKeyEvent(browser_, eventType, event.windowsKeyCode, + event.modifiers, event.isSystemKey?true:false, isAfterJavaScript); +} + +void BrowserWebViewDelegate::ShowStatus(const WebString& text, + cef_handler_statustype_t type) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) { + CefString textStr = string16(text); + handler->OnStatusMessage(browser_, textStr, type); + } + } +} + +void BrowserWebViewDelegate::LocationChangeDone(WebFrame* frame) { + CefRefPtr client = browser_->GetClient(); + if (!client.get()) + return; + + bool is_main_frame = (frame->parent() == 0); + if (is_main_frame) { + CefString title = browser_->UIT_GetTitle(); + if (title.empty()) { + // No title was provided by the page, so send a blank string to the + // client. + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) + handler->OnTitleChange(browser_, title); + } + } + + CefRefPtr handler = client->GetLoadHandler(); + if (handler.get()) { + // Notify the handler that loading has ended. + int httpStatusCode = frame->dataSource()->response().httpStatusCode(); + handler->OnLoadEnd(browser_, browser_->UIT_GetCefFrame(frame), + httpStatusCode); + } +} + +WebWidgetHost* BrowserWebViewDelegate::GetWidgetHost() { + if (this == browser_->UIT_GetWebViewDelegate()) + return browser_->UIT_GetWebViewHost(); + if (this == browser_->UIT_GetPopupDelegate()) + return browser_->UIT_GetPopupHost(); + return NULL; +} + +void BrowserWebViewDelegate::UpdateForCommittedLoad(WebFrame* frame, + bool is_new_navigation) { + // Code duplicated from RenderView::DidCommitLoadForFrame. + BrowserExtraData* extra_data = static_cast( + frame->dataSource()->extraData()); + + if (is_new_navigation) { + // New navigation. + UpdateSessionHistory(frame); + page_id_ = next_page_id_++; + } else if (extra_data && extra_data->pending_page_id != -1 && + !extra_data->request_committed) { + // This is a successful session history navigation! + UpdateSessionHistory(frame); + page_id_ = extra_data->pending_page_id; + } + + // Don't update session history multiple times. + if (extra_data) + extra_data->request_committed = true; + + UpdateURL(frame); +} + +void BrowserWebViewDelegate::UpdateURL(WebFrame* frame) { + WebDataSource* ds = frame->dataSource(); + DCHECK(ds); + + const WebURLRequest& request = ds->request(); + BrowserNavigationController* controller = + browser_->UIT_GetNavigationController(); + + if (controller->GetEntryCount() == 0) { + // This is the first navigation for the browser. Indicate that the browser + // now has a document. + browser_->set_has_document(true); + } + + // Type is unused. + scoped_ptr entry(new BrowserNavigationEntry); + + // Bug 654101: the referrer will be empty on https->http transitions. It + // would be nice if we could get the real referrer from somewhere. + entry->SetPageID(page_id_); + if (ds->hasUnreachableURL()) { + entry->SetURL(ds->unreachableURL()); + } else { + entry->SetURL(request.url()); + } + + // Update attributes of the CefFrame if it currently exists. + browser_->UIT_UpdateCefFrame(frame); + + bool is_main_frame = (frame->parent() == 0); + CefRefPtr client = browser_->GetClient(); + + if (is_main_frame && client.get()) { + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) { + // Notify the handler of an address change + std::string url = std::string(entry->GetURL().spec().c_str()); + handler->OnAddressChange(browser_, browser_->UIT_GetCefFrame(frame), url); + } + } + + const WebHistoryItem& history_item = frame->currentHistoryItem(); + if (!history_item.isNull()) + entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); + + bool old_can_go_back = !controller->IsAtStart(); + bool old_can_go_forward = !controller->IsAtEnd(); + controller->DidNavigateToEntry(entry.release()); + bool new_can_go_back = !controller->IsAtStart(); + bool new_can_go_forward = !controller->IsAtEnd(); + + last_page_id_updated_ = std::max(last_page_id_updated_, page_id_); + + if (old_can_go_back != new_can_go_back || + old_can_go_forward != new_can_go_forward) { + browser_->set_nav_state(new_can_go_back, new_can_go_forward); + CefRefPtr handler = client->GetDisplayHandler(); + if (handler.get()) { + // Notify the handler of a navigation state change + handler->OnNavStateChange(browser_, new_can_go_back, new_can_go_forward); + } + } +} + +void BrowserWebViewDelegate::UpdateSessionHistory(WebFrame* frame) { + // If we have a valid page ID at this point, then it corresponds to the page + // we are navigating away from. Otherwise, this is the first navigation, so + // there is no past session history to record. + if (page_id_ == -1) + return; + + BrowserNavigationEntry* entry = static_cast( + browser_->UIT_GetNavigationController()->GetEntryWithPageID(page_id_)); + if (!entry) + return; + + WebView* view = browser_->UIT_GetWebView(); + if (!view) + return; + + const WebHistoryItem& history_item = view->mainFrame()->previousHistoryItem(); + if (history_item.isNull()) + return; + + entry->SetContentState(webkit_glue::HistoryItemToString(history_item)); +} + +bool BrowserWebViewDelegate::OnBeforeMenu( + const WebKit::WebContextMenuData& data, int mouse_x, int mouse_y, + int& edit_flags, int& type_flags) { + // Populate the edit flags values. + edit_flags = data.editFlags; + if (browser_->UIT_CanGoBack()) + edit_flags |= MENU_CAN_GO_BACK; + if (browser_->UIT_CanGoForward()) + edit_flags |= MENU_CAN_GO_FORWARD; + + // Populate the type flags values. + type_flags = MENUTYPE_NONE; + if (!data.pageURL.isEmpty()) + type_flags |= MENUTYPE_PAGE; + if (!data.frameURL.isEmpty()) + type_flags |= MENUTYPE_FRAME; + if (!data.linkURL.isEmpty()) + type_flags |= MENUTYPE_LINK; + if (data.mediaType == WebContextMenuData::MediaTypeImage) + type_flags |= MENUTYPE_IMAGE; + if (!data.selectedText.isEmpty()) + type_flags |= MENUTYPE_SELECTION; + if (data.isEditable) + type_flags |= MENUTYPE_EDITABLE; + if (data.isSpellCheckingEnabled && !data.misspelledWord.isEmpty()) + type_flags |= MENUTYPE_MISSPELLED_WORD; + if (data.mediaType == WebContextMenuData::MediaTypeVideo) + type_flags |= MENUTYPE_VIDEO; + if (data.mediaType == WebContextMenuData::MediaTypeAudio) + type_flags |= MENUTYPE_AUDIO; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetMenuHandler(); + + if (handler.get()) { + // Gather menu information. + CefMenuInfo menuInfo; + + CefString linkStr(std::string(data.linkURL.spec())); + CefString imageStr(std::string(data.srcURL.spec())); + CefString pageStr(std::string(data.pageURL.spec())); + CefString frameStr(std::string(data.frameURL.spec())); + CefString selectedTextStr(string16(data.selectedText)); + CefString misspelledWordStr(string16(data.misspelledWord)); + CefString securityInfoStr(std::string(data.securityInfo)); + + menuInfo.typeFlags = type_flags; + menuInfo.x = mouse_x; + menuInfo.y = mouse_y; + cef_string_set(linkStr.c_str(), linkStr.length(), &menuInfo.linkUrl, false); + cef_string_set(imageStr.c_str(), imageStr.length(), &menuInfo.imageUrl, + false); + cef_string_set(pageStr.c_str(), pageStr.length(), &menuInfo.pageUrl, false); + cef_string_set(frameStr.c_str(), frameStr.length(), &menuInfo.frameUrl, + false); + cef_string_set(selectedTextStr.c_str(), selectedTextStr.length(), + &menuInfo.selectionText, false); + cef_string_set(misspelledWordStr.c_str(), misspelledWordStr.length(), + &menuInfo.misspelledWord, false); + menuInfo.editFlags = edit_flags; + cef_string_set(securityInfoStr.c_str(), securityInfoStr.length(), + &menuInfo.securityInfo, false); + + // Notify the handler that a context menu is requested. + if (handler->OnBeforeMenu(browser_, menuInfo)) + return true; + } + + return false; +} diff --git a/cef1/libcef/browser_webview_delegate.h b/cef1/libcef/browser_webview_delegate.h new file mode 100644 index 000000000..2893e1618 --- /dev/null +++ b/cef1/libcef/browser_webview_delegate.h @@ -0,0 +1,405 @@ +// Copyright (c) 2008-2009 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. + +// BrowserWebViewDelegate class: +// This class implements the WebViewDelegate methods for the test shell. One +// instance is owned by each CefBrowser. + +#ifndef CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_ +#define CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_ +#pragma once + +#include +#include +#include + +#include "libcef/browser_navigation_controller.h" +#include "libcef/browser_webcookiejar_impl.h" + +#include "base/basictypes.h" +#include "base/compiler_specific.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "build/build_config.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFileChooserParams.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebFileSystem.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrameClient.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPermissionClient.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPrerendererClient.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebViewClient.h" +#include "webkit/glue/webcursor.h" +#include "webkit/plugins/npapi/webplugin_page_delegate.h" + +#if defined(TOOLKIT_GTK) +#include // NOLINT(build/include_order) +#endif + +#if defined(OS_MACOSX) +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenuInfo.h" +#include "libcef/external_popup_menu_mac.h" +#endif + +#if defined(OS_WIN) +class BrowserDragDelegate; +class WebDropTarget; +#endif + +#if defined(OS_LINUX) +class WebDragSource; +class WebDropTarget; +#endif + +class CefBrowserImpl; +class GURL; +class WebWidgetHost; +class FilePath; + +class BrowserWebViewDelegate : public WebKit::WebViewClient, + public WebKit::WebFrameClient, + public WebKit::WebPermissionClient, + public WebKit::WebPrerendererClient, + public webkit::npapi::WebPluginPageDelegate, + public base::SupportsWeakPtr { + public: + // WebKit::WebViewClient + virtual WebKit::WebView* createView( + WebKit::WebFrame* creator, const WebKit::WebURLRequest& request, + const WebKit::WebWindowFeatures& features, const WebKit::WebString& name, + WebKit::WebNavigationPolicy policy) OVERRIDE; + virtual WebKit::WebWidget* createPopupMenu(WebKit::WebPopupType popup_type) + OVERRIDE; + virtual WebKit::WebExternalPopupMenu* createExternalPopupMenu( + const WebKit::WebPopupMenuInfo& info, + WebKit::WebExternalPopupMenuClient* client) OVERRIDE; + virtual WebKit::WebStorageNamespace* createSessionStorageNamespace( + unsigned quota) OVERRIDE; + virtual WebKit::WebGraphicsContext3D* createGraphicsContext3D( + const WebKit::WebGraphicsContext3D::Attributes& attributes) OVERRIDE; + virtual void didAddMessageToConsole( + const WebKit::WebConsoleMessage& message, + const WebKit::WebString& source_name, unsigned source_line) OVERRIDE; + virtual void printPage(WebKit::WebFrame* frame) OVERRIDE; + virtual bool shouldBeginEditing(const WebKit::WebRange& range) OVERRIDE; + virtual bool shouldEndEditing(const WebKit::WebRange& range) OVERRIDE; + virtual bool shouldInsertNode( + const WebKit::WebNode& node, const WebKit::WebRange& range, + WebKit::WebEditingAction action) OVERRIDE; + virtual bool shouldInsertText( + const WebKit::WebString& text, const WebKit::WebRange& range, + WebKit::WebEditingAction action) OVERRIDE; + virtual bool shouldChangeSelectedRange( + const WebKit::WebRange& from, const WebKit::WebRange& to, + WebKit::WebTextAffinity affinity, bool still_selecting) OVERRIDE; + virtual bool shouldDeleteRange(const WebKit::WebRange& range) OVERRIDE; + virtual bool shouldApplyStyle( + const WebKit::WebString& style, const WebKit::WebRange& range) OVERRIDE; + virtual bool isSmartInsertDeleteEnabled() OVERRIDE; + virtual bool isSelectTrailingWhitespaceEnabled() OVERRIDE; + virtual bool handleCurrentKeyboardEvent() OVERRIDE; + virtual bool runFileChooser( + const WebKit::WebFileChooserParams& params, + WebKit::WebFileChooserCompletion* chooser_completion) OVERRIDE; + virtual void runModalAlertDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message) OVERRIDE; + virtual bool runModalConfirmDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message) OVERRIDE; + virtual bool runModalPromptDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message, + const WebKit::WebString& default_value, WebKit::WebString* actual_value) + OVERRIDE; + virtual bool runModalBeforeUnloadDialog( + WebKit::WebFrame* frame, const WebKit::WebString& message) OVERRIDE; + virtual void showContextMenu( + WebKit::WebFrame* frame, const WebKit::WebContextMenuData& data) OVERRIDE; + virtual void setStatusText(const WebKit::WebString& text) OVERRIDE; + virtual void setMouseOverURL(const WebKit::WebURL& url) OVERRIDE; + virtual void setKeyboardFocusURL(const WebKit::WebURL& url) OVERRIDE; + virtual void setToolTipText( + const WebKit::WebString& text, WebKit::WebTextDirection hint) OVERRIDE; + virtual void startDragging( + WebKit::WebFrame* frame, + const WebKit::WebDragData& data, + WebKit::WebDragOperationsMask mask, + const WebKit::WebImage& image, + const WebKit::WebPoint& image_offset) OVERRIDE; + virtual bool acceptsLoadDrops() OVERRIDE; + virtual void focusNext() OVERRIDE; + virtual void focusPrevious() OVERRIDE; + virtual void focusedNodeChanged(const WebKit::WebNode& node) OVERRIDE; + virtual void navigateBackForwardSoon(int offset) OVERRIDE; + virtual int historyBackListCount() OVERRIDE; + virtual int historyForwardListCount() OVERRIDE; + + // WebKit::WebWidgetClient + virtual void didInvalidateRect(const WebKit::WebRect& rect) OVERRIDE; + virtual void didScrollRect(int dx, int dy, + const WebKit::WebRect& clip_rect) OVERRIDE; + virtual void scheduleComposite() OVERRIDE; + virtual void scheduleAnimation() OVERRIDE; + virtual void didFocus() OVERRIDE; + virtual void didBlur() OVERRIDE; + virtual void didChangeCursor(const WebKit::WebCursorInfo& cursor) OVERRIDE; + virtual void closeWidgetSoon() OVERRIDE; + virtual void show(WebKit::WebNavigationPolicy policy) OVERRIDE; + virtual void runModal() OVERRIDE; + virtual WebKit::WebRect windowRect() OVERRIDE; + virtual void setWindowRect(const WebKit::WebRect& rect) OVERRIDE; + virtual WebKit::WebRect rootWindowRect() OVERRIDE; + virtual WebKit::WebRect windowResizerRect() OVERRIDE; + virtual WebKit::WebScreenInfo screenInfo() OVERRIDE; + + // WebKit::WebFrameClient + virtual WebKit::WebPlugin* createPlugin( + WebKit::WebFrame*, const WebKit::WebPluginParams&) OVERRIDE; + virtual WebKit::WebMediaPlayer* createMediaPlayer( + WebKit::WebFrame*, WebKit::WebMediaPlayerClient*) OVERRIDE; + virtual WebKit::WebApplicationCacheHost* createApplicationCacheHost( + WebKit::WebFrame* frame, WebKit::WebApplicationCacheHostClient* client) + OVERRIDE; + virtual WebKit::WebCookieJar* cookieJar(WebKit::WebFrame*) OVERRIDE; + virtual void willClose(WebKit::WebFrame*) OVERRIDE; + virtual void loadURLExternally( + WebKit::WebFrame*, const WebKit::WebURLRequest&, + WebKit::WebNavigationPolicy) OVERRIDE; + virtual WebKit::WebNavigationPolicy decidePolicyForNavigation( + WebKit::WebFrame*, const WebKit::WebURLRequest&, + WebKit::WebNavigationType, const WebKit::WebNode&, + WebKit::WebNavigationPolicy default_policy, bool isRedirect) OVERRIDE; + virtual bool canHandleRequest( + WebKit::WebFrame*, const WebKit::WebURLRequest&) OVERRIDE { return true; } + virtual WebKit::WebURLError cannotHandleRequestError( + WebKit::WebFrame*, const WebKit::WebURLRequest& request) OVERRIDE; + virtual WebKit::WebURLError cancelledError( + WebKit::WebFrame*, const WebKit::WebURLRequest& request) OVERRIDE; + virtual void didCreateDataSource( + WebKit::WebFrame*, WebKit::WebDataSource*) OVERRIDE; + virtual void didStartProvisionalLoad(WebKit::WebFrame*) OVERRIDE; + virtual void didReceiveServerRedirectForProvisionalLoad(WebKit::WebFrame*) + OVERRIDE; + virtual void didFailProvisionalLoad( + WebKit::WebFrame*, const WebKit::WebURLError&) OVERRIDE; + virtual void didCommitProvisionalLoad( + WebKit::WebFrame*, bool is_new_navigation) OVERRIDE; + virtual void didCreateScriptContext( + WebKit::WebFrame*, v8::Handle, int extensionGroup, + int worldId) OVERRIDE; + virtual void willReleaseScriptContext( + WebKit::WebFrame*, v8::Handle, int worldId) OVERRIDE; + virtual void didReceiveTitle( + WebKit::WebFrame*, const WebKit::WebString& title, + WebKit::WebTextDirection direction) OVERRIDE; + virtual void didFailLoad( + WebKit::WebFrame*, const WebKit::WebURLError&) OVERRIDE; + virtual void didFinishLoad(WebKit::WebFrame*) OVERRIDE; + virtual void didNavigateWithinPage( + WebKit::WebFrame*, bool isNewNavigation) OVERRIDE; + virtual void willSendRequest( + WebKit::WebFrame*, unsigned identifier, WebKit::WebURLRequest&, + const WebKit::WebURLResponse& redirectResponse) OVERRIDE; + virtual void didChangeContentsSize( + WebKit::WebFrame*, const WebKit::WebSize&) OVERRIDE; + virtual void reportFindInPageMatchCount( + int request_id, int count, bool final_update) OVERRIDE; + virtual void reportFindInPageSelection( + int request_id, int active_match_ordinal, const WebKit::WebRect& sel) + OVERRIDE; + virtual void openFileSystem( + WebKit::WebFrame* frame, + WebKit::WebFileSystem::Type type, + long long size, // NOLINT(runtime/int) + bool create, + WebKit::WebFileSystemCallbacks* callbacks) OVERRIDE; + + // WebKit::WebPermissionClient + virtual bool allowScriptExtension( + WebKit::WebFrame*, + const WebKit::WebString& extensionName, + int extensionGroup) OVERRIDE; + + // WebKit::WebPrerendererClient + virtual void willAddPrerender(WebKit::WebPrerender* prerender) OVERRIDE; + + // webkit_glue::WebPluginPageDelegate + virtual webkit::npapi::WebPluginDelegate* CreatePluginDelegate( + const FilePath& file_path, + const std::string& mime_type) OVERRIDE; + virtual WebKit::WebPlugin* CreatePluginReplacement( + const FilePath& file_path) OVERRIDE; + virtual void CreatedPluginWindow( + gfx::PluginWindowHandle handle) OVERRIDE; + virtual void WillDestroyPluginWindow( + gfx::PluginWindowHandle handle) OVERRIDE; + virtual void DidMovePlugin( + const webkit::npapi::WebPluginGeometry& move) OVERRIDE; + virtual void DidStartLoadingForPlugin() OVERRIDE {} + virtual void DidStopLoadingForPlugin() OVERRIDE {} + virtual WebKit::WebCookieJar* GetCookieJar() OVERRIDE; + + explicit BrowserWebViewDelegate(CefBrowserImpl* browser); + virtual ~BrowserWebViewDelegate(); + void Reset(); + + void SetSmartInsertDeleteEnabled(bool enabled); + void SetSelectTrailingWhitespaceEnabled(bool enabled); + + // Additional accessors +#if defined(OS_WIN) || defined(OS_LINUX) + // Sets the webview as a drop target. + void RegisterDragDrop(); +#endif +#if defined(OS_WIN) + void RevokeDragDrop(); + + // Called after dragging has finished. + void EndDragging(); + + BrowserDragDelegate* drag_delegate() { return drag_delegate_.get(); } + WebDropTarget* drop_target() { return drop_target_.get(); } + + void set_destroy_on_drag_end(bool val) { destroy_on_drag_end_ = val; } +#endif // defined(OS_WIN) + + void set_pending_extra_data(BrowserExtraData* extra_data) { + pending_extra_data_.reset(extra_data); + } + + void SetCustomPolicyDelegate(bool is_custom, bool is_permissive); + void WaitForPolicyDelegate(); + + void set_block_redirects(bool block_redirects) { + block_redirects_ = block_redirects; + } + bool block_redirects() const { + return block_redirects_; + } + + void SetEditCommand(const std::string& name, const std::string& value) { + edit_command_name_ = name; + edit_command_value_ = value; + } + + void ClearEditCommand() { + edit_command_name_.clear(); + edit_command_value_.clear(); + } + + CefBrowserImpl* GetBrowser() { return browser_; } + +#if defined(OS_MACOSX) + // Called after the external popup menu has been dismissed. + void ClosePopupMenu(); +#endif + +#ifdef OS_LINUX + void HandleContextMenu(int selected_id); +#endif + + bool OnKeyboardEvent(const WebKit::WebKeyboardEvent& event, + bool isAfterJavaScript); + + protected: + // Default handling of JavaScript messages. + void ShowJavaScriptAlert(WebKit::WebFrame* webframe, + const CefString& message); + bool ShowJavaScriptConfirm(WebKit::WebFrame* webframe, + const CefString& message); + bool ShowJavaScriptPrompt(WebKit::WebFrame* webframe, + const CefString& message, + const CefString& default_value, + CefString* result); + + // Called to show the file chooser dialog. + bool ShowFileChooser(std::vector& file_names, + const bool multi_select, + const WebKit::WebString& title, + const FilePath& default_file); + + // Called to show status messages. + void ShowStatus(const WebKit::WebString& text, cef_handler_statustype_t type); + + // In the Mac code, this is called to trigger the end of a test after the + // page has finished loading. From here, we can generate the dump for the + // test. + void LocationChangeDone(WebKit::WebFrame*); + + WebWidgetHost* GetWidgetHost(); + + void UpdateForCommittedLoad(WebKit::WebFrame* webframe, + bool is_new_navigation); + void UpdateURL(WebKit::WebFrame* frame); + void UpdateSessionHistory(WebKit::WebFrame* frame); + + bool OnBeforeMenu(const WebKit::WebContextMenuData& data, + int mouse_x, + int mouse_y, + int& edit_flags, + int& type_flags); + + private: + // Causes navigation actions just printout the intended navigation instead + // of taking you to the page. This is used for cases like mailto, where you + // don't actually want to open the mail program. + bool policy_delegate_enabled_; + + // Toggles the behavior of the policy delegate. If true, then navigations + // will be allowed. Otherwise, they will be ignored (dropped). + bool policy_delegate_is_permissive_; + + // If true, the policy delegate will signal layout test completion. + bool policy_delegate_should_notify_done_; + + // Non-owning pointer. The delegate is owned by the host. + CefBrowserImpl* browser_; + + // For tracking session history. See RenderView. + int page_id_; + int last_page_id_updated_; + + scoped_ptr pending_extra_data_; + + WebCursor current_cursor_; +#if defined(OS_WIN) + // Classes needed by drag and drop. + scoped_refptr drag_delegate_; + bool destroy_on_drag_end_; +#endif +#if defined(OS_WIN) || defined(OS_LINUX) + scoped_refptr drop_target_; +#endif + +#if defined(OS_LINUX) + // The type of cursor the window is currently using. + // Used for judging whether a new SetCursor call is actually changing the + // cursor. + GdkCursorType cursor_type_; + scoped_refptr drag_source_; +#endif + +#if defined(OS_MACOSX) + // The external popup menu for the currently showing select popup. + scoped_ptr external_popup_menu_; +#endif + + // true if we want to enable smart insert/delete. + bool smart_insert_delete_enabled_; + + // true if we want to enable selection of trailing whitespaces + bool select_trailing_whitespace_enabled_; + + // true if we should block any redirects + bool block_redirects_; + + // Edit command associated to the current keyboard event. + std::string edit_command_name_; + std::string edit_command_value_; + + BrowserWebCookieJarImpl cookie_jar_; + + DISALLOW_COPY_AND_ASSIGN(BrowserWebViewDelegate); +}; + +#endif // CEF_LIBCEF_BROWSER_WEBVIEW_DELEGATE_H_ diff --git a/cef1/libcef/browser_webview_delegate_gtk.cc b/cef1/libcef/browser_webview_delegate_gtk.cc new file mode 100644 index 000000000..f79b1c22d --- /dev/null +++ b/cef1/libcef/browser_webview_delegate_gtk.cc @@ -0,0 +1,414 @@ +// Copyright (c) 2012 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. + +#include "libcef/browser_webview_delegate.h" +#include "libcef/browser_impl.h" +#include "libcef/drag_data_impl.h" +#include "libcef/web_drop_target_gtk.h" +#include "libcef/web_drag_source_gtk.h" + +#include "base/message_loop.h" +#include "base/string_util.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenu.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebImage.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/gtk_util.h" +#include "ui/gfx/point.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/window_open_disposition.h" +#include "webkit/plugins/npapi/plugin_list.h" +#include "webkit/plugins/npapi/webplugin.h" +#include "webkit/plugins/npapi/webplugin_delegate_impl.h" + +#include // NOLINT(build/include_order) +#include // NOLINT(build/include_order) + + +using webkit::npapi::WebPluginDelegateImpl; +using WebKit::WebContextMenuData; +using WebKit::WebCursorInfo; +using WebKit::WebDragData; +using WebKit::WebDragOperationsMask; +using WebKit::WebExternalPopupMenu; +using WebKit::WebExternalPopupMenuClient; +using WebKit::WebFrame; +using WebKit::WebImage; +using WebKit::WebNavigationPolicy; +using WebKit::WebPoint; +using WebKit::WebPopupMenuInfo; +using WebKit::WebRect; +using WebKit::WebWidget; +using WebKit::WebView; + +namespace { + +enum SelectionClipboardType { + TEXT_HTML, + PLAIN_TEXT, +}; + +GdkAtom GetTextHtmlAtom() { + GdkAtom kTextHtmlGdkAtom = gdk_atom_intern_static_string("text/html"); + return kTextHtmlGdkAtom; +} + +void SelectionClipboardGetContents(GtkClipboard* clipboard, + GtkSelectionData* selection_data, guint info, gpointer data) { + // Ignore formats that we don't know about. + if (info != TEXT_HTML && info != PLAIN_TEXT) + return; + + WebView* webview = static_cast(data); + WebFrame* frame = webview->focusedFrame(); + if (!frame) + frame = webview->mainFrame(); + DCHECK(frame); + + std::string selection; + if (TEXT_HTML == info) + selection = frame->selectionAsMarkup().utf8(); + else + selection = frame->selectionAsText().utf8(); + + if (TEXT_HTML == info) { + gtk_selection_data_set(selection_data, + GetTextHtmlAtom(), + 8 /* bits per data unit, ie, char */, + reinterpret_cast(selection.data()), + selection.length()); + } else { + gtk_selection_data_set_text(selection_data, selection.data(), + selection.length()); + } +} + +} // namespace + +// WebViewClient --------------------------------------------------------------- + +WebKit::WebExternalPopupMenu* BrowserWebViewDelegate::createExternalPopupMenu( + const WebKit::WebPopupMenuInfo& info, + WebKit::WebExternalPopupMenuClient* client) { + NOTIMPLEMENTED(); + return NULL; +} + +static gboolean MenuItemHandle(GtkWidget* menu_item, gpointer data) { + if (!data) + return FALSE; + + BrowserWebViewDelegate* webViewDelegate = + reinterpret_cast(data); + int id = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(menu_item), "menu_id")); + + webViewDelegate->HandleContextMenu(id); + + return FALSE; +} + +static GtkWidget* MenuItemCreate(GtkWidget* parent_menu, const char* name, + int id, bool is_enabled, BrowserWebViewDelegate* webViewDelegate) { + GtkWidget* menu_item = gtk_menu_item_new_with_label(name); + + g_object_set_data(G_OBJECT(menu_item), "menu_id", + reinterpret_cast(id)); + g_signal_connect(G_OBJECT(menu_item), "activate", G_CALLBACK(MenuItemHandle), + (gpointer)webViewDelegate); + gtk_menu_shell_append(GTK_MENU_SHELL(parent_menu), menu_item); + gtk_widget_set_sensitive(menu_item, is_enabled); + + gtk_widget_show(menu_item); + + return menu_item; +} + +static GtkWidget* MenuItemCreateSeperator(GtkWidget* parent_menu) { + GtkWidget* menu_item = gtk_menu_item_new(); + + gtk_menu_shell_append(GTK_MENU_SHELL(parent_menu), menu_item); + gtk_widget_show(menu_item); + + return menu_item; +} + +void BrowserWebViewDelegate::showContextMenu(WebKit::WebFrame* frame, + const WebKit::WebContextMenuData& data) { + GtkWidget* menu = NULL; + GdkPoint mouse_pt = { data.mousePosition.x, data.mousePosition.y }; + + int edit_flags = 0; + int type_flags = 0; + + // Make sure events can be pumped while the menu is up. + MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); + + // Give the client a chance to handle the menu. + if (OnBeforeMenu(data, mouse_pt.x, mouse_pt.y, edit_flags, type_flags)) + return; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetMenuHandler(); + + // Build the correct default context menu + if (type_flags & MENUTYPE_EDITABLE) { + menu = gtk_menu_new(); + MenuItemCreate(menu, "Undo", MENU_ID_UNDO, + !!(edit_flags & MENU_CAN_UNDO), this); + MenuItemCreate(menu, "Redo", MENU_ID_REDO, + !!(edit_flags & MENU_CAN_REDO), this); + MenuItemCreate(menu, "Cut", MENU_ID_CUT, + !!(edit_flags & MENU_CAN_CUT), this); + MenuItemCreate(menu, "Copy", MENU_ID_COPY, + !!(edit_flags & MENU_CAN_COPY), this); + MenuItemCreate(menu, "Paste", MENU_ID_PASTE, + !!(edit_flags & MENU_CAN_PASTE), this); + MenuItemCreate(menu, "Delete", MENU_ID_DELETE, + !!(edit_flags & MENU_CAN_DELETE), this); + MenuItemCreateSeperator(menu); + MenuItemCreate(menu, "Select All", MENU_ID_SELECTALL, + !!(edit_flags & MENU_CAN_SELECT_ALL), this); + } else if (type_flags & MENUTYPE_SELECTION) { + menu = gtk_menu_new(); + MenuItemCreate(menu, "Copy", MENU_ID_COPY, + !!(edit_flags & MENU_CAN_COPY), this); + } else if (type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) { + menu = gtk_menu_new(); + MenuItemCreate(menu, "Back", MENU_ID_NAV_BACK, + !!(edit_flags & MENU_CAN_GO_BACK), this); + MenuItemCreate(menu, "Forward", MENU_ID_NAV_FORWARD, + !!(edit_flags & MENU_CAN_GO_FORWARD), this); + MenuItemCreateSeperator(menu); + // TODO(port): Enable the print item when supported. + // MenuItemCreate(menu, "Print", MENU_ID_PRINT, true, this); + MenuItemCreate(menu, "View Source", MENU_ID_VIEWSOURCE, true, this); + } + + if (menu) { + gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, 3, + gtk_get_current_event_time()); + } +} + +// WebWidgetClient ------------------------------------------------------------ + +void BrowserWebViewDelegate::show(WebNavigationPolicy policy) { + WebWidgetHost* host = GetWidgetHost(); + GtkWidget* drawing_area = host->view_handle(); + GtkWidget* window = + gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); + gtk_widget_show_all(window); +} + +void BrowserWebViewDelegate::didChangeCursor(const WebCursorInfo& cursor_info) { + current_cursor_.InitFromCursorInfo(cursor_info); + GdkCursorType cursor_type = + static_cast(current_cursor_.GetCursorType()); + GdkCursor* gdk_cursor; + if (cursor_type == GDK_CURSOR_IS_PIXMAP) { + // TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is + // that calling gdk_window_set_cursor repeatedly is expensive. We should + // avoid it here where possible. + gdk_cursor = current_cursor_.GetCustomCursor(); + } else { + // Optimize the common case, where the cursor hasn't changed. + // However, we can switch between different pixmaps, so only on the + // non-pixmap branch. + if (cursor_type_ == cursor_type) + return; + if (cursor_type == GDK_LAST_CURSOR) + gdk_cursor = NULL; + else + gdk_cursor = gfx::GetCursor(cursor_type); + } + cursor_type_ = cursor_type; + gdk_window_set_cursor(browser_->UIT_GetWebViewWndHandle()->window, + gdk_cursor); +} + +WebRect BrowserWebViewDelegate::windowRect() { + WebWidgetHost* host = GetWidgetHost(); + GtkWidget* drawing_area = host->view_handle(); + GtkWidget* vbox = gtk_widget_get_parent(drawing_area); + GtkWidget* window = gtk_widget_get_parent(vbox); + + gint x, y; + gtk_window_get_position(GTK_WINDOW(window), &x, &y); + x += vbox->allocation.x + drawing_area->allocation.x; + y += vbox->allocation.y + drawing_area->allocation.y; + + return WebRect(x, y, + drawing_area->allocation.width, + drawing_area->allocation.height); +} + +void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { + if (this == browser_->UIT_GetWebViewDelegate()) { + // TODO(port): Set the window rectangle. + } else if (this == browser_->UIT_GetPopupDelegate()) { + WebWidgetHost* host = GetWidgetHost(); + GtkWidget* drawing_area = host->view_handle(); + GtkWidget* window = + gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); + gtk_window_resize(GTK_WINDOW(window), rect.width, rect.height); + gtk_window_move(GTK_WINDOW(window), rect.x, rect.y); + } +} + +WebRect BrowserWebViewDelegate::rootWindowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + // We are being asked for the x/y and width/height of the entire browser + // window. This means the x/y is the distance from the corner of the + // screen, and the width/height is the size of the entire browser window. + // For example, this is used to implement window.screenX and window.screenY. + GtkWidget* window = gtk_widget_get_ancestor(GTK_WIDGET(host->view_handle()), + GTK_TYPE_WINDOW); + + gint x, y, width, height; + gtk_window_get_position(GTK_WINDOW(window), &x, &y); + gtk_window_get_size(GTK_WINDOW(window), &width, &height); + return WebRect(x, y, width, height); + } + return WebRect(); +} + +WebRect BrowserWebViewDelegate::windowResizerRect() { + // Not necessary on Linux. + return WebRect(); +} + +void BrowserWebViewDelegate::startDragging( + WebFrame* frame, + const WebDragData& data, + WebDragOperationsMask mask, + const WebImage& image, + const WebPoint& image_offset) { + if (browser_->settings().drag_drop_disabled) { + browser_->UIT_GetWebView()->dragSourceSystemDragEnded(); + return; + } + + WebDropData drop_data(data); + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDragHandler(); + if (handler.get()) { + CefRefPtr data(new CefDragDataImpl(drop_data)); + if (handler->OnDragStart(browser_, data, + static_cast(mask))) { + browser_->UIT_GetWebView()->dragSourceSystemDragEnded(); + return; + } + } + } + drag_source_ = new WebDragSource(browser_); + drag_source_->StartDragging(drop_data, mask, image, image_offset); +} + +void BrowserWebViewDelegate::runModal() { + NOTIMPLEMENTED(); +} + +// WebPluginPageDelegate ------------------------------------------------------ + +webkit::npapi::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( + const FilePath& path, + const std::string& mime_type) { + // TODO(evanm): we probably shouldn't be doing this mapping to X ids at + // this level. + GdkNativeWindow plugin_parent = + GDK_WINDOW_XWINDOW(browser_->UIT_GetWebViewHost()->view_handle()->window); + + return webkit::npapi::WebPluginDelegateImpl::Create(path, mime_type, + plugin_parent); +} + +void BrowserWebViewDelegate::CreatedPluginWindow( + gfx::PluginWindowHandle id) { + browser_->UIT_GetWebViewHost()->CreatePluginContainer(id); +} + +void BrowserWebViewDelegate::WillDestroyPluginWindow( + gfx::PluginWindowHandle id) { + browser_->UIT_GetWebViewHost()->DestroyPluginContainer(id); +} + +void BrowserWebViewDelegate::DidMovePlugin( + const webkit::npapi::WebPluginGeometry& move) { + WebWidgetHost* host = GetWidgetHost(); + webkit::npapi::GtkPluginContainerManager* plugin_container_manager = + static_cast(host)->plugin_container_manager(); + plugin_container_manager->MovePluginContainer(move); +} + +void BrowserWebViewDelegate::HandleContextMenu(int selected_id) { + if (selected_id != 0) { + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetMenuHandler(); + + // An action was chosen + cef_menu_id_t menuId = static_cast(selected_id); + bool handled = false; + if (handler.get()) { + // Ask the handler if it wants to handle the action + handled = handler->OnMenuAction(browser_, menuId); + } + + if (!handled) { + // Execute the action + browser_->UIT_HandleAction(menuId, browser_->GetFocusedFrame()); + } + } +} + +// Private methods ------------------------------------------------------------ + +void BrowserWebViewDelegate::RegisterDragDrop() { + DCHECK(!drop_target_); + drop_target_ = new WebDropTarget(browser_); +} + +// Protected methods ---------------------------------------------------------- + +void BrowserWebViewDelegate::ShowJavaScriptAlert( + WebKit::WebFrame* webframe, const CefString& message) { + NOTIMPLEMENTED(); +} + +bool BrowserWebViewDelegate::ShowJavaScriptConfirm( + WebKit::WebFrame* webframe, const CefString& message) { + NOTIMPLEMENTED(); + return false; +} + +bool BrowserWebViewDelegate::ShowJavaScriptPrompt( + WebKit::WebFrame* webframe, const CefString& message, + const CefString& default_value, CefString* result) { + NOTIMPLEMENTED(); + return false; +} + +// Called to show the file chooser dialog. +bool BrowserWebViewDelegate::ShowFileChooser(std::vector& file_names, + const bool multi_select, + const WebKit::WebString& title, + const FilePath& default_file) { + NOTIMPLEMENTED(); + return false; +} diff --git a/cef1/libcef/browser_webview_delegate_mac.mm b/cef1/libcef/browser_webview_delegate_mac.mm new file mode 100644 index 000000000..2230be163 --- /dev/null +++ b/cef1/libcef/browser_webview_delegate_mac.mm @@ -0,0 +1,536 @@ +// Copyright (c) 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. + +#include "libcef/browser_webview_delegate.h" +#import "libcef/browser_webview_mac.h" +#include "libcef/browser_impl.h" +#include "libcef/drag_data_impl.h" +#import "include/cef_application_mac.h" + +#import + +#include "base/file_util.h" +#include "base/mac/mac_util.h" +#include "base/sys_string_conversions.h" +#include "base/threading/thread_restrictions.h" +#include "skia/ext/skia_utils_mac.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebImage.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenu.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webcursor.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/plugins/npapi/plugin_list.h" +#include "webkit/plugins/npapi/webplugin_delegate_impl.h" +#include "webkit/glue/webmenurunner_mac.h" + +using webkit::npapi::WebPluginDelegateImpl; +using WebKit::WebContextMenuData; +using WebKit::WebCursorInfo; +using WebKit::WebDragData; +using WebKit::WebDragOperationsMask; +using WebKit::WebExternalPopupMenu; +using WebKit::WebExternalPopupMenuClient; +using WebKit::WebImage; +using WebKit::WebNavigationPolicy; +using WebKit::WebPoint; +using WebKit::WebPopupMenuInfo; +using WebKit::WebRect; +using WebKit::WebWidget; + + +namespace { + +void AddMenuItem(CefRefPtr browser, + CefRefPtr handler, + NSMenu* menu, + id target, + cef_menu_id_t menuId, + const std::string& label, + bool enabled) { + std::string disp_str; + if (handler.get()) { + // Let the handler change the label if desired. + CefString actual_label(label); + handler->GetMenuLabel(browser, menuId, actual_label); + disp_str = actual_label; + } else { + disp_str = label; + } + + NSString* str = base::SysUTF8ToNSString(disp_str); + NSMenuItem* item = + [[[NSMenuItem alloc] initWithTitle:str + action:enabled?@selector(menuItemSelected:):nil + keyEquivalent:@""] autorelease]; + [item setTarget:target]; + [item setTag:menuId]; + [menu addItem:item]; +} + +void AddMenuSeparator(NSMenu* menu) { + NSMenuItem* item = [NSMenuItem separatorItem]; + [menu addItem:item]; +} + +} // namespace + +@interface BrowserMenuDelegate : NSObject { + @private + CefRefPtr browser_; +} + +- (id)initWithBrowser:(CefBrowserImpl*)browser; +- (void)menuItemSelected:(id)sender; +@end + +@implementation BrowserMenuDelegate + +- (id)initWithBrowser:(CefBrowserImpl*)browser { + self = [super init]; + if (self) + browser_ = browser; + return self; + +} + +// Called when a context menu item is selected by the user. +- (void)menuItemSelected:(id)sender { + cef_menu_id_t menuId = static_cast([sender tag]); + bool handled = false; + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetMenuHandler(); + if (handler.get()) { + // Ask the handler if it wants to handle the action. + handled = handler->OnMenuAction(browser_.get(), menuId); + } + } + + if(!handled) { + // Execute the action. + browser_->UIT_HandleAction(menuId, browser_->GetFocusedFrame()); + } +} + +@end + +// WebViewClient -------------------------------------------------------------- + +WebExternalPopupMenu* BrowserWebViewDelegate::createExternalPopupMenu( + const WebPopupMenuInfo& info, + WebExternalPopupMenuClient* client) { + DCHECK(!external_popup_menu_.get()); + external_popup_menu_.reset(new ExternalPopupMenu(this, info, client)); + return external_popup_menu_.get(); +} + +void BrowserWebViewDelegate::ClosePopupMenu() { + if (external_popup_menu_ == NULL) { + NOTREACHED(); + return; + } + external_popup_menu_.reset(); +} + +void BrowserWebViewDelegate::showContextMenu( + WebKit::WebFrame* frame, const WebKit::WebContextMenuData& data) { + WebWidgetHost* host = GetWidgetHost(); + if (!host) + return; + + NSView *view = browser_->UIT_GetMainWndHandle(); + if (!view) + return; + + NSWindow* window = [view window]; + + int screenX = -1; + int screenY = -1; + NSPoint mouse_pt = {data.mousePosition.x, data.mousePosition.y}; + if (!browser_->IsWindowRenderingDisabled()) { + mouse_pt = [window mouseLocationOutsideOfEventStream]; + NSPoint screen_pt = [window convertBaseToScreen:mouse_pt]; + screenX = screen_pt.x; + screenY = screen_pt.y; + } + + int edit_flags = 0; + int type_flags = 0; + NSMenu* menu = nil; + + // Make sure events can be pumped while the menu is up. + MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); + + // Give the client a chance to handle the menu. + if (OnBeforeMenu(data, mouse_pt.x, mouse_pt.y, edit_flags, type_flags)) + return; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetMenuHandler(); + + if (client.get() && browser_->IsWindowRenderingDisabled()) { + // Retrieve the screen coordinates. + CefRefPtr render_handler = client->GetRenderHandler(); + if (!render_handler.get() || + !render_handler->GetScreenPoint(browser_, mouse_pt.x, mouse_pt.y, + screenX, screenY)) { + return; + } + } + + BrowserMenuDelegate* delegate = + [[[BrowserMenuDelegate alloc] initWithBrowser:browser_] autorelease]; + + // Build the correct default context menu + if (type_flags & MENUTYPE_EDITABLE) { + menu = [[[NSMenu alloc] initWithTitle:@""] autorelease]; + + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_UNDO, "Undo", + !!(edit_flags & MENU_CAN_UNDO)); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_REDO, "Redo", + !!(edit_flags & MENU_CAN_REDO)); + AddMenuSeparator(menu); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_CUT, "Cut", + !!(edit_flags & MENU_CAN_CUT)); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_COPY, "Copy", + !!(edit_flags & MENU_CAN_COPY)); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_PASTE, "Paste", + !!(edit_flags & MENU_CAN_PASTE)); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_DELETE, "Delete", + !!(edit_flags & MENU_CAN_DELETE)); + AddMenuSeparator(menu); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_SELECTALL, + "Select All", !!(edit_flags & MENU_CAN_SELECT_ALL)); + } else if(type_flags & MENUTYPE_SELECTION) { + menu = [[[NSMenu alloc] initWithTitle:@""] autorelease]; + + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_COPY, "Copy", + !!(edit_flags & MENU_CAN_COPY)); + } else if(type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) { + menu = [[[NSMenu alloc] initWithTitle:@""] autorelease]; + + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_NAV_BACK, "Back", + !!(edit_flags & MENU_CAN_GO_BACK)); + AddMenuItem(browser_, handler, menu, delegate, MENU_ID_NAV_FORWARD, + "Forward", !!(edit_flags & MENU_CAN_GO_FORWARD)); + // TODO(port): Enable the below menu items when supported. + //AddMenuSeparator(menu); + //AddMenuItem(browser_, handler, menu, delegate, MENU_ID_PRINT, "Print", + // true); + //AddMenuItem(browser_, handler, menu, delegate, MENU_ID_VIEWSOURCE, + // "View Source", true); + } + + if (!menu) + return; + + // Synthesize an event for the click, as there is no certainty that + // [NSApp currentEvent] will return a valid event. + NSPoint screen_pt = {screenX, screenY}; + NSPoint window_pt = [window convertScreenToBase:screen_pt]; + + NSEvent* currentEvent = [NSApp currentEvent]; + NSTimeInterval eventTime = [currentEvent timestamp]; + NSEvent* clickEvent = [NSEvent mouseEventWithType:NSRightMouseDown + location:window_pt + modifierFlags:NSRightMouseDownMask + timestamp:eventTime + windowNumber:[window windowNumber] + context:nil + eventNumber:0 + clickCount:1 + pressure:1.0]; + + + // Menu selection events go to the BrowserMenuDelegate. + [menu setDelegate:delegate]; + + // Show the menu. + [NSMenu popUpContextMenu:menu + withEvent:clickEvent + forView:view]; +} + +// WebWidgetClient ------------------------------------------------------------ + +void BrowserWebViewDelegate::show(WebNavigationPolicy policy) { + DCHECK(this != browser_->UIT_GetPopupDelegate()); +} + +void BrowserWebViewDelegate::didChangeCursor(const WebCursorInfo& cursor_info) { + NSCursor* ns_cursor = WebCursor(cursor_info).GetNativeCursor(); + + if (!browser_->IsWindowRenderingDisabled()) { + [ns_cursor set]; + } else { + // Notify the handler of cursor change. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) + handler->OnCursorChange(browser_, ns_cursor); + } + } +} + +WebRect BrowserWebViewDelegate::windowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + if (!browser_->IsWindowRenderingDisabled()) { + NSView *view = host->view_handle(); + NSRect rect = [view frame]; + return gfx::Rect(NSRectToCGRect(rect)); + } else { + // Retrieve the view rectangle from the handler. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) { + CefRect rect(0, 0, 0, 0); + if (handler->GetViewRect(browser_, rect)) + return WebRect(rect.x, rect.y, rect.width, rect.height); + } + } + } + } + return WebRect(); +} + +void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { + if (this == browser_->UIT_GetWebViewDelegate()) { + // TODO(port): Set the window rectangle. + } else if (this == browser_->UIT_GetPopupDelegate()) { + NOTREACHED(); + } +} + +WebRect BrowserWebViewDelegate::rootWindowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + NSView *view = host->view_handle(); + NSRect rect = [[[view window] contentView] frame]; + return gfx::Rect(NSRectToCGRect(rect)); + } + return WebRect(); +} + +@interface NSWindow(OSInternals) +- (NSRect)_growBoxRect; +@end + +WebRect BrowserWebViewDelegate::windowResizerRect() { + NSRect resize_rect = NSMakeRect(0, 0, 0, 0); + WebWidgetHost* host = GetWidgetHost(); + if (host) { + NSView *view = host->view_handle(); + NSWindow* window = [view window]; + if (window == nil) + return gfx::Rect(); + + resize_rect = [window _growBoxRect]; + // The scrollbar assumes that the resizer goes all the way down to the + // bottom corner, so we ignore any y offset to the rect itself and use the + // entire bottom corner. + resize_rect.origin.y = 0; + // Convert to view coordinates from window coordinates. + resize_rect = [view convertRect:resize_rect fromView:nil]; + // Flip the rect in view coordinates + resize_rect.origin.y = + [view frame].size.height - resize_rect.origin.y - + resize_rect.size.height; + } + return gfx::Rect(NSRectToCGRect(resize_rect)); +} + +void BrowserWebViewDelegate::startDragging( + WebKit::WebFrame* frame, + const WebDragData& data, + WebDragOperationsMask mask, + const WebImage& image, + const WebPoint& image_offset) { + if (browser_->settings().drag_drop_disabled || + browser_->IsWindowRenderingDisabled()) { + browser_->UIT_GetWebView()->dragSourceSystemDragEnded(); + return; + } + + WebWidgetHost* host = GetWidgetHost(); + if (!host) + return; + + BrowserWebView *view = static_cast(host->view_handle()); + if (!view) + return; + + WebDropData drop_data(data); + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDragHandler(); + if (handler.get()) { + CefRefPtr data(new CefDragDataImpl(drop_data)); + if (handler->OnDragStart(browser_, data, + static_cast(mask))) { + browser_->UIT_GetWebView()->dragSourceSystemDragEnded(); + return; + } + } + } + + // By allowing nested tasks, the code below also allows Close(), + // which would deallocate |this|. The same problem can occur while + // processing -sendEvent:, so Close() is deferred in that case. + // Drags from web content do not come via -sendEvent:, this sets the + // same flag -sendEvent: would. + CefScopedSendingEvent sendingEventScoper; + + // The drag invokes a nested event loop, arrange to continue + // processing events. + MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); + + NSImage* ns_image = nil; + if (!image.isNull()) { + const SkBitmap& bitmap = image.getSkBitmap(); + CGColorSpaceRef color_space = base::mac::GetSystemColorSpace(); + ns_image = gfx::SkBitmapToNSImageWithColorSpace(bitmap, color_space); + } + NSPoint offset = NSPointFromCGPoint(gfx::Point(image_offset).ToCGPoint()); + + // Keep a reference to the NSView so that it won't be destroyed until after + // the drag operation has completed. + [view retain]; + + [view startDragWithDropData:drop_data + dragOperationMask:static_cast(mask) + image:ns_image + offset:offset]; + + [view release]; +} + +void BrowserWebViewDelegate::runModal() { + NOTIMPLEMENTED(); +} + +// WebPluginPageDelegate ------------------------------------------------------ + +webkit::npapi::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( + const FilePath& path, + const std::string& mime_type) { + WebWidgetHost *host = GetWidgetHost(); + if (!host) + return NULL; + + gfx::PluginWindowHandle containing_view = 0; + WebPluginDelegateImpl* delegate = WebPluginDelegateImpl::Create( + path, mime_type, containing_view); + if (delegate) + delegate->SetNoBufferContext(); + return delegate; +} + +void BrowserWebViewDelegate::CreatedPluginWindow( + gfx::PluginWindowHandle handle) { + if (browser_->IsWindowRenderingDisabled()) { + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (host) + host->AddWindowedPlugin(handle); + } +} + +void BrowserWebViewDelegate::WillDestroyPluginWindow( + gfx::PluginWindowHandle handle) { + if (browser_->IsWindowRenderingDisabled()) { + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (host) + host->RemoveWindowedPlugin(handle); + } +} + +void BrowserWebViewDelegate::DidMovePlugin( + const webkit::npapi::WebPluginGeometry& move) { + if (browser_->IsWindowRenderingDisabled()) { + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (host) { + host->MoveWindowedPlugin(move); + } + } +} + +// Protected methods ---------------------------------------------------------- + +void BrowserWebViewDelegate::ShowJavaScriptAlert( + WebKit::WebFrame* webframe, const CefString& message) { + std::string messageStr(message); + NSString *text = [NSString stringWithUTF8String:messageStr.c_str()]; + NSAlert *alert = [NSAlert alertWithMessageText:@"JavaScript Alert" + defaultButton:@"OK" + alternateButton:nil + otherButton:nil + informativeTextWithFormat:text]; + [alert runModal]; +} + +bool BrowserWebViewDelegate::ShowJavaScriptConfirm( + WebKit::WebFrame* webframe, const CefString& message) { + NOTIMPLEMENTED(); + return false; +} + +bool BrowserWebViewDelegate::ShowJavaScriptPrompt( + WebKit::WebFrame* webframe, const CefString& message, + const CefString& default_value, CefString* result) { + NOTIMPLEMENTED(); + return false; +} + +// Called to show the file chooser dialog. +bool BrowserWebViewDelegate::ShowFileChooser(std::vector& file_names, + const bool multi_select, + const WebKit::WebString& title, + const FilePath& default_file) { + NSOpenPanel* dialog = [NSOpenPanel openPanel]; + if (!title.isNull()) + [dialog setTitle:base::SysUTF16ToNSString(title)]; + + NSString* default_dir = nil; + NSString* default_filename = nil; + if (!default_file.empty()) { + // The file dialog is going to do a ton of stats anyway. Not much + // point in eliminating this one. + base::ThreadRestrictions::ScopedAllowIO allow_io; + if (file_util::DirectoryExists(default_file)) { + default_dir = base::SysUTF8ToNSString(default_file.value()); + } else { + default_dir = base::SysUTF8ToNSString(default_file.DirName().value()); + default_filename = + base::SysUTF8ToNSString(default_file.BaseName().value()); + } + } + + [dialog setAllowsOtherFileTypes:YES]; + [dialog setAllowsMultipleSelection:multi_select]; + [dialog setCanChooseFiles:YES]; + [dialog setCanChooseDirectories:NO]; + + NSInteger result = [dialog runModalForDirectory:default_dir + file:default_filename]; + if (result == NSFileHandlingPanelCancelButton) + return false; + + NSArray *urls = [dialog URLs]; + int i, count = [urls count]; + for (i=0; i +#include +#include + +#include "libcef/browser_drag_delegate_win.h" +#include "libcef/browser_navigation_controller.h" +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/drag_data_impl.h" +#include "libcef/web_drop_target_win.h" + +#include "base/message_loop.h" +#include "base/string_util.h" +#include "net/base/net_errors.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebCursorInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebImage.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/gfx/gdi_util.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/point.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/glue/window_open_disposition.h" +#include "webkit/plugins/npapi/plugin_list.h" +#include "webkit/plugins/npapi/webplugin.h" +#include "webkit/plugins/npapi/webplugin_delegate_impl.h" + +using webkit::npapi::WebPluginDelegateImpl; +using WebKit::WebContextMenuData; +using WebKit::WebCursorInfo; +using WebKit::WebDragData; +using WebKit::WebDragOperationsMask; +using WebKit::WebExternalPopupMenu; +using WebKit::WebExternalPopupMenuClient; +using WebKit::WebFrame; +using WebKit::WebImage; +using WebKit::WebNavigationPolicy; +using WebKit::WebPoint; +using WebKit::WebPopupMenuInfo; +using WebKit::WebRect; +using WebKit::WebWidget; + +namespace { + +static const wchar_t kPluginWindowClassName[] = L"WebPluginHost"; + +void AddMenuItem(CefRefPtr browser, + CefRefPtr handler, + HMENU menu, + cef_menu_id_t menuId, + const wchar_t* label, + bool enabled, + std::list& label_list) { + CefString actual_label(label); + if (handler.get()) { + // Let the handler change the label if desired, + handler->GetMenuLabel(browser, menuId, actual_label); + } + + // Store the label in a list to simplify memory management. + label_list.push_back(actual_label); + + MENUITEMINFO mii; + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_FTYPE | MIIM_ID | MIIM_STRING; + mii.fType = MFT_STRING; + if (!enabled) { + mii.fMask |= MIIM_STATE; + mii.fState = MFS_GRAYED; + } + mii.wID = menuId; + mii.dwTypeData = const_cast(label_list.back().c_str()); + + InsertMenuItem(menu, -1, TRUE, &mii); +} + +void AddMenuSeparator(HMENU menu) { + MENUITEMINFO mii; + mii.cbSize = sizeof(mii); + mii.fMask = MIIM_FTYPE; + mii.fType = MFT_SEPARATOR; + + InsertMenuItem(menu, -1, TRUE, &mii); +} + +} // namespace + +// WebViewClient -------------------------------------------------------------- + +WebExternalPopupMenu* BrowserWebViewDelegate::createExternalPopupMenu( + const WebPopupMenuInfo& info, + WebExternalPopupMenuClient* client) { + NOTREACHED(); + return NULL; +} + +// WebWidgetClient ------------------------------------------------------------ + +void BrowserWebViewDelegate::show(WebNavigationPolicy) { + if (this == browser_->UIT_GetWebViewDelegate()) { + if (!browser_->IsWindowRenderingDisabled()) { + // Restore the window and bring it to the top if the window is currently + // visible. + HWND root = GetAncestor(browser_->UIT_GetMainWndHandle(), GA_ROOT); + if (IsWindowVisible(root)) { + ShowWindow(root, SW_SHOWNORMAL); + SetWindowPos(root, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); + } + } + } else if (this == browser_->UIT_GetPopupDelegate()) { + if (!browser_->IsWindowRenderingDisabled()) { + // Show popup widgets without activation. + ShowWindow(browser_->UIT_GetPopupWndHandle(), SW_SHOWNA); + } else { + // Notify the handler of popup visibility change. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) + handler->OnPopupShow(browser_, true); + } + } + } +} + +void BrowserWebViewDelegate::didChangeCursor(const WebCursorInfo& cursor_info) { + if (WebWidgetHost* host = GetWidgetHost()) { + current_cursor_.InitFromCursorInfo(cursor_info); + HMODULE hModule = ::GetModuleHandle(L"libcef.dll"); + if (!hModule) + hModule = ::GetModuleHandle(NULL); + HCURSOR hCursor = current_cursor_.GetCursor(hModule); + + if (!browser_->IsWindowRenderingDisabled()) { + host->SetCursor(hCursor); + } else { + // Notify the handler of cursor change. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) + handler->OnCursorChange(browser_, hCursor); + } + } + } +} + +WebRect BrowserWebViewDelegate::windowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + if (!browser_->IsWindowRenderingDisabled()) { + RECT rect; + ::GetWindowRect(host->view_handle(), &rect); + return gfx::Rect(rect); + } else { + // Retrieve the view rectangle from the handler. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) { + CefRect rect(0, 0, 0, 0); + if (handler->GetViewRect(browser_, rect)) + return WebRect(rect.x, rect.y, rect.width, rect.height); + } + } + } + } + return WebRect(); +} + +void BrowserWebViewDelegate::setWindowRect(const WebRect& rect) { + if (this == browser_->UIT_GetWebViewDelegate()) { + // ignored + } else if (this == browser_->UIT_GetPopupDelegate()) { + if (!browser_->IsWindowRenderingDisabled()) { + MoveWindow(browser_->UIT_GetPopupWndHandle(), rect.x, rect.y, rect.width, + rect.height, FALSE); + } else { + browser_->set_popup_rect(rect); + browser_->UIT_GetPopupHost()->SetSize(rect.width, rect.height); + + // Notify the handler of popup size change. + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRenderHandler(); + if (handler.get()) { + handler->OnPopupSize(browser_, + CefRect(rect.x, rect.y, rect.width, rect.height)); + } + } + } + } +} + +WebRect BrowserWebViewDelegate::rootWindowRect() { + if (WebWidgetHost* host = GetWidgetHost()) { + RECT rect; + HWND root_window = ::GetAncestor(host->view_handle(), GA_ROOT); + ::GetWindowRect(root_window, &rect); + return gfx::Rect(rect); + } + return WebRect(); +} + +WebRect BrowserWebViewDelegate::windowResizerRect() { + // Not necessary on Windows. + return WebRect(); +} + +void BrowserWebViewDelegate::startDragging( + WebFrame* frame, + const WebDragData& data, + WebDragOperationsMask mask, + const WebImage& image, + const WebPoint& image_offset) { + // Dragging is not supported when window rendering is disabled. + if (browser_->settings().drag_drop_disabled || + browser_->IsWindowRenderingDisabled()) { + EndDragging(); + return; + } + + WebDropData drop_data(data); + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDragHandler(); + if (handler.get()) { + CefRefPtr data(new CefDragDataImpl(drop_data)); + if (handler->OnDragStart(browser_, data, + static_cast(mask))) { + EndDragging(); + return; + } + } + } + + drag_delegate_ = new BrowserDragDelegate(this); + drag_delegate_->StartDragging(drop_data, mask, image.getSkBitmap(), + image_offset); +} + +void BrowserWebViewDelegate::runModal() { + WebWidgetHost* host = GetWidgetHost(); + if (!host) + return; + + show(WebKit::WebNavigationPolicyNewWindow); + + browser_->UIT_SetIsModal(true); + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + + if (client.get()) + handler = client->GetLifeSpanHandler(); + + bool handled(false); + + if (handler.get()) { + // Let the client override the modal message loop. + handled = handler->RunModal(browser_); + } + + if (!handled) { + HWND child = ::GetAncestor(browser_->UIT_GetMainWndHandle(), GA_ROOT); + HWND owner = ::GetAncestor(browser_->opener_window(), GA_ROOT); + + if (child && owner) { + // Set the owner so that Windows keeps this window above the owner. + ::SetWindowLong(child, GWL_HWNDPARENT, (LONG)owner); + // Disable the owner if it is enabled so that you can't interact with it. + // while this child window is open. + if (::IsWindowEnabled(owner)) { + ::EnableWindow(owner, FALSE); + browser_->set_opener_was_disabled_by_modal_loop(true); + } + DWORD dwStyle = ::GetWindowLong(child, GWL_STYLE); + DWORD dwNewStyle = dwStyle | WS_POPUP; + if (dwStyle != dwNewStyle) + ::SetWindowLong(child, GWL_STYLE, dwNewStyle); + } + + // Tell the browser to exit this message loop when this window closes. + browser_->set_internal_modal_message_loop_is_active(true); + + // Start a new message loop here and return when this window closes. + MessageLoop* message_loop = MessageLoop::current(); + bool old_state = message_loop->NestableTasksAllowed(); + message_loop->SetNestableTasksAllowed(true); + message_loop->Run(); + message_loop->SetNestableTasksAllowed(old_state); + } +} + +// WebPluginPageDelegate ------------------------------------------------------ + +webkit::npapi::WebPluginDelegate* BrowserWebViewDelegate::CreatePluginDelegate( + const FilePath& file_path, + const std::string& mime_type) { + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (!host) + return NULL; + + HWND hwnd; + + if (!browser_->IsWindowRenderingDisabled()) { + // Parent the plugin container to the existing browser window. + hwnd = browser_->UIT_GetWebViewHost()->view_handle(); + DCHECK(hwnd != NULL); + } else { + // Parent the plugin container to the main window handle provided by the + // user. + hwnd = browser_->UIT_GetMainWndHandle(); + DCHECK(hwnd != NULL); + } + + return WebPluginDelegateImpl::Create(file_path, mime_type, hwnd); +} + +void BrowserWebViewDelegate::CreatedPluginWindow( + gfx::PluginWindowHandle handle) { + if (browser_->IsWindowRenderingDisabled()) { + static bool registered_class = false; + if (!registered_class) { + WNDCLASSEX wcex = {0}; + wcex.cbSize = sizeof(wcex); + wcex.style = CS_DBLCLKS; + wcex.lpfnWndProc = DefWindowProc; + wcex.hInstance = GetModuleHandle(NULL); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.lpszClassName = kPluginWindowClassName; + RegisterClassEx(&wcex); + registered_class = true; + } + + // Parent windowed plugin containers to a hidden window. + HWND parent = CreateWindow(kPluginWindowClassName, NULL, + WS_OVERLAPPED|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, + 0, 0, 0, 0, NULL, NULL, + GetModuleHandle(NULL), NULL); + DCHECK(parent != NULL); + SetParent(handle, parent); + + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (host) + host->AddWindowedPlugin(handle); + } +} + +void BrowserWebViewDelegate::WillDestroyPluginWindow( + gfx::PluginWindowHandle handle) { + if (browser_->IsWindowRenderingDisabled()) { + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (host) + host->RemoveWindowedPlugin(handle); + + // Destroy the hidden parent window. + DestroyWindow(GetParent(handle)); + } +} + +void BrowserWebViewDelegate::DidMovePlugin( + const webkit::npapi::WebPluginGeometry& move) { + UINT flags = 0; + + if (move.rects_valid) { + HRGN hrgn = ::CreateRectRgn(move.clip_rect.x(), + move.clip_rect.y(), + move.clip_rect.right(), + move.clip_rect.bottom()); + gfx::SubtractRectanglesFromRegion(hrgn, move.cutout_rects); + + // Note: System will own the hrgn after we call SetWindowRgn, + // so we don't need to call DeleteObject(hrgn) + ::SetWindowRgn(move.window, hrgn, FALSE); + } else { + flags |= (SWP_NOSIZE | SWP_NOMOVE); + } + + if (move.visible) + flags |= SWP_SHOWWINDOW; + else + flags |= SWP_HIDEWINDOW; + + ::SetWindowPos(move.window, + NULL, + move.window_rect.x(), + move.window_rect.y(), + move.window_rect.width(), + move.window_rect.height(), + flags); + + if (browser_->IsWindowRenderingDisabled()) { + WebViewHost* host = browser_->UIT_GetWebViewHost(); + if (host) { + host->MoveWindowedPlugin(move); + } + } +} + +void BrowserWebViewDelegate::showContextMenu( + WebFrame* frame, const WebContextMenuData& data) { + int screenX = -1, screenY = -1; + + POINT mouse_pt = {data.mousePosition.x, data.mousePosition.y}; + if (!browser_->IsWindowRenderingDisabled()) { + // Perform the conversion to screen coordinates only if window rendering is + // enabled. + MapWindowPoints(browser_->UIT_GetWebViewWndHandle(), HWND_DESKTOP, + &mouse_pt, 1); + screenX = mouse_pt.x; + screenY = mouse_pt.y; + } + + int edit_flags = 0; + int type_flags = 0; + HMENU menu = NULL; + std::list label_list; + + // Make sure events can be pumped while the menu is up. + MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current()); + + // Give the client a chance to handle the menu. + if (OnBeforeMenu(data, mouse_pt.x, mouse_pt.y, edit_flags, type_flags)) + return; + + CefRefPtr client = browser_->GetClient(); + CefRefPtr handler; + if (client.get()) + handler = client->GetMenuHandler(); + + if (client.get() && browser_->IsWindowRenderingDisabled()) { + // Retrieve the screen coordinates. + CefRefPtr render_handler = client->GetRenderHandler(); + if (!render_handler.get() || + !render_handler->GetScreenPoint(browser_, mouse_pt.x, mouse_pt.y, + screenX, screenY)) { + return; + } + } + + // Build the correct default context menu + if (type_flags & MENUTYPE_EDITABLE) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, handler, menu, MENU_ID_UNDO, L"Undo", + !!(edit_flags & MENU_CAN_UNDO), label_list); + AddMenuItem(browser_, handler, menu, MENU_ID_REDO, L"Redo", + !!(edit_flags & MENU_CAN_REDO), label_list); + AddMenuSeparator(menu); + AddMenuItem(browser_, handler, menu, MENU_ID_CUT, L"Cut", + !!(edit_flags & MENU_CAN_CUT), label_list); + AddMenuItem(browser_, handler, menu, MENU_ID_COPY, L"Copy", + !!(edit_flags & MENU_CAN_COPY), label_list); + AddMenuItem(browser_, handler, menu, MENU_ID_PASTE, L"Paste", + !!(edit_flags & MENU_CAN_PASTE), label_list); + AddMenuItem(browser_, handler, menu, MENU_ID_DELETE, L"Delete", + !!(edit_flags & MENU_CAN_DELETE), label_list); + AddMenuSeparator(menu); + AddMenuItem(browser_, handler, menu, MENU_ID_SELECTALL, L"Select All", + !!(edit_flags & MENU_CAN_SELECT_ALL), label_list); + } else if (type_flags & MENUTYPE_SELECTION) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, handler, menu, MENU_ID_COPY, L"Copy", + !!(edit_flags & MENU_CAN_COPY), label_list); + } else if (type_flags & (MENUTYPE_PAGE | MENUTYPE_FRAME)) { + menu = CreatePopupMenu(); + AddMenuItem(browser_, handler, menu, MENU_ID_NAV_BACK, L"Back", + !!(edit_flags & MENU_CAN_GO_BACK), label_list); + AddMenuItem(browser_, handler, menu, MENU_ID_NAV_FORWARD, L"Forward", + !!(edit_flags & MENU_CAN_GO_FORWARD), label_list); + AddMenuSeparator(menu); + AddMenuItem(browser_, handler, menu, MENU_ID_PRINT, L"Print", + true, label_list); + AddMenuItem(browser_, handler, menu, MENU_ID_VIEWSOURCE, L"View Source", + true, label_list); + } + + if (!menu) + return; + + // Show the context menu + int selected_id = TrackPopupMenu(menu, + TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD | TPM_RECURSE, + screenX, screenY, 0, browser_->UIT_GetMainWndHandle(), NULL); + + if (selected_id != 0) { + // An action was chosen + cef_menu_id_t menuId = static_cast(selected_id); + bool handled = false; + if (handler.get()) { + // Ask the handler if it wants to handle the action + handled = handler->OnMenuAction(browser_, menuId); + } + + if (!handled) { + // Execute the action + browser_->UIT_HandleAction(menuId, browser_->GetFocusedFrame()); + } + } + + DestroyMenu(menu); +} + +// Private methods ------------------------------------------------------------ + +void BrowserWebViewDelegate::RegisterDragDrop() { + DCHECK(!drop_target_); + drop_target_ = new WebDropTarget(browser_); +} + +void BrowserWebViewDelegate::RevokeDragDrop() { + if (drop_target_.get()) + ::RevokeDragDrop(browser_->UIT_GetWebViewWndHandle()); +} + +void BrowserWebViewDelegate::EndDragging() { + if (browser_->UIT_GetWebView()) + browser_->UIT_GetWebView()->dragSourceSystemDragEnded(); + drag_delegate_ = NULL; + + if (destroy_on_drag_end_) + browser_->UIT_DestroyBrowser(); +} + +void BrowserWebViewDelegate::ShowJavaScriptAlert(WebFrame* webframe, + const CefString& message) { + // TODO(cef): Think about what we should be showing as the prompt caption + std::wstring messageStr = message; + std::wstring titleStr = browser_->UIT_GetTitle(); + MessageBox(browser_->UIT_GetMainWndHandle(), messageStr.c_str(), + titleStr.c_str(), MB_OK | MB_ICONWARNING); +} + +bool BrowserWebViewDelegate::ShowJavaScriptConfirm(WebFrame* webframe, + const CefString& message) { + // TODO(cef): Think about what we should be showing as the prompt caption + std::wstring messageStr = message; + std::wstring titleStr = browser_->UIT_GetTitle(); + int rv = MessageBox(browser_->UIT_GetMainWndHandle(), messageStr.c_str(), + titleStr.c_str(), MB_YESNO | MB_ICONQUESTION); + return (rv == IDYES); +} + +bool BrowserWebViewDelegate::ShowJavaScriptPrompt(WebFrame* webframe, + const CefString& message, + const CefString& default_value, + CefString* result) { + // TODO(cef): Implement a default prompt dialog + return false; +} + +namespace { + +// from chrome/browser/views/shell_dialogs_win.cc + +bool RunOpenFileDialog(const std::wstring& filter, HWND owner, 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]; + base::wcslcpy(filename, path->value().c_str(), arraysize(filename)); + + ofn.lpstrFile = filename; + ofn.nMaxFile = MAX_PATH; + + // 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; + + if (!filter.empty()) { + ofn.lpstrFilter = filter.c_str(); + } + bool success = !!GetOpenFileName(&ofn); + if (success) + *path = FilePath(filename); + return success; +} + +bool RunOpenMultiFileDialog(const std::wstring& filter, HWND owner, + 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_array filename(new wchar_t[UNICODE_STRING_MAX_CHARS]); + filename[0] = 0; + + ofn.lpstrFile = filename.get(); + ofn.nMaxFile = UNICODE_STRING_MAX_CHARS; + + // 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_HIDEREADONLY | OFN_ALLOWMULTISELECT; + + if (!filter.empty()) { + ofn.lpstrFilter = filter.c_str(); + } + 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(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)); + } + } + } + return success; +} + +} // namespace + +bool BrowserWebViewDelegate::ShowFileChooser(std::vector& file_names, + const bool multi_select, + const WebKit::WebString& title, + const FilePath& default_file) { + bool result = false; + + if (multi_select) { + result = RunOpenMultiFileDialog(L"", browser_->UIT_GetMainWndHandle(), + &file_names); + } else { + FilePath file_name; + result = RunOpenFileDialog(L"", browser_->UIT_GetMainWndHandle(), + &file_name); + if (result) + file_names.push_back(file_name); + } + + return result; +} + diff --git a/cef1/libcef/browser_webview_mac.h b/cef1/libcef/browser_webview_mac.h new file mode 100644 index 000000000..c219620dc --- /dev/null +++ b/cef1/libcef/browser_webview_mac.h @@ -0,0 +1,97 @@ +// Copyright (c) 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. + +#ifndef CEF_LIBCEF_BROWSER_WEBVIEW_MAC_H_ +#define CEF_LIBCEF_BROWSER_WEBVIEW_MAC_H_ +#pragma once + +#import +#import "base/mac/cocoa_protocols.h" +#include "base/string16.h" +#include "base/memory/scoped_nsobject.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositionUnderline.h" +#include + +class CefBrowserImpl; +@class WebDragSource; +@class WebDropTarget; +struct WebDropData; + +// A view to wrap the WebCore view and help it live in a Cocoa world. The +// (rough) equivalent of Apple's WebView. + +@interface BrowserWebView : NSView { + @private + CefBrowserImpl* browser_; // weak + NSTrackingArea* trackingArea_; + bool is_in_setfocus_; + + scoped_nsobject dragSource_; + scoped_nsobject dropTarget_; + + // Represents the input-method attributes supported by this object. + 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 if unmarkText is called or not when handling a keyboard + // event. + BOOL unmarkTextCalled_; + + // The range of current marked text inside the whole content of the DOM node + // being edited. + // TODO(suzhe): This is currently a fake value, as we do not support accessing + // the whole content yet. + NSRange markedRange_; + + // 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. + string16 textToBeInserted_; + + // Marked text which was generated by handling a key down event. + string16 markedText_; + + // Underline information of the |markedText_|. + std::vector underlines_; +} + +- (void)mouseDown:(NSEvent *)theEvent; +- (void)rightMouseDown:(NSEvent *)theEvent; +- (void)otherMouseDown:(NSEvent *)theEvent; +- (void)mouseUp:(NSEvent *)theEvent; +- (void)rightMouseUp:(NSEvent *)theEvent; +- (void)otherMouseUp:(NSEvent *)theEvent; +- (void)mouseMoved:(NSEvent *)theEvent; +- (void)mouseDragged:(NSEvent *)theEvent; +- (void)scrollWheel:(NSEvent *)theEvent; +- (void)rightMouseDragged:(NSEvent *)theEvent; +- (void)otherMouseDragged:(NSEvent *)theEvent; +- (void)mouseEntered:(NSEvent *)theEvent; +- (void)mouseExited:(NSEvent *)theEvent; +- (void)keyDown:(NSEvent *)theEvent; +- (void)keyUp:(NSEvent *)theEvent; +- (BOOL)isOpaque; +- (void)setFrame:(NSRect)frameRect; + +// Register this WebView as a drag/drop target. +- (void)registerDragDrop; + +// Called from BrowserWebViewDelegate::startDragging() to initiate dragging. +- (void)startDragWithDropData:(const WebDropData&)dropData + dragOperationMask:(NSDragOperation)operationMask + image:(NSImage*)image + offset:(NSPoint)offset; + +@property (nonatomic, assign) CefBrowserImpl* browser; +@property (nonatomic, assign) bool in_setfocus; + +@end + +#endif // CEF_LIBCEF_BROWSER_WEBVIEW_MAC_H_ diff --git a/cef1/libcef/browser_webview_mac.mm b/cef1/libcef/browser_webview_mac.mm new file mode 100644 index 000000000..ec087e81b --- /dev/null +++ b/cef1/libcef/browser_webview_mac.mm @@ -0,0 +1,615 @@ +// Copyright (c) 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. + +#import + +#import "libcef/browser_webview_mac.h" +#import "libcef/browser_impl.h" +#import "libcef/cef_context.h" +#import "libcef/web_drag_source_mac.h" +#import "libcef/web_drop_target_mac.h" +#import "libcef/webwidget_host.h" + +#import "base/memory/scoped_ptr.h" +#import "base/string_util.h" +#import "base/sys_string_conversions.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebInputEventFactory.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebSubstringUtil.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#import "third_party/mozilla/NSPasteboard+Utils.h" +#import "third_party/skia/include/core/SkRegion.h" +#import "ui/gfx/rect.h" + +using WebKit::WebColor; +using WebKit::WebCompositionUnderline; +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebKeyboardEvent; +using WebKit::WebPoint; +using WebKit::WebRect; +using WebKit::WebString; +using WebKit::WebSubstringUtil; + +// This code is copied from +// content/browser/renderer_host/render_widget_host_mac +namespace { +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)]; + if (NSNumber *style = [attrs objectForKey:NSUnderlineStyleAttributeName]) { + WebColor color = SK_ColorBLACK; + if (NSColor *colorAttr = + [attrs objectForKey:NSUnderlineColorAttributeName]) { + color = WebColorFromNSColor( + [colorAttr colorUsingColorSpaceName:NSDeviceRGBColorSpace]); + } + underlines->push_back(WebCompositionUnderline( + range.location, NSMaxRange(range), color, [style intValue] > 1)); + } + i = range.location + range.length; + } +} +} // namespace + +@implementation BrowserWebView + +@synthesize browser = browser_; +@synthesize in_setfocus = is_in_setfocus_; + +- (id)initWithFrame:(NSRect)frame { + self = [super initWithFrame:frame]; + if (self) { + trackingArea_ = + [[NSTrackingArea alloc] initWithRect:frame + options:NSTrackingMouseMoved | + NSTrackingActiveInActiveApp | + NSTrackingInVisibleRect + owner:self + userInfo:nil]; + [self addTrackingArea:trackingArea_]; + } + return self; +} + +- (void) dealloc { + if (browser_) + browser_->UIT_DestroyBrowser(); + + [self removeTrackingArea:trackingArea_]; + [trackingArea_ release]; + + [super dealloc]; +} + +- (void)drawRect:(NSRect)rect { +#ifndef NDEBUG + CGContextRef context = reinterpret_cast( + [[NSGraphicsContext currentContext] graphicsPort]); + CGContextSetRGBFillColor(context, 1, 0, 1, 1); + CGContextFillRect(context, NSRectToCGRect(rect)); +#endif + + if (browser_ && browser_->UIT_GetWebView()) { + NSInteger count; + const NSRect *rects; + [self getRectsBeingDrawn:&rects count:&count]; + + SkRegion update_rgn; + for (int i = 0; i < count; i++) { + const NSRect r = rects[i]; + const float min_x = NSMinX(r); + const float max_x = NSMaxX(r); + const float min_y = NSHeight([self bounds]) - NSMaxY(r); + const float max_y = NSHeight([self bounds]) - NSMinY(r); + update_rgn.op(min_x, min_y, max_x, max_y, SkRegion::kUnion_Op); + } + + browser_->UIT_GetWebViewHost()->Paint(update_rgn); + } +} + +- (void)mouseDown:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)rightMouseDown:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)otherMouseDown:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)mouseUp:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)rightMouseUp:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)otherMouseUp:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)mouseMoved:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)mouseDragged:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)scrollWheel:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->WheelEvent(theEvent); +} + +- (void)rightMouseDragged:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)otherMouseDragged:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)mouseEntered:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +- (void)mouseExited:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->MouseEvent(theEvent); +} + +// This code is mostly copied and adapted from +// content/browser/renderer_host/render_widget_host_mac +- (void)keyDown:(NSEvent *)theEvent { + // Records the current marked text state, so that we can know if the marked + // text was deleted or not after handling the key down event. + BOOL oldHasMarkedText = hasMarkedText_; + + // We check if the marked text has one or less characters and a delete key is + // pressed. In such cases, we want to cancel IME composition and delete the + // marked character, so we dispatch the event directly to WebKit. + if (hasMarkedText_ && underlines_.size() <= 1) { + // Check for backspace or delete. + if ([theEvent keyCode] == 0x33 || [theEvent keyCode] == 0x75) + browser_->UIT_GetWebViewHost()->KeyEvent(theEvent); + } + + textToBeInserted_.clear(); + markedText_.clear(); + underlines_.clear(); + unmarkTextCalled_ = NO; + + handlingKeyDown_ = YES; + [self interpretKeyEvents:[NSArray arrayWithObject:theEvent]]; + handlingKeyDown_ = NO; + + // Only send a corresponding key press event if there is no marked text. + // We also handle keys like backspace or delete, where the length + // of the text to be inserted is 0. + if (!hasMarkedText_ && !oldHasMarkedText && + !textToBeInserted_.length() <= 1) { + if (textToBeInserted_.length() == 1) { + // If a single character was inserted, then we just send it as a keypress + // event. + WebKeyboardEvent keyboard_event( + WebInputEventFactory::keyboardEvent(theEvent)); + keyboard_event.type = WebInputEvent::Char; + keyboard_event.text[0] = textToBeInserted_[0]; + keyboard_event.text[1] = 0; + browser_->UIT_GetWebView()->handleInputEvent(keyboard_event); + } else { + browser_->UIT_GetWebViewHost()->KeyEvent(theEvent); + } + } + + // Calling KeyEvent() could have destroyed the widget. + // We perform a sanity check and return if the widget is NULL. + if (!browser_ || !browser_->UIT_GetWebView()) + return; + + BOOL textInserted = NO; + if (textToBeInserted_.length() > + ((hasMarkedText_ || oldHasMarkedText) ? 0u : 1u)) { + browser_->UIT_GetWebView()->confirmComposition(textToBeInserted_); + textInserted = YES; + } + + if (hasMarkedText_ && markedText_.length()) { + browser_->UIT_GetWebView()->setComposition(markedText_, underlines_, + selectedRange_.location, + NSMaxRange(selectedRange_)); + } else if (oldHasMarkedText && !hasMarkedText_ && !textInserted) { + if (unmarkTextCalled_) { + browser_->UIT_GetWebView()->confirmComposition(); + } else { + // Simulating a cancelComposition + browser_->UIT_GetWebView()->setComposition(EmptyString16(), underlines_, + 0, 0); + } + } +} + +- (void)keyUp:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->KeyEvent(theEvent); +} + +- (void)flagsChanged:(NSEvent *)theEvent { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebViewHost()->KeyEvent(theEvent); +} + +- (BOOL)isOpaque { + return YES; +} + +- (BOOL)canBecomeKeyView { + return browser_ && browser_->UIT_GetWebView(); +} + +- (BOOL)acceptsFirstResponder { + return browser_ && browser_->UIT_GetWebView(); +} + +- (BOOL)becomeFirstResponder { + if (browser_ && browser_->UIT_GetWebView()) { + if (!is_in_setfocus_) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetFocusHandler(); + if (handler.get() && + handler->OnSetFocus(browser_, FOCUS_SOURCE_SYSTEM)) { + return NO; + } + } + } + + browser_->UIT_GetWebViewHost()->SetFocus(YES); + return [super becomeFirstResponder]; + } + + return NO; +} + +- (BOOL)resignFirstResponder { + if (browser_ && browser_->UIT_GetWebView()) { + browser_->UIT_GetWebViewHost()->SetFocus(NO); + return [super resignFirstResponder]; + } + + return NO; +} + +- (void)setFrame:(NSRect)frameRect { + [super setFrame:frameRect]; + if (browser_ && browser_->UIT_GetWebView()) { + const NSRect bounds = [self bounds]; + browser_->UIT_GetWebViewHost()->Resize(gfx::Rect(NSRectToCGRect(bounds))); + } +} + +- (void)undo:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Undo(); +} + +- (void)redo:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Redo(); +} + +- (void)cut:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Cut(); +} + +- (void)copy:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Copy(); +} + +- (void)paste:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Paste(); +} + +- (void)delete:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Delete(); +} + +- (void)selectAll:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->SelectAll(); +} + +- (void)registerDragDrop { + dropTarget_.reset([[WebDropTarget alloc] initWithWebView:self]); + + // Register the view to handle the appropriate drag types. + NSArray* types = [NSArray arrayWithObjects:NSStringPboardType, + NSHTMLPboardType, NSURLPboardType, nil]; + [self registerForDraggedTypes:types]; +} + +- (void)startDragWithDropData:(const WebDropData&)dropData + dragOperationMask:(NSDragOperation)operationMask + image:(NSImage*)image + offset:(NSPoint)offset { + dragSource_.reset([[WebDragSource alloc] + initWithWebView:self + dropData:&dropData + image:image + offset:offset + pasteboard:[NSPasteboard pasteboardWithName:NSDragPboard] + dragOperationMask:operationMask]); + [dragSource_ startDrag]; +} + +// NSPasteboardOwner methods + +- (void)pasteboard:(NSPasteboard*)sender provideDataForType:(NSString*)type { + [dragSource_ lazyWriteToPasteboard:sender + forType:type]; +} + +// NSDraggingSource methods + +// Returns what kind of drag operations are available. This is a required +// method for NSDraggingSource. +- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal { + if (dragSource_.get()) + return [dragSource_ draggingSourceOperationMaskForLocal:isLocal]; + // No web drag source - this is the case for dragging a file from the + // downloads manager. Default to copy operation. Note: It is desirable to + // allow the user to either move or copy, but this requires additional + // plumbing to update the download item's path once its moved. + return NSDragOperationCopy; +} + +// Called when a drag initiated in our view ends. +- (void)draggedImage:(NSImage*)anImage + endedAt:(NSPoint)screenPoint + operation:(NSDragOperation)operation { + [dragSource_ endDragAt:screenPoint operation:operation]; + + // Might as well throw out this object now. + dragSource_.reset(); +} + +// Called when a drag initiated in our view moves. +- (void)draggedImage:(NSImage*)draggedImage movedTo:(NSPoint)screenPoint { + [dragSource_ moveDragTo:screenPoint]; +} + +// Called when we're informed where a file should be dropped. +- (NSArray*)namesOfPromisedFilesDroppedAtDestination:(NSURL*)dropDest { + if (![dropDest isFileURL]) + return nil; + + NSString* file_name = [dragSource_ dragPromisedFileTo:[dropDest path]]; + if (!file_name) + return nil; + + return [NSArray arrayWithObject:file_name]; +} + +// NSDraggingDestination methods + +- (NSDragOperation)draggingEntered:(id)sender { + return [dropTarget_ draggingEntered:sender view:self]; +} + +- (void)draggingExited:(id)sender { + [dropTarget_ draggingExited:sender]; +} + +- (NSDragOperation)draggingUpdated:(id)sender { + return [dropTarget_ draggingUpdated:sender view:self]; +} + +- (BOOL)performDragOperation:(id)sender { + return [dropTarget_ performDragOperation:sender view:self]; +} + +// NSTextInputClient methods + +// This code is mostly copied and adapted from +// content/browser/renderer_host/render_widget_host_mac +extern "C" { + extern NSString *NSTextInputReplacementRangeAttributeName; +} + +- (NSArray *)validAttributesForMarkedText { + if (!validAttributesForMarkedText_) { + validAttributesForMarkedText_.reset([[NSArray alloc] initWithObjects: + NSUnderlineStyleAttributeName, + NSUnderlineColorAttributeName, + NSMarkedClauseSegmentAttributeName, + NSTextInputReplacementRangeAttributeName, + nil]); + } + return validAttributesForMarkedText_.get(); +} + +- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint { + DCHECK([self window]); + // |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. + thePoint = [[self window] convertScreenToBase:thePoint]; + thePoint = [self convertPoint:thePoint fromView:nil]; + thePoint.y = NSHeight([self frame]) - thePoint.y; + + WebPoint point(thePoint.x, thePoint.y); + return (NSUInteger)browser_->UIT_GetWebView()->focusedFrame()-> + characterIndexForPoint(point); +} + +- (NSRect)firstRectForCharacterRange:(NSRange)theRange + actualRange:(NSRangePointer) actualRange { + if (actualRange) + *actualRange = theRange; + + if (!browser_ || !browser_->UIT_GetWebView() || + !browser_->UIT_GetWebView()->focusedFrame()) { + return NSMakeRect(0, 0, 0, 0); + } + + WebRect webRect; + browser_->UIT_GetWebView()->focusedFrame()->firstRectForCharacterRange( + theRange.location, theRange.length, webRect); + NSRect rect = NSMakeRect(webRect.x, webRect.y, webRect.width, webRect.height); + + // The returned rectangle is in WebKit coordinates (upper left origin), so + // flip the coordinate system and then convert it into screen coordinates for + // return. + NSRect viewFrame = [self frame]; + rect.origin.y = NSHeight(viewFrame) - rect.origin.y; + rect.origin.y -= rect.size.height; + rect = [self convertRectToBase:rect]; + rect.origin = [[self window] convertBaseToScreen:rect.origin]; + return rect; +} + +- (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)theRange + actualRange:(NSRangePointer) actualRange { + if (actualRange) + *actualRange = theRange; + + if (!browser_ || !browser_->UIT_GetWebView() || + !browser_->UIT_GetWebView()->focusedFrame()) { + return nil; + } + + return WebSubstringUtil::attributedSubstringInRange( + browser_->UIT_GetWebView()->focusedFrame(), + theRange.location, + theRange.length); +} + +- (void)doCommandBySelector:(SEL)selector { +} + +- (NSRange)markedRange { + return hasMarkedText_ ? markedRange_ : NSMakeRange(NSNotFound, 0); +} + +- (NSRange)selectedRange { + return selectedRange_; +} + +- (NSInteger)conversationIdentifier { + return reinterpret_cast(self); +} + +- (BOOL)hasMarkedText { + return hasMarkedText_; +} + +- (void)unmarkText { + hasMarkedText_ = NO; + markedText_.clear(); + underlines_.clear(); + + if (!handlingKeyDown_) { + if (browser_ && browser_->UIT_GetWebView()) + browser_->UIT_GetWebView()->confirmComposition(); + } else { + unmarkTextCalled_ = YES; + } +} + +- (void)setMarkedText:(id)string 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 = [string isKindOfClass:[NSAttributedString class]]; + NSString* im_text = isAttributedString ? [string string] : string; + 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(string, &underlines_); + } else { + // Use a thin black underline by default. + underlines_.push_back( + WebCompositionUnderline(0, length, SK_ColorBLACK, false)); + } + + // 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_) { + if (browser_ && browser_->UIT_GetWebView()) { + const WebString markedText(markedText_); + browser_->UIT_GetWebView()->setComposition(markedText, + underlines_, + newSelRange.location, + NSMaxRange(newSelRange)); + } + } +} + +- (void)insertText:(id)string replacementRange: (NSRange) replacementRange { + BOOL isAttributedString = [string isKindOfClass:[NSAttributedString class]]; + NSString* im_text = isAttributedString ? [string string] : string; + if (handlingKeyDown_) { + textToBeInserted_.append(base::SysNSStringToUTF16(im_text)); + } else { + browser_->UIT_GetWebViewHost()->webwidget()->confirmComposition( + base::SysNSStringToUTF16(im_text)); + } + + // Inserting text will delete all marked text automatically. + hasMarkedText_ = NO; +} + +@end diff --git a/cef1/libcef/browser_zoom_map.cc b/cef1/libcef/browser_zoom_map.cc new file mode 100644 index 000000000..2be915400 --- /dev/null +++ b/cef1/libcef/browser_zoom_map.cc @@ -0,0 +1,35 @@ +// 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_zoom_map.h" +#include "libcef/cef_thread.h" + +ZoomMap* ZoomMap::GetInstance() { + return Singleton::get(); +} + +void ZoomMap::set(const GURL& url, double zoomLevel) { + REQUIRE_UIT(); + + if (zoomLevel == 0.) { + // Remove the entry for this host. + Map::iterator iter = map_.find(url.host()); + if (iter != map_.end()) + map_.erase(iter); + } else { + // Update the entry for this host. + map_[url.host()] = zoomLevel; + } +} + +bool ZoomMap::get(const GURL& url, double& zoomLevel) { + REQUIRE_UIT(); + + Map::const_iterator iter = map_.find(url.host()); + if (iter == map_.end()) + return false; + + zoomLevel = iter->second; + return true; +} diff --git a/cef1/libcef/browser_zoom_map.h b/cef1/libcef/browser_zoom_map.h new file mode 100644 index 000000000..5b4345d9a --- /dev/null +++ b/cef1/libcef/browser_zoom_map.h @@ -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. + +#ifndef CEF_LIBCEF_BROWSER_ZOOM_MAP_H_ +#define CEF_LIBCEF_BROWSER_ZOOM_MAP_H_ +#pragma once + +#include +#include + +#include "include/internal/cef_string.h" +#include "base/memory/singleton.h" +#include "googleurl/src/gurl.h" + +// Maps the host/domain of a URL to a zoom value. +// NOTE: This class is not thread-safe. It is assumed that the methods will be +// called from the UI thread. +class ZoomMap { + public: + // Returns the static ZoomMap instance. + static ZoomMap* GetInstance(); + + // Store |zoomLevel| with key |url|. + void set(const GURL& url, double zoomLevel); + + // Returns true if there is a |zoomLevel| keyed with |url|, false otherwise. + // |zoomLevel| is the "out" variable. + bool get(const GURL& url, double& zoomLevel); + + private: + typedef std::map Map; + Map map_; + + friend struct DefaultSingletonTraits; + + ZoomMap() {} + virtual ~ZoomMap() {} + + DISALLOW_COPY_AND_ASSIGN(ZoomMap); +}; + +#endif // CEF_LIBCEF_BROWSER_ZOOM_MAP_H_ diff --git a/cef1/libcef/cef_context.cc b/cef1/libcef/cef_context.cc new file mode 100644 index 000000000..852f3749f --- /dev/null +++ b/cef1/libcef/cef_context.cc @@ -0,0 +1,598 @@ +// 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/cef_context.h" +#include "libcef/browser_devtools_scheme_handler.h" +#include "libcef/browser_impl.h" +#include "libcef/browser_webkit_glue.h" + +#include "base/bind.h" +#include "base/file_util.h" +#include "base/path_service.h" +#include "base/synchronization/waitable_event.h" +#include "ui/base/resource/resource_bundle.h" +#include "ui/base/ui_base_paths.h" + +#if defined(OS_MACOSX) || defined(OS_WIN) +#include "crypto/nss_util.h" +#endif + +#if defined(OS_MACOSX) +#include "base/mac/foundation_util.h" +#include "base/mac/mac_util.h" +#include "grit/webkit_resources.h" +#endif + +#if defined(OS_WIN) +#include "base/win/resource_util.h" +#endif + +// Global CefContext pointer +CefRefPtr _Context; + +namespace { + +// Both the CefContext constuctor and the CefContext::RemoveBrowser method need +// to initialize or reset to the same value. +const int kNextBrowserIdReset = 1; + +#if defined(OS_MACOSX) + +FilePath GetDefaultPackPath() { + // Start out with the path to the running executable. + FilePath execPath; + PathService::Get(base::FILE_EXE, &execPath); + + // Get the main bundle path. + FilePath bundlePath = base::mac::GetAppBundlePath(execPath); + + // Go into the Contents/Resources directory. + return bundlePath.Append(FILE_PATH_LITERAL("Contents")) + .Append(FILE_PATH_LITERAL("Resources")); +} + +#else // !defined(OS_MACOSX) + +FilePath GetDefaultPackPath() { + FilePath pak_dir; + PathService::Get(base::DIR_MODULE, &pak_dir); + return pak_dir; +} + +#endif // !defined(OS_MACOSX) + +// Used in multi-threaded message loop mode to observe shutdown of the UI +// thread. +class DestructionObserver : public MessageLoop::DestructionObserver { + public: + explicit DestructionObserver(base::WaitableEvent *event) : event_(event) {} + virtual void WillDestroyCurrentMessageLoop() { + MessageLoop::current()->RemoveDestructionObserver(this); + event_->Signal(); + delete this; + } + private: + base::WaitableEvent *event_; +}; + +#if defined(OS_WIN) + +// Helper method for retrieving a resource from a module. +base::StringPiece GetRawDataResource(HMODULE module, int resource_id) { + void* data_ptr; + size_t data_size; + return base::win::GetDataResourceFromModule(module, resource_id, &data_ptr, + &data_size) + ? base::StringPiece(static_cast(data_ptr), data_size) + : base::StringPiece(); +} + +#endif // defined(OS_MACOSX) + +} // namespace + + +class CefResourceBundleDelegate : public ui::ResourceBundle::Delegate { + public: + CefResourceBundleDelegate(CefContext* context) + : context_(context), + allow_pack_file_load_(false) { + } + + void set_allow_pack_file_load(bool val) { allow_pack_file_load_ = val; } + + private: + virtual FilePath GetPathForResourcePack( + const FilePath& pack_path, + ui::ScaleFactor scale_factor) OVERRIDE { + // Only allow the cef pack file to load. + if (!context_->settings().pack_loading_disabled && allow_pack_file_load_) + return pack_path; + return FilePath(); + } + + virtual FilePath GetPathForLocalePack(const FilePath& pack_path, + const std::string& locale) OVERRIDE { + if (!context_->settings().pack_loading_disabled) + return pack_path; + return FilePath(); + } + + virtual gfx::Image GetImageNamed(int resource_id) OVERRIDE { + return gfx::Image(); + } + + virtual gfx::Image GetNativeImageNamed( + int resource_id, + ui::ResourceBundle::ImageRTL rtl) OVERRIDE { + return gfx::Image(); + } + + virtual base::RefCountedStaticMemory* LoadDataResourceBytes( + int resource_id, + ui::ScaleFactor scale_factor) OVERRIDE { + return NULL; + } + + virtual bool GetRawDataResource(int resource_id, + ui::ScaleFactor scale_factor, + base::StringPiece* value) OVERRIDE { + return false; + } + + virtual bool GetLocalizedString(int message_id, string16* value) OVERRIDE { + return false; + } + + virtual scoped_ptr GetFont( + ui::ResourceBundle::FontStyle style) OVERRIDE { + return scoped_ptr(); + } + + // CefContext pointer is guaranteed to outlive this object. + CefContext* context_; + bool allow_pack_file_load_; + + DISALLOW_COPY_AND_ASSIGN(CefResourceBundleDelegate); +}; + + +bool CefInitialize(const CefSettings& settings, CefRefPtr application) { + // Return true if the global context already exists. + if (_Context.get()) + return true; + + if (settings.size != sizeof(cef_settings_t)) { + NOTREACHED() << "invalid CefSettings structure size"; + return false; + } + + // Create the new global context object. + _Context = new CefContext(); + + // Initialize the global context. + return _Context->Initialize(settings, application); +} + +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 (!_Context->process()->CalledOnValidThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + // Shut down the global context. This will block until shutdown is complete. + _Context->Shutdown(); + + // Delete the global context object. + _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 (!_Context->process()->CalledOnValidThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + _Context->process()->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 (!_Context->process()->CalledOnValidThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + _Context->process()->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 (!_Context->process()->CalledOnValidThread()) { + NOTREACHED() << "called on invalid thread"; + return; + } + + _Context->process()->QuitMessageLoop(); +} + + +// CefContext + +CefContext::CefContext() + : initialized_(false), + shutting_down_(false), + request_context_(NULL), + next_browser_id_(kNextBrowserIdReset), + current_webviewhost_(NULL) { +} + +CefContext::~CefContext() { + if (!shutting_down_) + Shutdown(); +} + +bool CefContext::Initialize(const CefSettings& settings, + CefRefPtr application) { + settings_ = settings; + application_ = application; + + cache_path_ = FilePath(CefString(&settings.cache_path)); + if (!cache_path_.empty() && + !file_util::PathExists(cache_path_) && + !file_util::CreateDirectory(cache_path_)) { + NOTREACHED() << "Failed to create cache_path directory"; + cache_path_.clear(); + } + +#if defined(OS_MACOSX) || defined(OS_WIN) + // We want to be sure to init NSPR on the main thread. + crypto::EnsureNSPRInit(); +#endif + + process_.reset(new CefProcess(settings_.multi_threaded_message_loop)); + process_->CreateChildThreads(); + + initialized_ = true; + + // Perform DevTools scheme registration when CEF initialization is complete. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&RegisterDevToolsSchemeHandler, true)); + + return true; +} + +void CefContext::Shutdown() { + // Must always be called on the same thread as Initialize. + DCHECK(process_->CalledOnValidThread()); + + 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 browser_shutdown_event(false, false); + base::WaitableEvent uithread_shutdown_event(false, false); + + // Finish shutdown on the UI thread. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefContext::UIT_FinishShutdown, this, + &browser_shutdown_event, &uithread_shutdown_event)); + + // Block until browser shutdown is complete. + browser_shutdown_event.Wait(); + + // Delete the process to destroy the child threads. + process_.reset(NULL); + + // Block until UI thread shutdown is complete. + uithread_shutdown_event.Wait(); + } else { + // Finish shutdown on the current thread, which should be the UI thread. + UIT_FinishShutdown(NULL, NULL); + + // Delete the process to destroy the child threads. + process_.reset(NULL); + } +} + +bool CefContext::AddBrowser(CefRefPtr browser) { + bool found = false; + + AutoLock lock_scope(this); + + // check that the browser isn't already in the list before adding + BrowserList::const_iterator it = browserlist_.begin(); + for (; it != browserlist_.end(); ++it) { + if (it->get() == browser.get()) { + found = true; + break; + } + } + + if (!found) { + browser->UIT_SetUniqueID(next_browser_id_++); + browserlist_.push_back(browser); + } + + return !found; +} + +bool CefContext::RemoveBrowser(CefRefPtr browser) { + bool deleted = false; + bool empty = false; + + { + AutoLock lock_scope(this); + + BrowserList::iterator it = browserlist_.begin(); + for (; it != browserlist_.end(); ++it) { + if (it->get() == browser.get()) { + browserlist_.erase(it); + deleted = true; + break; + } + } + + if (browserlist_.empty()) { + next_browser_id_ = kNextBrowserIdReset; + empty = true; + } + } + + if (empty) { + if (CefThread::CurrentlyOn(CefThread::UI)) { + webkit_glue::ClearCache(); + } else { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(webkit_glue::ClearCache)); + } + } + + return deleted; +} + +CefRefPtr CefContext::GetBrowserByID(int id) { + AutoLock lock_scope(this); + + BrowserList::const_iterator it = browserlist_.begin(); + for (; it != browserlist_.end(); ++it) { + if (it->get()->UIT_GetUniqueID() == id) + return it->get(); + } + + return NULL; +} + +void CefContext::InitializeResourceBundle() { + FilePath pak_file, locales_dir; + + if (!settings_.pack_loading_disabled) { + if (settings_.pack_file_path.length > 0) + pak_file = FilePath(CefString(&settings_.pack_file_path)); + + if (pak_file.empty()) + pak_file = GetDefaultPackPath().Append(FILE_PATH_LITERAL("chrome.pak")); + + if (settings_.locales_dir_path.length > 0) + locales_dir = FilePath(CefString(&settings_.locales_dir_path)); + + if (!locales_dir.empty()) + PathService::Override(ui::DIR_LOCALES, locales_dir); + } + + std::string locale_str = locale(); + if (locale_str.empty()) + locale_str = "en-US"; + + resource_bundle_delegate_.reset(new CefResourceBundleDelegate(this)); + const std::string loaded_locale = + ui::ResourceBundle::InitSharedInstanceWithLocale( + locale_str, resource_bundle_delegate_.get()); + if (!settings_.pack_loading_disabled) { + CHECK(!loaded_locale.empty()) << "Locale could not be found for " + << locale_str; + + if (file_util::PathExists(pak_file)) { + resource_bundle_delegate_->set_allow_pack_file_load(true); + ResourceBundle::GetSharedInstance().AddDataPack( + pak_file, ui::SCALE_FACTOR_NONE); + resource_bundle_delegate_->set_allow_pack_file_load(false); + } else { + NOTREACHED() << "Could not load chrome.pak"; + } + } +} + +void CefContext::CleanupResourceBundle() { + ResourceBundle::CleanupSharedInstance(); + resource_bundle_delegate_.reset(NULL); +} + +string16 CefContext::GetLocalizedString(int message_id) const { + 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; + } + } + + if (value.empty() && !settings_.pack_loading_disabled) + value = ResourceBundle::GetSharedInstance().GetLocalizedString(message_id); + + if (value.empty()) + LOG(ERROR) << "No localized string available for id " << message_id; + + return value; +} + +base::StringPiece CefContext::GetDataResource(int resource_id) const { + 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); + } + } + +#if defined(OS_WIN) + if (value.empty()) { + FilePath file_path; + HMODULE hModule = NULL; + + // Try to load the resource from the DLL. + if (PathService::Get(base::FILE_MODULE, &file_path)) + hModule = ::GetModuleHandle(file_path.value().c_str()); + if (!hModule) + hModule = ::GetModuleHandle(NULL); + value = ::GetRawDataResource(hModule, resource_id); + } +#elif defined(OS_MACOSX) + if (value.empty()) { + switch (resource_id) { + case IDR_BROKENIMAGE: { + // Use webkit's broken image icon (16x16) + static std::string broken_image_data; + if (broken_image_data.empty()) { + FilePath path = GetResourcesFilePath(); + // In order to match WebKit's colors for the missing image, we have to + // use a PNG. The GIF doesn't have the color range needed to correctly + // match the TIFF they use in Safari. + path = path.AppendASCII("missingImage.png"); + bool success = file_util::ReadFileToString(path, &broken_image_data); + if (!success) { + LOG(FATAL) << "Failed reading: " << path.value(); + } + } + value = broken_image_data; + break; + } + case IDR_TEXTAREA_RESIZER: { + // Use webkit's text area resizer image. + static std::string resize_corner_data; + if (resize_corner_data.empty()) { + FilePath path = GetResourcesFilePath(); + path = path.AppendASCII("textAreaResizeCorner.png"); + bool success = file_util::ReadFileToString(path, &resize_corner_data); + if (!success) { + LOG(FATAL) << "Failed reading: " << path.value(); + } + } + value = resize_corner_data; + break; + } + + default: + break; + } + } +#endif // defined(OS_MACOSX) + + if (value.empty() && !settings_.pack_loading_disabled) { + value = ResourceBundle::GetSharedInstance().GetRawDataResource( + resource_id, ui::SCALE_FACTOR_NONE); + } + + if (value.empty()) + LOG(ERROR) << "No data resource available for id " << resource_id; + + return value; +} + +#if defined(OS_MACOSX) +FilePath CefContext::GetResourcesFilePath() const { + FilePath path; + // We need to know if we're bundled or not to know which path to use. + if (base::mac::AmIBundled()) { + PathService::Get(base::DIR_EXE, &path); + path = path.Append(FilePath::kParentDirectory); + return path.AppendASCII("Resources"); + } else { + // TODO(port): Allow the embedder to customize the resource path. + PathService::Get(base::DIR_SOURCE_ROOT, &path); + path = path.AppendASCII("src"); + path = path.AppendASCII("cef"); + path = path.AppendASCII("tests"); + path = path.AppendASCII("cefclient"); + return path.AppendASCII("res"); + } +} +#endif // defined(OS_MACOSX) + +std::string CefContext::locale() const { + std::string localeStr = CefString(&settings_.locale); + if (!localeStr.empty()) + return localeStr; + + return "en-US"; +} + +void CefContext::UIT_FinishShutdown( + base::WaitableEvent* browser_shutdown_event, + base::WaitableEvent* uithread_shutdown_event) { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + + BrowserList list; + + { + AutoLock lock_scope(this); + if (!browserlist_.empty()) { + list = browserlist_; + browserlist_.clear(); + } + } + + // Destroy any remaining browser windows. + if (!list.empty()) { + BrowserList::iterator it = list.begin(); + for (; it != list.end(); ++it) + (*it)->UIT_DestroyBrowser(); + } + + if (uithread_shutdown_event) { + // The destruction observer will signal the UI thread shutdown event when + // the UI thread has been destroyed. + MessageLoop::current()->AddDestructionObserver( + new DestructionObserver(uithread_shutdown_event)); + + // Signal the browser shutdown event now. + browser_shutdown_event->Signal(); + } +} diff --git a/cef1/libcef/cef_context.h b/cef1/libcef/cef_context.h new file mode 100644 index 000000000..f6d867bc9 --- /dev/null +++ b/cef1/libcef/cef_context.h @@ -0,0 +1,145 @@ +// 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_CEF_CONTEXT_H_ +#define CEF_LIBCEF_CEF_CONTEXT_H_ +#pragma once + +#include +#include +#include + +#include "include/cef_app.h" +#include "include/cef_base.h" +#include "libcef/browser_file_system.h" +#include "libcef/browser_request_context.h" +#include "libcef/cef_process.h" + +#include "base/at_exit.h" +#include "base/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/threading/sequenced_worker_pool.h" + +class CefBrowserImpl; +class CefResourceBundleDelegate; +class WebViewHost; + +namespace base { +class WaitableEvent; +} + +class CefContext : public CefBase { + public: + typedef std::list > BrowserList; + + CefContext(); + ~CefContext(); + + // These methods will be called on the main application thread. + bool Initialize(const CefSettings& settings, CefRefPtr application); + void Shutdown(); + + // 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_; } + + CefProcess* process() { return process_.get(); } + + bool AddBrowser(CefRefPtr browser); + bool RemoveBrowser(CefRefPtr browser); + CefRefPtr GetBrowserByID(int id); + BrowserList* GetBrowserList() { return &browserlist_; } + + void InitializeResourceBundle(); + void CleanupResourceBundle(); + + string16 GetLocalizedString(int message_id) const; + base::StringPiece GetDataResource(int resource_id) const; + +#if defined(OS_MACOSX) + FilePath GetResourcesFilePath() const; +#endif + + // Retrieve the path at which cache data will be stored on disk. If empty, + // cache data will be stored in-memory. + const FilePath& cache_path() const { return cache_path_; } + + const CefSettings& settings() const { return settings_; } + CefRefPtr application() const { return application_; } + + // Return the locale specified in CefSettings or the default value of "en-US". + std::string locale() const; + + // The BrowserRequestContext object is managed by CefProcessIOThread. + void set_request_context(BrowserRequestContext* request_context) { + request_context_ = request_context; + } + BrowserRequestContext* request_context() { return request_context_; } + + BrowserFileSystem* file_system() { return &file_system_; } + + // Used to keep track of the web view host we're dragging over. WARNING: + // this pointer should never be dereferenced. Use it only for comparing + // pointers. + WebViewHost* current_webviewhost() { return current_webviewhost_; } + void set_current_webviewhost(WebViewHost* host) { + current_webviewhost_ = host; + } + + // The SequencedWorkerPool object is managed by CefProcessUIThread. + void set_blocking_pool(base::SequencedWorkerPool* blocking_pool) { + blocking_pool_ = blocking_pool; + } + base::SequencedWorkerPool* blocking_pool() { return blocking_pool_.get(); } + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + + private: + // Performs shutdown actions that need to occur on the UI thread before any + // threads are destroyed. + void UIT_FinishShutdown(base::WaitableEvent* browser_shutdown_event, + base::WaitableEvent* uithread_shutdown_event); + + // Track context state. + bool initialized_; + bool shutting_down_; + + // Manages the various process threads. + scoped_ptr process_; + + // Initialize the AtExitManager on the main application thread to avoid + // asserts and possible memory leaks. + base::AtExitManager at_exit_manager_; + + CefSettings settings_; + CefRefPtr application_; + FilePath cache_path_; + BrowserRequestContext* request_context_; + BrowserFileSystem file_system_; + scoped_ptr resource_bundle_delegate_; + + // Map of browsers that currently exist. + BrowserList browserlist_; + + // Used for assigning unique IDs to browser instances. + int next_browser_id_; + + WebViewHost* current_webviewhost_; + + scoped_refptr blocking_pool_; + + IMPLEMENT_REFCOUNTING(CefContext); + IMPLEMENT_LOCKING(CefContext); +}; + +// Global context object pointer. +extern CefRefPtr _Context; + +// Helper macro that returns true if the global context is in a valid state. +#define CONTEXT_STATE_VALID() \ + (_Context.get() && _Context->initialized() && !_Context->shutting_down()) + +#endif // CEF_LIBCEF_CEF_CONTEXT_H_ diff --git a/cef1/libcef/cef_process.cc b/cef1/libcef/cef_process.cc new file mode 100644 index 000000000..ee9e17e50 --- /dev/null +++ b/cef1/libcef/cef_process.cc @@ -0,0 +1,157 @@ +// Copyright (c) 2010 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. + +#include "libcef/cef_process.h" +#include "libcef/cef_process_io_thread.h" +#include "libcef/cef_process_sub_thread.h" +#include "libcef/cef_process_ui_thread.h" + +#include "base/synchronization/waitable_event.h" +#include "base/threading/thread.h" + +// Class used to process events on the current message loop. +class CefMessageLoopForUI : public MessageLoopForUI { + typedef MessageLoopForUI inherited; + + public: + CefMessageLoopForUI() + : is_iterating_(true) { + } +#if defined(OS_MACOSX) + virtual ~CefMessageLoopForUI() { + // On Mac the MessageLoop::AutoRunState scope in Run() never exits so clear + // the state_ variable to avoid an assertion in the MessageLoop destructor. + state_ = NULL; + } +#endif + + // Returns the MessageLoopForUI of the current thread. + static CefMessageLoopForUI* current() { + MessageLoop* loop = MessageLoop::current(); + DCHECK_EQ(MessageLoop::TYPE_UI, loop->type()); + return static_cast(loop); + } + + virtual bool DoIdleWork() { + bool valueToRet = inherited::DoIdleWork(); + if (is_iterating_) + pump_->Quit(); + return valueToRet; + } + + // Do a single interation of the UI message loop. + void DoMessageLoopIteration() { +#if defined(OS_MACOSX) + Run(); +#else + RunWithDispatcher(NULL); +#endif + } + + // Run the UI message loop. + void RunMessageLoop() { + is_iterating_ = false; + DoMessageLoopIteration(); + } + + bool is_iterating() { return is_iterating_; } + + private: + // True if the message loop is doing one iteration at a time. + bool is_iterating_; + + DISALLOW_COPY_AND_ASSIGN(CefMessageLoopForUI); +}; + +CefProcess::CefProcess(bool multi_threaded_message_loop) + : multi_threaded_message_loop_(multi_threaded_message_loop), + created_ui_thread_(false), + created_io_thread_(false), + created_file_thread_(false) { +} + +CefProcess::~CefProcess() { + // Terminate the IO thread. + io_thread_.reset(); + + // Terminate the FILE thread. + file_thread_.reset(); + + if (!multi_threaded_message_loop_) { + // Must explicitly clean up the UI thread. + ui_thread_->CleanUp(); + + // Terminate the UI thread. + ui_thread_.reset(); + + // Terminate the message loop. + ui_message_loop_.reset(); + } +} + +void CefProcess::DoMessageLoopIteration() { + DCHECK(CalledOnValidThread() && ui_message_loop_.get() != NULL); + DCHECK(ui_message_loop_->is_iterating()); + ui_message_loop_->DoMessageLoopIteration(); +} + +void CefProcess::RunMessageLoop() { + DCHECK(CalledOnValidThread() && ui_message_loop_.get() != NULL); + ui_message_loop_->RunMessageLoop(); +} + +void CefProcess::QuitMessageLoop() { + DCHECK(CalledOnValidThread() && ui_message_loop_.get() != NULL); + ui_message_loop_->Quit(); +} + +void CefProcess::CreateUIThread() { + DCHECK(!created_ui_thread_ && ui_thread_.get() == NULL); + created_ui_thread_ = true; + + scoped_ptr thread; + if (multi_threaded_message_loop_) { + // Create the message loop on a new thread. + thread.reset(new CefProcessUIThread()); + base::Thread::Options options; + options.message_loop_type = MessageLoop::TYPE_UI; + if (!thread->StartWithOptions(options)) + return; + } else { + // Create the message loop on the current (main application) thread. + ui_message_loop_.reset(new CefMessageLoopForUI()); + thread.reset( + new CefProcessUIThread(ui_message_loop_.get())); + + // Must explicitly initialize the UI thread. + thread->Init(); + } + + ui_thread_.swap(thread); +} + +void CefProcess::CreateIOThread() { + DCHECK(!created_io_thread_ && io_thread_.get() == NULL); + created_io_thread_ = true; + + scoped_ptr thread(new CefProcessIOThread()); + base::Thread::Options options; + options.message_loop_type = MessageLoop::TYPE_IO; + if (!thread->StartWithOptions(options)) + return; + io_thread_.swap(thread); +} + +void CefProcess::CreateFileThread() { + DCHECK(!created_file_thread_ && file_thread_.get() == NULL); + created_file_thread_ = true; + + scoped_ptr thread(new CefProcessSubThread(CefThread::FILE)); + base::Thread::Options options; + options.message_loop_type = MessageLoop::TYPE_IO; + if (!thread->StartWithOptions(options)) + return; + file_thread_.swap(thread); +} diff --git a/cef1/libcef/cef_process.h b/cef1/libcef/cef_process.h new file mode 100644 index 000000000..81c4c7a57 --- /dev/null +++ b/cef1/libcef/cef_process.h @@ -0,0 +1,122 @@ +// Copyright (c) 2010 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. + +// This interface is for managing the global services of the application. Each +// service is lazily created when requested the first time. The service getters +// will return NULL if the service is not available, so callers must check for +// this condition. + +#ifndef CEF_LIBCEF_CEF_PROCESS_H_ +#define CEF_LIBCEF_CEF_PROCESS_H_ +#pragma once + +#include +#include + +#include "base/basictypes.h" +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop.h" +#include "base/threading/non_thread_safe.h" +#include "ipc/ipc_message.h" + +namespace base { +class Thread; +class WaitableEvent; +} + +class CefProcessIOThread; +class CefProcessUIThread; +class CefMessageLoopForUI; + +// NOT THREAD SAFE, call only from the main thread. +// These functions shouldn't return NULL unless otherwise noted. +class CefProcess : public base::NonThreadSafe { + public: + explicit CefProcess(bool multi_threaded_message_loop); + virtual ~CefProcess(); + + // Creates key child threads. We need to do this explicitly since + // CefThread::PostTask silently deletes a posted task if the target message + // loop isn't created. + void CreateChildThreads() { + ui_thread(); + // Create the FILE thread before the IO thread because IO thread + // initialization depends on existance of the FILE thread (for cache + // support, etc). + file_thread(); + io_thread(); + } + + CefProcessUIThread* ui_thread() { + DCHECK(CalledOnValidThread()); + if (!created_ui_thread_) + CreateUIThread(); + return ui_thread_.get(); + } + + // Do a single iteration of the UI message loop on the current thread. If + // RunMessageLoop() was called you do not need to call this method. + void DoMessageLoopIteration(); + + // Run the UI message loop on the current thread. + void RunMessageLoop(); + + // Quit the UI message loop on the current thread. + void QuitMessageLoop(); + + // Returns the thread that we perform I/O coordination on (network requests, + // communication with renderers, etc. + // NOTE: You should ONLY use this to pass to IPC or other objects which must + // need a MessageLoop*. If you just want to post a task, use + // CefThread::PostTask (or other variants) as they take care of checking + // that a thread is still alive, race conditions, lifetime differences etc. + // If you still must use this, need to check the return value for NULL. + CefProcessIOThread* io_thread() { + DCHECK(CalledOnValidThread()); + if (!created_io_thread_) + CreateIOThread(); + return io_thread_.get(); + } + + // Returns the thread that we perform random file operations on. For code + // that wants to do I/O operations (not network requests or even file: URL + // requests), this is the thread to use to avoid blocking the UI thread. + // It might be nicer to have a thread pool for this kind of thing. + base::Thread* file_thread() { + DCHECK(CalledOnValidThread()); + if (!created_file_thread_) + CreateFileThread(); + return file_thread_.get(); + } + +#if defined(IPC_MESSAGE_LOG_ENABLED) + // Enable or disable IPC logging for the browser, all processes + // derived from ChildProcess (plugin etc), and all + // renderers. + void SetIPCLoggingEnabled(bool enable); +#endif + + private: + void CreateUIThread(); + void CreateIOThread(); + void CreateFileThread(); + + bool multi_threaded_message_loop_; + + bool created_ui_thread_; + scoped_ptr ui_thread_; + scoped_ptr ui_message_loop_; + + bool created_io_thread_; + scoped_ptr io_thread_; + + bool created_file_thread_; + scoped_ptr file_thread_; + + DISALLOW_COPY_AND_ASSIGN(CefProcess); +}; + +#endif // CEF_LIBCEF_CEF_PROCESS_H_ diff --git a/cef1/libcef/cef_process_io_thread.cc b/cef1/libcef/cef_process_io_thread.cc new file mode 100644 index 000000000..b25e8a32c --- /dev/null +++ b/cef1/libcef/cef_process_io_thread.cc @@ -0,0 +1,78 @@ +// Copyright (c) 2010 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. + +#include "libcef/cef_process_io_thread.h" + +#include "libcef/cef_context.h" +#include "libcef/browser_appcache_system.h" +#include "libcef/browser_file_writer.h" +#include "libcef/browser_network_delegate.h" +#include "libcef/browser_resource_loader_bridge.h" +#include "libcef/browser_socket_stream_bridge.h" +#include "libcef/browser_webblobregistry_impl.h" + +#include "build/build_config.h" +#include "base/compiler_specific.h" +#include "net/socket/client_socket_pool_manager.h" + +#if defined(OS_WIN) +#include // NOLINT(build/include_order) +#endif + +CefProcessIOThread::CefProcessIOThread() + : CefThread(CefThread::IO), request_context_(NULL) {} + +CefProcessIOThread::CefProcessIOThread(MessageLoop* message_loop) + : CefThread(CefThread::IO, message_loop), request_context_(NULL) {} + +CefProcessIOThread::~CefProcessIOThread() { + // We cannot rely on our base class to stop the thread since we want our + // CleanUp function to run. + Stop(); +} + +void CefProcessIOThread::Init() { + CefThread::Init(); + + FilePath cache_path(_Context->cache_path()); + request_context_.reset(new BrowserRequestContext(cache_path, + net::HttpCache::NORMAL, false)); + _Context->set_request_context(request_context_.get()); + + network_delegate_.reset(new BrowserNetworkDelegate()); + request_context_->set_network_delegate(network_delegate_.get()); + + BrowserAppCacheSystem::InitializeOnIOThread(request_context_.get()); + BrowserFileWriter::InitializeOnIOThread(request_context_.get()); + BrowserFileSystem::InitializeOnIOThread( + request_context_->blob_storage_controller()); + BrowserSocketStreamBridge::InitializeOnIOThread(request_context_.get()); + BrowserWebBlobRegistryImpl::InitializeOnIOThread( + request_context_->blob_storage_controller()); +} + +void CefProcessIOThread::CleanUp() { + // Flush any remaining messages. This ensures that any accumulated + // Task objects get destroyed before we exit, which avoids noise in + // purify leak-test results. + MessageLoop::current()->RunAllPending(); + + // In reverse order of initialization. + BrowserWebBlobRegistryImpl::Cleanup(); + BrowserSocketStreamBridge::Cleanup(); + BrowserFileSystem::CleanupOnIOThread(); + BrowserFileWriter::CleanupOnIOThread(); + BrowserAppCacheSystem::CleanupOnIOThread(); + + _Context->set_request_context(NULL); + + request_context_->set_network_delegate(NULL); + network_delegate_.reset(NULL); + + _Context->set_request_context(NULL); + request_context_.reset(NULL); + + CefThread::Cleanup(); +} diff --git a/cef1/libcef/cef_process_io_thread.h b/cef1/libcef/cef_process_io_thread.h new file mode 100644 index 000000000..61341b052 --- /dev/null +++ b/cef1/libcef/cef_process_io_thread.h @@ -0,0 +1,46 @@ +// Copyright (c) 2010 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. + +#ifndef CEF_LIBCEF_CEF_PROCESS_IO_THREAD_H_ +#define CEF_LIBCEF_CEF_PROCESS_IO_THREAD_H_ +#pragma once + +#include "libcef/browser_request_context.h" +#include "libcef/cef_thread.h" + +#include "base/basictypes.h" + +namespace net { +class NetworkDelegate; +} + +// ---------------------------------------------------------------------------- +// CefProcessIOThread +// +// This simple thread object is used for the specialized threads that the +// CefProcess spins up. +// +// Applications must initialize the COM library before they can call +// COM library functions other than CoGetMalloc and memory allocation +// functions, so this class initializes COM for those users. +class CefProcessIOThread : public CefThread { + public: + CefProcessIOThread(); + explicit CefProcessIOThread(MessageLoop* message_loop); + virtual ~CefProcessIOThread(); + + BrowserRequestContext* request_context() { return request_context_.get(); } + + protected: + virtual void Init(); + virtual void CleanUp(); + + scoped_ptr request_context_; + scoped_ptr network_delegate_; + + DISALLOW_COPY_AND_ASSIGN(CefProcessIOThread); +}; + +#endif // CEF_LIBCEF_CEF_PROCESS_IO_THREAD_H_ diff --git a/cef1/libcef/cef_process_sub_thread.cc b/cef1/libcef/cef_process_sub_thread.cc new file mode 100644 index 000000000..6d59e3be1 --- /dev/null +++ b/cef1/libcef/cef_process_sub_thread.cc @@ -0,0 +1,31 @@ +// Copyright (c) 2010 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. + +#include "libcef/cef_process_sub_thread.h" + +#include "build/build_config.h" +#include "base/compiler_specific.h" + +CefProcessSubThread::CefProcessSubThread(CefThread::ID identifier) + : CefThread(identifier) {} + +CefProcessSubThread::CefProcessSubThread(CefThread::ID identifier, + MessageLoop* message_loop) + : CefThread(identifier, message_loop) {} + +CefProcessSubThread::~CefProcessSubThread() { + // We cannot rely on our base class to stop the thread since we want our + // CleanUp function to run. + Stop(); +} + +void CefProcessSubThread::CleanUp() { + // Flush any remaining messages. This ensures that any accumulated + // Task objects get destroyed before we exit, which avoids noise in + // purify leak-test results. + MessageLoop::current()->RunAllPending(); + + CefThread::Cleanup(); +} diff --git a/cef1/libcef/cef_process_sub_thread.h b/cef1/libcef/cef_process_sub_thread.h new file mode 100644 index 000000000..b1d4bf570 --- /dev/null +++ b/cef1/libcef/cef_process_sub_thread.h @@ -0,0 +1,36 @@ +// Copyright (c) 2010 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. + +#ifndef CEF_LIBCEF_CEF_PROCESS_SUB_THREAD_H_ +#define CEF_LIBCEF_CEF_PROCESS_SUB_THREAD_H_ +#pragma once + +#include "libcef/cef_thread.h" + +#include "base/basictypes.h" + +// ---------------------------------------------------------------------------- +// CefProcessSubThread +// +// This simple thread object is used for the specialized threads that the +// CefProcess spins up. +// +// Applications must initialize the COM library before they can call +// COM library functions other than CoGetMalloc and memory allocation +// functions, so this class initializes COM for those users. +class CefProcessSubThread : public CefThread { + public: + explicit CefProcessSubThread(CefThread::ID identifier); + CefProcessSubThread(CefThread::ID identifier, MessageLoop* message_loop); + virtual ~CefProcessSubThread(); + + protected: + virtual void CleanUp(); + + private: + DISALLOW_COPY_AND_ASSIGN(CefProcessSubThread); +}; + +#endif // CEF_LIBCEF_CEF_PROCESS_SUB_THREAD_H_ diff --git a/cef1/libcef/cef_process_ui_thread.cc b/cef1/libcef/cef_process_ui_thread.cc new file mode 100644 index 000000000..9da589556 --- /dev/null +++ b/cef1/libcef/cef_process_ui_thread.cc @@ -0,0 +1,217 @@ +// Copyright (c) 2010 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. + +#include "libcef/cef_process_ui_thread.h" + +#include + +#include "include/cef_version.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/browser_webkit_init.h" +#include "libcef/cef_context.h" + +#include "base/bind.h" +#include "base/command_line.h" +#include "base/i18n/icu_util.h" +#include "base/metrics/stats_table.h" +#include "base/rand_util.h" +#include "base/string_number_conversions.h" +#include "base/stringprintf.h" +#include "build/build_config.h" +#include "net/base/net_module.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebNetworkStateNotifier.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptController.h" +#include "ui/base/ui_base_paths.h" +#include "ui/gl/gl_implementation.h" +#include "webkit/glue/user_agent.h" +#include "webkit/glue/webkit_glue.h" +#include "webkit/plugins/npapi/plugin_list.h" + +#if defined(OS_WIN) +#include // NOLINT(build/include_order) +#include // NOLINT(build/include_order) +#endif + +namespace { + +static const char* kStatsFilePrefix = "libcef_"; +static int kStatsFileThreads = 20; +static int kStatsFileCounters = 200; + +base::StringPiece ResourceProvider(int resource_id) { + return _Context->GetDataResource(resource_id); +} + +} // namespace + +CefProcessUIThread::CefProcessUIThread() + : CefThread(CefThread::UI), statstable_(NULL), webkit_init_(NULL) {} + +CefProcessUIThread::CefProcessUIThread(MessageLoop* message_loop) + : CefThread(CefThread::UI, message_loop), statstable_(NULL), + webkit_init_(NULL) {} + +CefProcessUIThread::~CefProcessUIThread() { + // We cannot rely on our base class to stop the thread since we want our + // CleanUp function to run. + Stop(); +} + +void CefProcessUIThread::Init() { + // Initialize the global CommandLine object. + CommandLine::Init(0, NULL); + + const CefSettings& settings = _Context->settings(); + + // Initialize logging. + logging::LoggingDestination logging_dest; + if (settings.log_severity == LOGSEVERITY_DISABLE) { + logging_dest = logging::LOG_NONE; + } else { +#if defined(OS_WIN) + logging_dest = logging::LOG_ONLY_TO_FILE; +#else + logging_dest = logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG; +#endif + logging::SetMinLogLevel(settings.log_severity); + } + + FilePath log_file = FilePath(CefString(&settings.log_file)); + logging::InitLogging(log_file.value().c_str(), logging_dest, + logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE, + logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS); + + // Load ICU data tables. + bool ret = icu_util::Initialize(); + if (!ret) { +#if defined(OS_WIN) + MessageBox(NULL, L"Failed to load the required icudt library", + L"CEF Initialization Error", MB_ICONERROR | MB_OK); +#endif + return; + } + + // Provides path resolution required for locating locale pack files. + ui::RegisterPathProvider(); + + _Context->InitializeResourceBundle(); + + PlatformInit(); + + // Initialize the blocking pool. + blocking_pool_ = new base::SequencedWorkerPool(3, "BrowserBlocking"); + _Context->set_blocking_pool(blocking_pool_.get()); + + // Initialize WebKit. + webkit_init_ = new BrowserWebKitInit(); + + // Initialize WebKit encodings + webkit_glue::InitializeTextEncoding(); + + // Config the network module so it has access to a limited set of resources. + net::NetModule::SetResourceProvider(ResourceProvider); + + // Load and initialize the stats table. Attempt to construct a somewhat + // unique name to isolate separate instances from each other. + statstable_ = new base::StatsTable( + kStatsFilePrefix + base::Uint64ToString(base::RandUint64()), + kStatsFileThreads, + kStatsFileCounters); + base::StatsTable::set_current(statstable_); + + if (settings.javascript_flags.length > 0) { + // Pass the JavaScript flags to V8. + webkit_glue::SetJavaScriptFlags(CefString(&settings.javascript_flags)); + } + +#if defined(OS_WIN) + if (settings.graphics_implementation == ANGLE_IN_PROCESS || + settings.graphics_implementation == ANGLE_IN_PROCESS_COMMAND_BUFFER) { + gfx::InitializeGLBindings(gfx::kGLImplementationEGLGLES2); + } else { + gfx::InitializeGLBindings(gfx::kGLImplementationDesktopGL); + } +#else + gfx::InitializeGLBindings(gfx::kGLImplementationDesktopGL); +#endif + + if (settings.user_agent.length > 0) { + webkit_glue::SetUserAgent(CefString(&settings.user_agent), false); + } else { + std::string product_version; + + if (settings.product_version.length > 0) { + product_version = CefString(&settings.product_version).ToString(); + } else { + product_version = base::StringPrintf("Chrome/%d.%d.%d.%d", + CHROME_VERSION_MAJOR, CHROME_VERSION_MINOR, CHROME_VERSION_BUILD, + CHROME_VERSION_PATCH); + } + + webkit_glue::SetUserAgent( + webkit_glue::BuildUserAgentFromProduct(product_version), false); + } + + if (settings.extra_plugin_paths) { + cef_string_t str; + memset(&str, 0, sizeof(str)); + + FilePath path; + int size = cef_string_list_size(settings.extra_plugin_paths); + for (int i = 0; i < size; ++i) { + if (!cef_string_list_value(settings.extra_plugin_paths, i, &str)) + continue; + path = FilePath(CefString(&str)); + webkit::npapi::PluginList::Singleton()->AddExtraPluginPath(path); + } + } + + // Create a network change notifier before starting the IO & File threads. + network_change_notifier_.reset(net::NetworkChangeNotifier::Create()); + + // Add a listener for OnConnectionTypeChanged to notify WebKit of changes. + net::NetworkChangeNotifier::AddConnectionTypeObserver(this); + + // Initialize WebKit with the current state. + WebKit::WebNetworkStateNotifier::setOnLine( + !net::NetworkChangeNotifier::IsOffline()); +} + +void CefProcessUIThread::CleanUp() { + // Flush any remaining messages. This ensures that any accumulated + // Task objects get destroyed before we exit, which avoids noise in + // purify leak-test results. + MessageLoop::current()->RunAllPending(); + + // Tear down the shared StatsTable. + base::StatsTable::set_current(NULL); + delete statstable_; + statstable_ = NULL; + + // Shut down WebKit. + delete webkit_init_; + webkit_init_ = NULL; + + // Release the network change notifier after all other threads end. + net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this); + network_change_notifier_.reset(); + + // Shut down the blocking pool. + _Context->set_blocking_pool(NULL); + blocking_pool_->Shutdown(); + blocking_pool_ = NULL; + + PlatformCleanUp(); + + _Context->CleanupResourceBundle(); +} + +void CefProcessUIThread::OnConnectionTypeChanged( + net::NetworkChangeNotifier::ConnectionType type) { + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); + WebKit::WebNetworkStateNotifier::setOnLine( + type != net::NetworkChangeNotifier::CONNECTION_NONE); +} + diff --git a/cef1/libcef/cef_process_ui_thread.h b/cef1/libcef/cef_process_ui_thread.h new file mode 100644 index 000000000..4b6bdef76 --- /dev/null +++ b/cef1/libcef/cef_process_ui_thread.h @@ -0,0 +1,62 @@ +// Copyright (c) 2010 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. + +#ifndef CEF_LIBCEF_CEF_PROCESS_UI_THREAD_H_ +#define CEF_LIBCEF_CEF_PROCESS_UI_THREAD_H_ +#pragma once + +#include "libcef/cef_thread.h" + +#include "base/basictypes.h" +#include "base/memory/scoped_ptr.h" +#include "base/threading/sequenced_worker_pool.h" +#include "net/base/network_change_notifier.h" + +class BrowserWebKitInit; +namespace base { +class StatsTable; +} + +// ---------------------------------------------------------------------------- +// CefProcessUIThread +// +// This simple thread object is used for the specialized threads that the +// CefProcess spins up. +// +// Applications must initialize the COM library before they can call +// COM library functions other than CoGetMalloc and memory allocation +// functions, so this class initializes COM for those users. +class CefProcessUIThread + : public net::NetworkChangeNotifier::ConnectionTypeObserver, + public CefThread { + public: + CefProcessUIThread(); + explicit CefProcessUIThread(MessageLoop* message_loop); + virtual ~CefProcessUIThread(); + + virtual void Init(); + virtual void CleanUp(); + + private: + void PlatformInit(); + void PlatformCleanUp(); + + // From net::NetworkChangeNotifier::ConnectionTypeObserver + virtual void OnConnectionTypeChanged( + net::NetworkChangeNotifier::ConnectionType type); + + base::StatsTable* statstable_; + + // WebKit implementation class. + BrowserWebKitInit* webkit_init_; + + scoped_ptr network_change_notifier_; + + scoped_refptr blocking_pool_; + + DISALLOW_COPY_AND_ASSIGN(CefProcessUIThread); +}; + +#endif // CEF_LIBCEF_CEF_PROCESS_UI_THREAD_H_ diff --git a/cef1/libcef/cef_process_ui_thread_gtk.cc b/cef1/libcef/cef_process_ui_thread_gtk.cc new file mode 100644 index 000000000..40b1593fe --- /dev/null +++ b/cef1/libcef/cef_process_ui_thread_gtk.cc @@ -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. + +#include "libcef/cef_process_ui_thread.h" +#include "libcef/browser_impl.h" + +void CefProcessUIThread::PlatformInit() { +} + +void CefProcessUIThread::PlatformCleanUp() { +} + diff --git a/cef1/libcef/cef_process_ui_thread_mac.mm b/cef1/libcef/cef_process_ui_thread_mac.mm new file mode 100644 index 000000000..0ef7ebfaa --- /dev/null +++ b/cef1/libcef/cef_process_ui_thread_mac.mm @@ -0,0 +1,24 @@ +// Copyright (c) 2010 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 + +#import "include/cef_application_mac.h" +#include "libcef/cef_process_ui_thread.h" +#include "libcef/browser_webkit_glue.h" +#include "libcef/cef_context.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" + +void CefProcessUIThread::PlatformInit() { + // The NSApplication instance must implement the CefAppProtocol protocol. + DCHECK([[NSApplication sharedApplication] + conformsToProtocol:@protocol(CefAppProtocol)]); + + // On Mac, the select popup menus are rendered by the browser. + WebKit::WebView::setUseExternalPopupMenus(true); +} + +void CefProcessUIThread::PlatformCleanUp() { +} diff --git a/cef1/libcef/cef_process_ui_thread_win.cc b/cef1/libcef/cef_process_ui_thread_win.cc new file mode 100644 index 000000000..206f52731 --- /dev/null +++ b/cef1/libcef/cef_process_ui_thread_win.cc @@ -0,0 +1,54 @@ +// Copyright (c) 2010 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. + +#include "libcef/cef_process_ui_thread.h" + +#include +#include + +#include "libcef/browser_impl.h" + +void CefProcessUIThread::PlatformInit() { + 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 window class + WNDCLASSEX wcex = { + /* cbSize = */ sizeof(WNDCLASSEX), + /* style = */ CS_HREDRAW | CS_VREDRAW, + /* lpfnWndProc = */ CefBrowserImpl::WndProc, + /* cbClsExtra = */ 0, + /* cbWndExtra = */ 0, + /* hInstance = */ ::GetModuleHandle(NULL), + /* hIcon = */ NULL, + /* hCursor = */ LoadCursor(NULL, IDC_ARROW), + /* hbrBackground = */ 0, + /* lpszMenuName = */ NULL, + /* lpszClassName = */ CefBrowserImpl::GetWndClass(), + /* hIconSm = */ NULL, + }; + RegisterClassEx(&wcex); +} + +void CefProcessUIThread::PlatformCleanUp() { + // Uninitialize COM stuff + OleUninitialize(); + + // Closes the COM library on the current thread. CoInitialize must + // be balanced by a corresponding call to CoUninitialize. + CoUninitialize(); +} + diff --git a/cef1/libcef/cef_string_list.cc b/cef1/libcef/cef_string_list.cc new file mode 100644 index 000000000..fbc2b2ce1 --- /dev/null +++ b/cef1/libcef/cef_string_list.cc @@ -0,0 +1,58 @@ +// 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); + DCHECK(value); + 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/cef1/libcef/cef_string_map.cc b/cef1/libcef/cef_string_map.cc new file mode 100644 index 000000000..9538ab05e --- /dev/null +++ b/cef1/libcef/cef_string_map.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/cef1/libcef/cef_string_multimap.cc b/cef1/libcef/cef_string_multimap.cc new file mode 100644 index 000000000..1daf4a8a9 --- /dev/null +++ b/cef1/libcef/cef_string_multimap.cc @@ -0,0 +1,116 @@ +// 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/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/cef1/libcef/cef_string_types.cc b/cef1/libcef/cef_string_types.cc new file mode 100644 index 000000000..cf82d381f --- /dev/null +++ b/cef1/libcef/cef_string_types.cc @@ -0,0 +1,269 @@ +// 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 "base/logging.h" +#include "base/string16.h" +#include "base/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; +} + +} // 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 = 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 = 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) { + string16 str; + bool ret = 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 = 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) { + string16 str; + bool ret = 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 = 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) { + 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) { + string16 str = 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/cef1/libcef/cef_thread.cc b/cef1/libcef/cef_thread.cc new file mode 100644 index 000000000..58194e02a --- /dev/null +++ b/cef1/libcef/cef_thread.cc @@ -0,0 +1,261 @@ +// Copyright (c) 2010 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. + +#include "libcef/cef_thread.h" + +#include "base/compiler_specific.h" +#include "base/message_loop.h" +#include "base/message_loop_proxy.h" + +#if defined(OS_WIN) +#include // NOLINT(build/include_order) +#endif + +using base::MessageLoopProxy; + +// Friendly names for the well-known threads. +static const char* cef_thread_names[CefThread::ID_COUNT] = { + "Cef_UIThread", // UI + "Cef_FileThread", // FILE + "Cef_IOThread", // IO +}; + +// An implementation of MessageLoopProxy to be used in conjunction +// with CefThread. +class CefThreadMessageLoopProxy : public MessageLoopProxy { + public: + explicit CefThreadMessageLoopProxy(CefThread::ID identifier) + : id_(identifier) { + } + + // TaskRunner implementation. + virtual bool PostDelayedTask(const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms) OVERRIDE { + return CefThread::PostDelayedTask(id_, from_here, task, delay_ms); + } + + virtual bool PostDelayedTask(const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) OVERRIDE { + return CefThread::PostDelayedTask(id_, from_here, task, delay); + } + + // SequencedTaskRunner implementation. + virtual bool PostNonNestableDelayedTask( + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms) OVERRIDE { + return CefThread::PostNonNestableDelayedTask(id_, from_here, task, + delay_ms); + } + + virtual bool PostNonNestableDelayedTask( + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) OVERRIDE { + return CefThread::PostNonNestableDelayedTask(id_, from_here, task, delay); + } + + virtual bool RunsTasksOnCurrentThread() const OVERRIDE { + return CefThread::CurrentlyOn(id_); + } + + private: + CefThread::ID id_; + DISALLOW_COPY_AND_ASSIGN(CefThreadMessageLoopProxy); +}; + + +base::Lock CefThread::lock_; + +CefThread* CefThread::cef_threads_[ID_COUNT]; + +CefThread::CefThread(CefThread::ID identifier) + : Thread(cef_thread_names[identifier]), + identifier_(identifier) { + Initialize(); +} + +CefThread::CefThread(ID identifier, MessageLoop* message_loop) + : Thread(cef_thread_names[identifier]), + identifier_(identifier) { + message_loop->set_thread_name(cef_thread_names[identifier]); + set_message_loop(message_loop); + Initialize(); +} + +void CefThread::Init() { +#if defined(OS_WIN) + // Initializes the COM library on the current thread. + CoInitialize(NULL); +#endif + +#if defined(OS_MACOSX) + autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool); +#endif +} + +void CefThread::Cleanup() { +#if defined(OS_WIN) + // Closes the COM library on the current thread. CoInitialize must + // be balanced by a corresponding call to CoUninitialize. + CoUninitialize(); +#endif + +#if defined(OS_MACOSX) + autorelease_pool_.reset(NULL); +#endif +} + +void CefThread::Initialize() { + base::AutoLock lock(lock_); + DCHECK(identifier_ >= 0 && identifier_ < ID_COUNT); + DCHECK(cef_threads_[identifier_] == NULL); + cef_threads_[identifier_] = this; +} + +CefThread::~CefThread() { + // Stop the thread here, instead of the parent's class destructor. This is so + // that if there are pending tasks that run, code that checks that it's on the + // correct CefThread succeeds. + Stop(); + + base::AutoLock lock(lock_); + cef_threads_[identifier_] = NULL; +#ifndef NDEBUG + // Double check that the threads are ordererd correctly in the enumeration. + for (int i = identifier_ + 1; i < ID_COUNT; ++i) { + DCHECK(!cef_threads_[i]) << + "Threads must be listed in the reverse order that they die"; + } +#endif +} + +// static +bool CefThread::IsWellKnownThread(ID identifier) { + base::AutoLock lock(lock_); + return (identifier >= 0 && identifier < ID_COUNT && + cef_threads_[identifier]); +} + +// static +bool CefThread::CurrentlyOn(ID identifier) { + base::AutoLock lock(lock_); + DCHECK(identifier >= 0 && identifier < ID_COUNT); + return cef_threads_[identifier] && + cef_threads_[identifier]->message_loop() == MessageLoop::current(); +} + +// static +bool CefThread::PostTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task) { + return PostTaskHelper(identifier, from_here, task, 0, true); +} + +// static +bool CefThread::PostDelayedTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms) { + return PostTaskHelper(identifier, from_here, task, delay_ms, true); +} + +// static +bool CefThread::PostDelayedTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) { + return PostTaskHelper(identifier, from_here, task, delay.InMilliseconds(), + true); +} + +// static +bool CefThread::PostNonNestableTask( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task) { + return PostTaskHelper(identifier, from_here, task, 0, false); +} + +// static +bool CefThread::PostNonNestableDelayedTask( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms) { + return PostTaskHelper(identifier, from_here, task, delay_ms, false); +} + +// static +bool CefThread::PostNonNestableDelayedTask( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay) { + return PostTaskHelper(identifier, from_here, task, delay.InMilliseconds(), + false); +} + +// static +bool CefThread::GetCurrentThreadIdentifier(ID* identifier) { + MessageLoop* cur_message_loop = MessageLoop::current(); + for (int i = 0; i < ID_COUNT; ++i) { + if (cef_threads_[i] && + cef_threads_[i]->message_loop() == cur_message_loop) { + *identifier = cef_threads_[i]->identifier_; + return true; + } + } + + return false; +} + +// static +scoped_refptr CefThread::GetMessageLoopProxyForThread( + ID identifier) { + scoped_refptr proxy = + new CefThreadMessageLoopProxy(identifier); + return proxy; +} + +// static +bool CefThread::PostTaskHelper( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms, + bool nestable) { + DCHECK(identifier >= 0 && identifier < ID_COUNT); + // Optimization: to avoid unnecessary locks, we listed the ID enumeration in + // order of lifetime. So no need to lock if we know that the other thread + // outlives this one. + // Note: since the array is so small, ok to loop instead of creating a map, + // which would require a lock because std::map isn't thread safe, defeating + // the whole purpose of this optimization. + ID current_thread; + bool guaranteed_to_outlive_target_thread = + GetCurrentThreadIdentifier(¤t_thread) && + current_thread >= identifier; + + if (!guaranteed_to_outlive_target_thread) + lock_.Acquire(); + + MessageLoop* message_loop = cef_threads_[identifier] ? + cef_threads_[identifier]->message_loop() : NULL; + if (message_loop) { + if (nestable) { + message_loop->PostDelayedTask(from_here, task, delay_ms); + } else { + message_loop->PostNonNestableDelayedTask(from_here, task, delay_ms); + } + } + + if (!guaranteed_to_outlive_target_thread) + lock_.Release(); + + return !!message_loop; +} diff --git a/cef1/libcef/cef_thread.h b/cef1/libcef/cef_thread.h new file mode 100644 index 000000000..50eff6381 --- /dev/null +++ b/cef1/libcef/cef_thread.h @@ -0,0 +1,207 @@ +// Copyright (c) 2010 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. + +#ifndef CEF_LIBCEF_CEF_THREAD_H_ +#define CEF_LIBCEF_CEF_THREAD_H_ +#pragma once + +#include "base/memory/scoped_ptr.h" +#include "base/synchronization/lock.h" +#include "base/threading/thread.h" + +#if defined(OS_MACOSX) +#include "base/mac/scoped_nsautorelease_pool.h" +#endif + +namespace base { +class MessageLoopProxy; +} + +/////////////////////////////////////////////////////////////////////////////// +// CefThread +// +// This class represents a thread that is known by a browser-wide name. For +// example, there is one IO thread for the entire browser process, and various +// pieces of code find it useful to retrieve a pointer to the IO thread's +// Invoke a task by thread ID: +// +// CefThread::PostTask(CefThread::IO, FROM_HERE, task); +// +// The return value is false if the task couldn't be posted because the target +// thread doesn't exist. If this could lead to data loss, you need to check the +// result and restructure the code to ensure it doesn't occur. +// +// This class automatically handles the lifetime of different threads. +// It's always safe to call PostTask on any thread. If it's not yet created, +// the task is deleted. There are no race conditions. If the thread that the +// task is posted to is guaranteed to outlive the current thread, then no locks +// are used. You should never need to cache pointers to MessageLoops, since +// they're not thread safe. +class CefThread : public base::Thread { + public: + // An enumeration of the well-known threads. + // NOTE: threads must be listed in the order of their life-time, with each + // thread outliving every other thread below it. + enum ID { + // The main thread in the browser. + UI, + + // This is the thread that interacts with the file system. + FILE, + + // This is the thread that processes network and schema messages. + IO, + + // This identifier does not represent a thread. Instead it counts the + // number of well-known threads. Insert new well-known threads before this + // identifier. + ID_COUNT + }; + + // Construct a CefThread with the supplied identifier. It is an error + // to construct a CefThread that already exists. + explicit CefThread(ID identifier); + + // Special constructor for the main (UI) thread and unittests. We use a dummy + // thread here since the main thread already exists. + CefThread(ID identifier, MessageLoop* message_loop); + + virtual ~CefThread(); + + // These are the same methods in message_loop.h, but are guaranteed to either + // get posted to the MessageLoop if it's still alive, or be deleted otherwise. + // They return true iff the thread existed and the task was posted. Note that + // even if the task is posted, there's no guarantee that it will run, since + // the target thread may already have a Quit message in its queue. + static bool PostTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task); + static bool PostDelayedTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms); + static bool PostDelayedTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay); + static bool PostNonNestableTask(ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task); + static bool PostNonNestableDelayedTask( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms); + static bool PostNonNestableDelayedTask( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + base::TimeDelta delay); + + template + static bool DeleteSoon(ID identifier, + const tracked_objects::Location& from_here, + const T* object) { + return GetMessageLoopProxyForThread(identifier)->DeleteSoon( + from_here, object); + } + + template + static bool ReleaseSoon(ID identifier, + const tracked_objects::Location& from_here, + const T* object) { + return GetMessageLoopProxyForThread(identifier)->ReleaseSoon( + from_here, object); + } + + // Callable on any thread. Returns whether the given ID corresponds to a well + // known thread. + static bool IsWellKnownThread(ID identifier); + + // Callable on any thread. Returns whether you're currently on a particular + // thread. + static bool CurrentlyOn(ID identifier); + + // If the current message loop is one of the known threads, returns true and + // sets identifier to its ID. Otherwise returns false. + static bool GetCurrentThreadIdentifier(ID* identifier); + + // Callers can hold on to a refcounted MessageLoopProxy beyond the lifetime + // of the thread. + static scoped_refptr GetMessageLoopProxyForThread( + ID identifier); + + // Use these templates in conjuction with RefCountedThreadSafe when you want + // to ensure that an object is deleted on a specific thread. This is needed + // when an object can hop between threads (i.e. IO -> FILE -> IO), and thread + // switching delays can mean that the final IO tasks executes before the FILE + // task's stack unwinds. This would lead to the object destructing on the + // FILE thread, which often is not what you want (i.e. to unregister from + // NotificationService, to notify other objects on the creating thread etc). + template + struct DeleteOnThread { + template + static void Destruct(T* x) { + if (CurrentlyOn(thread)) { + delete x; + } else { + DeleteSoon(thread, FROM_HERE, x); + } + } + }; + + // Sample usage: + // class Foo + // : public base::RefCountedThreadSafe< + // Foo, CefThread::DeleteOnIOThread> { + // + // ... + // private: + // friend class CefThread; + // friend class DeleteTask; + // + // ~Foo(); + struct DeleteOnUIThread : public DeleteOnThread { }; + struct DeleteOnIOThread : public DeleteOnThread { }; + struct DeleteOnFileThread : public DeleteOnThread { }; + + protected: + virtual void Init(); + virtual void Cleanup(); + + private: + // Common initialization code for the constructors. + void Initialize(); + + static bool PostTaskHelper( + ID identifier, + const tracked_objects::Location& from_here, + const base::Closure& task, + int64 delay_ms, + bool nestable); + + // The identifier of this thread. Only one thread can exist with a given + // identifier at a given time. + ID identifier_; + + // This lock protects |cef_threads_|. Do not read or modify that array + // without holding this lock. Do not block while holding this lock. + static base::Lock lock_; + + // An array of the CefThread objects. This array is protected by |lock_|. + // The threads are not owned by this array. Typically, the threads are owned + // on the UI thread by the g_browser_process object. CefThreads remove + // themselves from this array upon destruction. + static CefThread* cef_threads_[ID_COUNT]; + +#if defined(OS_MACOSX) + scoped_ptr autorelease_pool_; +#endif +}; + +#define REQUIRE_UIT() DCHECK(CefThread::CurrentlyOn(CefThread::UI)) +#define REQUIRE_IOT() DCHECK(CefThread::CurrentlyOn(CefThread::IO)) + +#endif // CEF_LIBCEF_CEF_THREAD_H_ diff --git a/cef1/libcef/cef_time.cc b/cef1/libcef/cef_time.cc new file mode 100644 index 000000000..cc28c8dcd --- /dev/null +++ b/cef1/libcef/cef_time.cc @@ -0,0 +1,69 @@ +// 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/cef_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; +} diff --git a/cef1/libcef/cef_time_util.h b/cef1/libcef/cef_time_util.h new file mode 100644 index 000000000..7996ff0ef --- /dev/null +++ b/cef1/libcef/cef_time_util.h @@ -0,0 +1,16 @@ +// 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_LIBCEF_CEF_TIME_UTIL_H_ +#define CEF_LIBCEF_CEF_TIME_UTIL_H_ +#pragma once + +#include "include/internal/cef_time.h" +#include "base/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_CEF_TIME_UTIL_H_ diff --git a/cef1/libcef/command_line_impl.cc b/cef1/libcef/command_line_impl.cc new file mode 100644 index 000000000..2cd304016 --- /dev/null +++ b/cef1/libcef/command_line_impl.cc @@ -0,0 +1,115 @@ +// 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_command_line.h" +#include "base/command_line.h" +#include "base/file_path.h" +#include "base/logging.h" + +namespace { + +class CefCommandLineImpl : public CefCommandLine { + public: + CefCommandLineImpl() + : command_line_(CommandLine::NO_PROGRAM) { + } + + virtual void InitFromArgv(int argc, const char* const* argv) OVERRIDE { +#if !defined(OS_WIN) + AutoLock lock_scope(this); + command_line_.InitFromArgv(argc, argv); +#else + NOTREACHED() << "method not supported on this platform"; +#endif + } + + virtual void InitFromString(const CefString& command_line) OVERRIDE { +#if defined(OS_WIN) + AutoLock lock_scope(this); + command_line_.ParseFromString(command_line); +#else + NOTREACHED() << "method not supported on this platform"; +#endif + } + + virtual CefString GetCommandLineString() OVERRIDE { + AutoLock lock_scope(this); + return command_line_.GetCommandLineString(); + } + + virtual CefString GetProgram() OVERRIDE { + AutoLock lock_scope(this); + return command_line_.GetProgram().value(); + } + + virtual void SetProgram(const CefString& program) OVERRIDE { + AutoLock lock_scope(this); + command_line_.SetProgram(FilePath(program)); + } + + virtual bool HasSwitches() OVERRIDE { + AutoLock lock_scope(this); + return (command_line_.GetSwitches().size() > 0); + } + + virtual bool HasSwitch(const CefString& name) OVERRIDE { + AutoLock lock_scope(this); + return command_line_.HasSwitch(name); + } + + virtual CefString GetSwitchValue(const CefString& name) OVERRIDE { + AutoLock lock_scope(this); + return command_line_.GetSwitchValueNative(name); + } + + virtual void GetSwitches(SwitchMap& switches) OVERRIDE { + AutoLock lock_scope(this); + const CommandLine::SwitchMap& map = command_line_.GetSwitches(); + CommandLine::SwitchMap::const_iterator it = map.begin(); + for (; it != map.end(); ++it) + switches.insert(std::make_pair(it->first, it->second)); + } + + virtual void AppendSwitch(const CefString& name) OVERRIDE { + AutoLock lock_scope(this); + command_line_.AppendSwitch(name); + } + + virtual void AppendSwitchWithValue(const CefString& name, + const CefString& value) OVERRIDE { + AutoLock lock_scope(this); + command_line_.AppendSwitchNative(name, value); + } + + virtual bool HasArguments() OVERRIDE { + AutoLock lock_scope(this); + return (command_line_.GetArgs().size() > 0); + } + + virtual void GetArguments(ArgumentList& arguments) OVERRIDE { + AutoLock lock_scope(this); + const CommandLine::StringVector& vec = command_line_.GetArgs(); + CommandLine::StringVector::const_iterator it = vec.begin(); + for (; it != vec.end(); ++it) + arguments.push_back(*it); + } + + virtual void AppendArgument(const CefString& argument) OVERRIDE { + AutoLock lock_scope(this); + command_line_.AppendArgNative(argument); + } + + private: + CommandLine command_line_; + + IMPLEMENT_REFCOUNTING(CefCommandLineImpl); + IMPLEMENT_LOCKING(CefCommandLineImpl); +}; + +} // namespace + +// static +CefRefPtr CefCommandLine::CreateCommandLine() { + return new CefCommandLineImpl(); +} diff --git a/cef1/libcef/cookie_manager_impl.cc b/cef1/libcef/cookie_manager_impl.cc new file mode 100644 index 000000000..e872110c6 --- /dev/null +++ b/cef1/libcef/cookie_manager_impl.cc @@ -0,0 +1,282 @@ +// 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/cookie_manager_impl.h" + +#include + +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" +#include "libcef/cef_time_util.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "chrome/browser/net/sqlite_persistent_cookie_store.h" + +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) { + 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::CookieMonster::CanonicalCookie& cc = *(it); + + 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.DoesExpire(); + if (cookie.has_expires) + cef_time_from_basetime(cc.ExpiryDate(), cookie.expires); + + bool deleteCookie = false; + bool keepLooping = visitor_->Visit(cookie, count, total, deleteCookie); + if (deleteCookie) { + cookie_monster_->DeleteCanonicalCookieAsync(cc, + net::CookieMonster::DeleteCookieCallback()); + } + if (!keepLooping) + break; + } + } + + private: + scoped_refptr cookie_monster_; + CefRefPtr visitor_; +}; + +} // namespace + + +CefCookieManagerImpl::CefCookieManagerImpl(bool is_global) + : is_global_(is_global) { + if (is_global) { + cookie_monster_ = + static_cast( + _Context->request_context()->cookie_store()); + DCHECK(cookie_monster_); + } +} + +CefCookieManagerImpl::~CefCookieManagerImpl() { +} + +void CefCookieManagerImpl::SetSupportedSchemes( + const std::vector& schemes) { + if (CefThread::CurrentlyOn(CefThread::IO)) { + if (schemes.empty()) + return; + + std::set scheme_set; + std::vector::const_iterator it = schemes.begin(); + for (; it != 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. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(&CefCookieManagerImpl::SetSupportedSchemes, + this, schemes)); + } +} + +bool CefCookieManagerImpl::VisitAllCookies( + CefRefPtr visitor) { + if (CefThread::CurrentlyOn(CefThread::IO)) { + scoped_refptr callback( + new VisitCookiesCallback(cookie_monster_, visitor)); + + cookie_monster_->GetAllCookiesAsync( + base::Bind(&VisitCookiesCallback::Run, callback.get())); + } else { + // Execute on the IO thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitAllCookies), + this, visitor)); + } + + return true; +} + +bool CefCookieManagerImpl::VisitUrlCookies( + const CefString& url, bool includeHttpOnly, + CefRefPtr visitor) { + if (CefThread::CurrentlyOn(CefThread::IO)) { + net::CookieOptions options; + if (includeHttpOnly) + options.set_include_httponly(); + + scoped_refptr callback( + new VisitCookiesCallback(cookie_monster_, visitor)); + + GURL gurl = GURL(url.ToString()); + cookie_monster_->GetAllCookiesForURLWithOptionsAsync(gurl, options, + base::Bind(&VisitCookiesCallback::Run, callback.get())); + } else { + // Execute on the IO thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::VisitUrlCookies), + this, url, includeHttpOnly, visitor)); + } + + return true; +} + +bool CefCookieManagerImpl::SetCookie(const CefString& url, + const CefCookie& cookie) { + // Verify that this function is being called on the IO thread. + if (!CefThread::CurrentlyOn(CefThread::IO)) { + NOTREACHED() << "called on invalid thread"; + 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, cookie.httponly, + net::CookieStore::SetCookiesCallback()); + return true; +} + +bool CefCookieManagerImpl::DeleteCookies(const CefString& url, + const CefString& cookie_name) { + // Verify that this function is being called on the IO thread. + if (!CefThread::CurrentlyOn(CefThread::IO)) { + NOTREACHED() << "called on invalid thread"; + 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) { + if (CefThread::CurrentlyOn(CefThread::IO)) { + FilePath new_path; + if (!path.empty()) + new_path = FilePath(path); + + if (is_global_) { + // Global path changes are handled by the request context. + _Context->request_context()->SetCookieStoragePath(new_path); + cookie_monster_ = + static_cast( + _Context->request_context()->cookie_store()); + return true; + } + + if (cookie_monster_ && ((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()) { + if (!file_util::PathExists(new_path) && + !file_util::CreateDirectory(new_path)) { + NOTREACHED() << "Failed to create cookie storage directory"; + new_path.clear(); + } else { + FilePath cookie_path = new_path.Append(FILE_PATH_LITERAL("Cookies")); + persistent_store = + new SQLitePersistentCookieStore(cookie_path, false, NULL); + } + } + + // 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); + storage_path_ = new_path; + } else { + // Execute on the IO thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(base::IgnoreResult(&CefCookieManagerImpl::SetStoragePath), + this, path)); + } + + 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; + } + + return new CefCookieManagerImpl(true); +} + +// static +CefRefPtr CefCookieManager::CreateManager( + const CefString& path) { + // 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->SetStoragePath(path); + return manager; +} diff --git a/cef1/libcef/cookie_manager_impl.h b/cef1/libcef/cookie_manager_impl.h new file mode 100644 index 000000000..643309610 --- /dev/null +++ b/cef1/libcef/cookie_manager_impl.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. + +#ifndef CEF_LIBCEF_COOKIE_IMPL_H_ +#define CEF_LIBCEF_COOKIE_IMPL_H_ + +#include "include/cef_cookie.h" +#include "base/file_path.h" +#include "net/cookies/cookie_monster.h" + +// Implementation of the CefCookieManager interface. +class CefCookieManagerImpl : public CefCookieManager { + public: + CefCookieManagerImpl(bool is_global); + + ~CefCookieManagerImpl(); + + // 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) OVERRIDE; + + net::CookieMonster* cookie_monster() { return cookie_monster_; } + + private: + scoped_refptr cookie_monster_; + bool is_global_; + FilePath storage_path_; + + IMPLEMENT_REFCOUNTING(CefCookieManagerImpl); +}; + +#endif // CEF_LIBCEF_COOKIE_IMPL_H_ diff --git a/cef1/libcef/cookie_store_proxy.cc b/cef1/libcef/cookie_store_proxy.cc new file mode 100644 index 000000000..6fca65928 --- /dev/null +++ b/cef1/libcef/cookie_store_proxy.cc @@ -0,0 +1,98 @@ +// 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/cookie_store_proxy.h" + +#include + +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/cookie_manager_impl.h" + +#include "base/logging.h" + + +CefCookieStoreProxy::CefCookieStoreProxy(CefBrowserImpl* browser) + : browser_(browser) { + DCHECK(browser_); +} + +void CefCookieStoreProxy::SetCookieWithOptionsAsync( + const GURL& url, + const std::string& cookie_line, + const net::CookieOptions& options, + const SetCookiesCallback& callback) { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->SetCookieWithOptionsAsync(url, cookie_line, options, callback); +} + +void CefCookieStoreProxy::GetCookiesWithOptionsAsync( + const GURL& url, const net::CookieOptions& options, + const GetCookiesCallback& callback) { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->GetCookiesWithOptionsAsync(url, options, callback); +} + +void CefCookieStoreProxy::GetCookiesWithInfoAsync( + const GURL& url, + const net::CookieOptions& options, + const GetCookieInfoCallback& callback) { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->GetCookiesWithInfoAsync(url, options, callback); +} + +void CefCookieStoreProxy::DeleteCookieAsync( + const GURL& url, + const std::string& cookie_name, + const base::Closure& callback) { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteCookieAsync(url, cookie_name, callback); +} + +void CefCookieStoreProxy::DeleteAllCreatedBetweenAsync( + const base::Time& delete_begin, + const base::Time& delete_end, + const DeleteCallback& callback) { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteAllCreatedBetweenAsync(delete_begin, delete_end, + callback); +} + +void CefCookieStoreProxy::DeleteSessionCookiesAsync( + const DeleteCallback& callback) { + scoped_refptr cookie_store = GetCookieStore(); + cookie_store->DeleteSessionCookiesAsync(callback); +} + +net::CookieMonster* CefCookieStoreProxy::GetCookieMonster() { + scoped_refptr cookie_store = GetCookieStore(); + return cookie_store->GetCookieMonster(); +} + +net::CookieStore* CefCookieStoreProxy::GetCookieStore() { + scoped_refptr cookie_store; + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetRequestHandler(); + if (handler.get()) { + // Get the manager from the handler. + CefRefPtr manager = + handler->GetCookieManager(browser_, browser_->pending_url().spec()); + if (manager.get()) { + cookie_store = + reinterpret_cast( + manager.get())->cookie_monster(); + } + } + } + + if (!cookie_store) { + // Use the global cookie store. + cookie_store = _Context->request_context()->cookie_store(); + } + + DCHECK(cookie_store); + return cookie_store; +} diff --git a/cef1/libcef/cookie_store_proxy.h b/cef1/libcef/cookie_store_proxy.h new file mode 100644 index 000000000..5a8bd79b3 --- /dev/null +++ b/cef1/libcef/cookie_store_proxy.h @@ -0,0 +1,48 @@ +// 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_COOKIE_STORE_PROXY_H_ +#define CEF_LIBCEF_COOKIE_STORE_PROXY_H_ +#pragma once + +#include "net/cookies/cookie_store.h" + +class CefBrowserImpl; + +// Handles cookie requests from the network stack. +class CefCookieStoreProxy : public net::CookieStore { + public: + explicit CefCookieStoreProxy(CefBrowserImpl* browser); + + // net::CookieStore methods. + virtual void SetCookieWithOptionsAsync( + const GURL& url, + const std::string& cookie_line, + const net::CookieOptions& options, + const SetCookiesCallback& callback) OVERRIDE; + virtual void GetCookiesWithOptionsAsync( + const GURL& url, const net::CookieOptions& options, + const GetCookiesCallback& callback) OVERRIDE; + void GetCookiesWithInfoAsync( + const GURL& url, + const net::CookieOptions& options, + const GetCookieInfoCallback& callback) OVERRIDE; + virtual void DeleteCookieAsync(const GURL& url, + const std::string& cookie_name, + const base::Closure& callback) OVERRIDE; + virtual void DeleteAllCreatedBetweenAsync(const base::Time& delete_begin, + const base::Time& delete_end, + const DeleteCallback& callback) + OVERRIDE; + virtual void DeleteSessionCookiesAsync(const DeleteCallback& callback) + OVERRIDE; + virtual net::CookieMonster* GetCookieMonster() OVERRIDE; + + private: + net::CookieStore* GetCookieStore(); + + CefBrowserImpl* browser_; +}; + +#endif // CEF_LIBCEF_COOKIE_STORE_PROXY_H_ diff --git a/cef1/libcef/dom_document_impl.cc b/cef1/libcef/dom_document_impl.cc new file mode 100644 index 000000000..3b5095582 --- /dev/null +++ b/cef1/libcef/dom_document_impl.cc @@ -0,0 +1,262 @@ +// 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/dom_document_impl.h" +#include "libcef/dom_node_impl.h" +#include "libcef/cef_thread.h" + +#include "base/logging.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebRange.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" + +using WebKit::WebDocument; +using WebKit::WebElement; +using WebKit::WebFrame; +using WebKit::WebNode; +using WebKit::WebRange; +using WebKit::WebString; +using WebKit::WebURL; + + +CefDOMDocumentImpl::CefDOMDocumentImpl(CefBrowserImpl* browser, + WebFrame* frame) + : browser_(browser), + frame_(frame) { + const WebDocument& document = frame_->document(); + DCHECK(!document.isNull()); +} + +CefDOMDocumentImpl::~CefDOMDocumentImpl() { + REQUIRE_UIT(); + + // 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(string16(id))); +} + +CefRefPtr CefDOMDocumentImpl::GetFocusedNode() { + const WebDocument& document = frame_->document(); + return GetOrCreateNode(document.focusedNode()); +} + +bool CefDOMDocumentImpl::HasSelection() { + if (!VerifyContext()) + return false; + + return frame_->hasSelection(); +} + +CefRefPtr CefDOMDocumentImpl::GetSelectionStartNode() { + if (!VerifyContext() || !frame_->hasSelection()) + return NULL; + + const WebRange& range = frame_->selectionRange(); + if (range.isNull()) + return NULL; + + int exceptionCode; + return GetOrCreateNode(range.startContainer(exceptionCode)); +} + +int CefDOMDocumentImpl::GetSelectionStartOffset() { + if (!VerifyContext() || !frame_->hasSelection()) + return 0; + + const WebRange& range = frame_->selectionRange(); + if (range.isNull()) + return 0; + + return range.startOffset(); +} + +CefRefPtr CefDOMDocumentImpl::GetSelectionEndNode() { + if (!VerifyContext() || !frame_->hasSelection()) + return NULL; + + const WebRange& range = frame_->selectionRange(); + if (range.isNull()) + return NULL; + + int exceptionCode; + return GetOrCreateNode(range.endContainer(exceptionCode)); +} + +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(string16(partialURL)); + if (!url.isNull()) { + GURL gurl = url; + str = gurl.spec(); + } + + return str; +} + +CefRefPtr CefDOMDocumentImpl::GetOrCreateNode( + const WebKit::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)); + return nodeImpl; +} + +void CefDOMDocumentImpl::RemoveNode(const WebKit::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_EQ(GetRefCt(), 1); + + 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 (!CefThread::CurrentlyOn(CefThread::UI) || frame_ == NULL) { + NOTREACHED(); + return false; + } + return true; +} diff --git a/cef1/libcef/dom_document_impl.h b/cef1/libcef/dom_document_impl.h new file mode 100644 index 000000000..54296ac31 --- /dev/null +++ b/cef1/libcef/dom_document_impl.h @@ -0,0 +1,65 @@ +// 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_LIBCEF_DOM_DOCUMENT_IMPL_H_ +#define CEF_LIBCEF_DOM_DOCUMENT_IMPL_H_ +#pragma once + +#include +#include "include/cef_dom.h" + +namespace WebKit { +class WebFrame; +class WebNode; +}; + +class CefBrowserImpl; + +class CefDOMDocumentImpl : public CefDOMDocument { + public: + CefDOMDocumentImpl(CefBrowserImpl* browser, + WebKit::WebFrame* frame); + virtual ~CefDOMDocumentImpl(); + + 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 CefRefPtr GetSelectionStartNode() OVERRIDE; + virtual int GetSelectionStartOffset() OVERRIDE; + virtual CefRefPtr GetSelectionEndNode() OVERRIDE; + virtual int GetSelectionEndOffset() OVERRIDE; + virtual CefString GetSelectionAsMarkup() OVERRIDE; + virtual CefString GetSelectionAsText() OVERRIDE; + virtual CefString GetBaseURL() OVERRIDE; + virtual CefString GetCompleteURL(const CefString& partialURL) OVERRIDE; + + CefBrowserImpl* GetBrowser() { return browser_; } + WebKit::WebFrame* GetFrame() { return frame_; } + + // The document maintains a map of all existing node objects. + CefRefPtr GetOrCreateNode(const WebKit::WebNode& node); + void RemoveNode(const WebKit::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_; + WebKit::WebFrame* frame_; + + typedef std::map NodeMap; + NodeMap node_map_; + + IMPLEMENT_REFCOUNTING(CefDOMDocumentImpl); +}; + +#endif // CEF_LIBCEF_DOM_DOCUMENT_IMPL_H_ diff --git a/cef1/libcef/dom_event_impl.cc b/cef1/libcef/dom_event_impl.cc new file mode 100644 index 000000000..8be8a6eb5 --- /dev/null +++ b/cef1/libcef/dom_event_impl.cc @@ -0,0 +1,160 @@ +// 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/dom_event_impl.h" +#include "libcef/cef_thread.h" +#include "libcef/dom_document_impl.h" + +#include "base/logging.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" + +using WebKit::WebDOMEvent; +using WebKit::WebString; + + +CefDOMEventImpl::CefDOMEventImpl(CefRefPtr document, + const WebKit::WebDOMEvent& event) + : document_(document), + event_(event) { + DCHECK(!event_.isNull()); +} + +CefDOMEventImpl::~CefDOMEventImpl() { + REQUIRE_UIT(); + DCHECK(event_.isNull()); +} + +CefString CefDOMEventImpl::GetType() { + CefString str; + if (!VerifyContext()) + return str; + + const WebString& type = event_.type(); + if (!type.isNull()) + str = type; + + return str; +} + +CefDOMEventImpl::Category CefDOMEventImpl::GetCategory() { + if (!VerifyContext()) + return DOM_EVENT_CATEGORY_UNKNOWN; + + int flags = 0; + if (event_.isUIEvent()) + flags |= DOM_EVENT_CATEGORY_UI; + if (event_.isMouseEvent()) + flags |= DOM_EVENT_CATEGORY_MOUSE; + if (event_.isMutationEvent()) + flags |= DOM_EVENT_CATEGORY_MUTATION; + if (event_.isKeyboardEvent()) + flags |= DOM_EVENT_CATEGORY_KEYBOARD; + if (event_.isTextEvent()) + flags |= DOM_EVENT_CATEGORY_TEXT; + if (event_.isCompositionEvent()) + flags |= DOM_EVENT_CATEGORY_COMPOSITION; + if (event_.isDragEvent()) + flags |= DOM_EVENT_CATEGORY_DRAG; + if (event_.isClipboardEvent()) + flags |= DOM_EVENT_CATEGORY_CLIPBOARD; + if (event_.isMessageEvent()) + flags |= DOM_EVENT_CATEGORY_MESSAGE; + if (event_.isWheelEvent()) + flags |= DOM_EVENT_CATEGORY_WHEEL; + if (event_.isBeforeTextInsertedEvent()) + flags |= DOM_EVENT_CATEGORY_BEFORE_TEXT_INSERTED; + if (event_.isOverflowEvent()) + flags |= DOM_EVENT_CATEGORY_OVERFLOW; + if (event_.isPageTransitionEvent()) + flags |= DOM_EVENT_CATEGORY_PAGE_TRANSITION; + if (event_.isPopStateEvent()) + flags |= DOM_EVENT_CATEGORY_POPSTATE; + if (event_.isProgressEvent()) + flags |= DOM_EVENT_CATEGORY_PROGRESS; + if (event_.isXMLHttpRequestProgressEvent()) + flags |= DOM_EVENT_CATEGORY_XMLHTTPREQUEST_PROGRESS; + if (event_.isWebKitAnimationEvent()) + flags |= DOM_EVENT_CATEGORY_WEBKIT_ANIMATION; + if (event_.isWebKitTransitionEvent()) + flags |= DOM_EVENT_CATEGORY_WEBKIT_TRANSITION; + if (event_.isBeforeLoadEvent()) + flags |= DOM_EVENT_CATEGORY_BEFORE_LOAD; + + return static_cast(flags); +} + +CefDOMEventImpl::Phase CefDOMEventImpl::GetPhase() { + if (!VerifyContext()) + return DOM_EVENT_PHASE_UNKNOWN; + + switch (event_.eventPhase()) { + case WebDOMEvent::CapturingPhase: + return DOM_EVENT_PHASE_CAPTURING; + case WebDOMEvent::AtTarget: + return DOM_EVENT_PHASE_AT_TARGET; + case WebDOMEvent::BubblingPhase: + return DOM_EVENT_PHASE_BUBBLING; + } + + return DOM_EVENT_PHASE_UNKNOWN; +} + +bool CefDOMEventImpl::CanBubble() { + if (!VerifyContext()) + return false; + + return event_.bubbles(); +} + +bool CefDOMEventImpl::CanCancel() { + if (!VerifyContext()) + return false; + + return event_.cancelable(); +} + +CefRefPtr CefDOMEventImpl::GetDocument() { + if (!VerifyContext()) + return NULL; + + return document_.get(); +} + +CefRefPtr CefDOMEventImpl::GetTarget() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(event_.target()); +} + +CefRefPtr CefDOMEventImpl::GetCurrentTarget() { + if (!VerifyContext()) + return NULL; + + return document_->GetOrCreateNode(event_.currentTarget()); +} + +void CefDOMEventImpl::Detach() { + // If you hit this assert it means that you are keeping references to this + // event object beyond the valid scope. + DCHECK_EQ(GetRefCt(), 1); + + document_ = NULL; + event_.assign(WebDOMEvent()); +} + +bool CefDOMEventImpl::VerifyContext() { + if (!document_.get()) { + NOTREACHED(); + return false; + } + if (!document_->VerifyContext()) + return false; + if (event_.isNull()) { + NOTREACHED(); + return false; + } + return true; +} diff --git a/cef1/libcef/dom_event_impl.h b/cef1/libcef/dom_event_impl.h new file mode 100644 index 000000000..4b57af4bb --- /dev/null +++ b/cef1/libcef/dom_event_impl.h @@ -0,0 +1,42 @@ +// 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_LIBCEF_DOM_EVENT_IMPL_H_ +#define CEF_LIBCEF_DOM_EVENT_IMPL_H_ +#pragma once + +#include "include/cef_dom.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEvent.h" + +class CefDOMDocumentImpl; + +class CefDOMEventImpl : public CefDOMEvent { + public: + CefDOMEventImpl(CefRefPtr document, + const WebKit::WebDOMEvent& event); + virtual ~CefDOMEventImpl(); + + virtual CefString GetType() OVERRIDE; + virtual Category GetCategory() OVERRIDE; + virtual Phase GetPhase() OVERRIDE; + virtual bool CanBubble() OVERRIDE; + virtual bool CanCancel() OVERRIDE; + virtual CefRefPtr GetDocument() OVERRIDE; + virtual CefRefPtr GetTarget() OVERRIDE; + virtual CefRefPtr GetCurrentTarget() OVERRIDE; + + // Will be called from CefDOMEventListenerWrapper::handleEvent(). + void Detach(); + + // Verify that the object exists and is being accessed on the UI thread. + bool VerifyContext(); + + protected: + CefRefPtr document_; + WebKit::WebDOMEvent event_; + + IMPLEMENT_REFCOUNTING(CefDOMEventImpl); +}; + +#endif // CEF_LIBCEF_DOM_EVENT_IMPL_H_ diff --git a/cef1/libcef/dom_node_impl.cc b/cef1/libcef/dom_node_impl.cc new file mode 100644 index 000000000..73fdf78cf --- /dev/null +++ b/cef1/libcef/dom_node_impl.cc @@ -0,0 +1,459 @@ +// 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/dom_node_impl.h" +#include "libcef/browser_impl.h" +#include "libcef/cef_thread.h" +#include "libcef/dom_document_impl.h" +#include "libcef/dom_event_impl.h" +#include "libcef/tracker.h" + +#include "base/logging.h" +#include "base/string_util.h" +#include "base/utf_string_conversions.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDOMEventListener.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebElement.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFormControlElement.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputElement.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSelectElement.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" + +using WebKit::WebDocument; +using WebKit::WebDOMEvent; +using WebKit::WebDOMEventListener; +using WebKit::WebElement; +using WebKit::WebFrame; +using WebKit::WebFormControlElement; +using WebKit::WebInputElement; +using WebKit::WebNode; +using WebKit::WebSelectElement; +using WebKit::WebString; + +namespace { + +// Wrapper implementation for WebDOMEventListener. +class CefDOMEventListenerWrapper : public WebDOMEventListener, + public CefTrackNode { + public: + CefDOMEventListenerWrapper(CefBrowserImpl* browser, WebFrame* frame, + CefRefPtr listener) + : browser_(browser), + frame_(frame), + listener_(listener) { + // Cause this object to be deleted immediately before the frame is closed. + browser->UIT_AddFrameObject(frame, this); + } + virtual ~CefDOMEventListenerWrapper() { + REQUIRE_UIT(); + } + + virtual void handleEvent(const WebDOMEvent& event) { + CefRefPtr documentImpl; + CefRefPtr eventImpl; + + if (!event.isNull()) { + // Create CefDOMDocumentImpl and CefDOMEventImpl objects that are valid + // only for the scope of this method. + const WebDocument& document = frame_->document(); + if (!document.isNull()) { + documentImpl = new CefDOMDocumentImpl(browser_, frame_); + eventImpl = new CefDOMEventImpl(documentImpl, event); + } + } + + listener_->HandleEvent(eventImpl.get()); + + if (eventImpl.get()) + eventImpl->Detach(); + if (documentImpl.get()) + documentImpl->Detach(); + } + + protected: + CefBrowserImpl* browser_; + WebFrame* frame_; + CefRefPtr listener_; +}; + +} // namespace + + +CefDOMNodeImpl::CefDOMNodeImpl(CefRefPtr document, + const WebKit::WebNode& node) + : document_(document), + node_(node) { +} + +CefDOMNodeImpl::~CefDOMNodeImpl() { + REQUIRE_UIT(); + + 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::EntityReferenceNode: + return DOM_NODE_TYPE_ENTITY_REFERENCE; + case WebNode::EntityNode: + return DOM_NODE_TYPE_ENTITY; + 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; + case WebNode::NotationNode: + return DOM_NODE_TYPE_NOTATION; + case WebNode::XPathNamespaceNode: + return DOM_NODE_TYPE_XPATH_NAMESPACE; + 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(); +} + +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 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(); + + string16 value; + const string16& form_control_type = formElement.formControlType(); + if (form_control_type == ASCIIToUTF16("text")) { + const WebInputElement& input_element = + formElement.toConst(); + value = input_element.value(); + } else if (form_control_type == ASCIIToUTF16("select-one")) { + const WebSelectElement& select_element = + formElement.toConst(); + value = select_element.value(); + } + + TrimWhitespace(value, 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 node_.setNodeValue(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()); +} + +void CefDOMNodeImpl::AddEventListener(const CefString& eventType, + CefRefPtr listener, + bool useCapture) { + if (!VerifyContext()) + return; + + node_.addEventListener(string16(eventType), + new CefDOMEventListenerWrapper(document_->GetBrowser(), + document_->GetFrame(), listener), + useCapture); +} + +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(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(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) { + string16 name = element.attributeLocalName(i); + 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(string16(attrName), 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/cef1/libcef/dom_node_impl.h b/cef1/libcef/dom_node_impl.h new file mode 100644 index 000000000..e98d1d2b1 --- /dev/null +++ b/cef1/libcef/dom_node_impl.h @@ -0,0 +1,62 @@ +// 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_LIBCEF_DOM_NODE_IMPL_H_ +#define CEF_LIBCEF_DOM_NODE_IMPL_H_ +#pragma once + +#include "include/cef_dom.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebNode.h" + +class CefDOMDocumentImpl; + +class CefDOMNodeImpl : public CefDOMNode { + public: + CefDOMNodeImpl(CefRefPtr document, + const WebKit::WebNode& node); + virtual ~CefDOMNodeImpl(); + + virtual Type GetType() OVERRIDE; + virtual bool IsText() OVERRIDE; + virtual bool IsElement() 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 void AddEventListener(const CefString& eventType, + CefRefPtr listener, + bool useCapture) 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; + + // 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_; + WebKit::WebNode node_; + + IMPLEMENT_REFCOUNTING(CefDOMNodeImpl); +}; + +#endif // CEF_LIBCEF_DOM_NODE_IMPL_H_ diff --git a/cef1/libcef/download_util.cc b/cef1/libcef/download_util.cc new file mode 100644 index 000000000..28831ab92 --- /dev/null +++ b/cef1/libcef/download_util.cc @@ -0,0 +1,189 @@ +// 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. + +#include "libcef/download_util.h" + +#include "base/file_path.h" +#include "base/string16.h" +#include "base/string_util.h" +#include "base/sys_string_conversions.h" +#include "base/utf_string_conversions.h" +#include "base/threading/thread.h" +#include "base/threading/thread_restrictions.h" +#include "googleurl/src/gurl.h" +#include "net/base/mime_util.h" +#include "net/base/net_util.h" + +namespace { + +#if defined(OS_WIN) +// Returns whether the specified extension is automatically integrated into the +// windows shell. +// From chrome/browser/download/download_util.cc +bool IsShellIntegratedExtension(const string16& extension) { + string16 extension_lower = StringToLowerASCII(extension); + + static const wchar_t* const integrated_extensions[] = { + // See . + L"local", + // Right-clicking on shortcuts can be magical. + L"lnk", + }; + + for (int i = 0; i < arraysize(integrated_extensions); ++i) { + if (extension_lower == integrated_extensions[i]) + return true; + } + + // See . + // That vulnerability report is not exactly on point, but files become magical + // if their end in a CLSID. Here we block extensions that look like CLSIDs. + if (extension_lower.size() > 0 && extension_lower.at(0) == L'{' && + extension_lower.at(extension_lower.length() - 1) == L'}') + return true; + + return false; +} + +// Returns whether the specified file name is a reserved name on windows. +// This includes names like "com2.zip" (which correspond to devices) and +// desktop.ini and thumbs.db which have special meaning to the windows shell. +// From chrome/browser/download/download_util.cc +bool IsReservedName(const string16& filename) { + // This list is taken from the MSDN article "Naming a file" + // http://msdn2.microsoft.com/en-us/library/aa365247(VS.85).aspx + // I also added clock$ because GetSaveFileName seems to consider it as a + // reserved name too. + static const wchar_t* const known_devices[] = { + L"con", L"prn", L"aux", L"nul", L"com1", L"com2", L"com3", L"com4", L"com5", + L"com6", L"com7", L"com8", L"com9", L"lpt1", L"lpt2", L"lpt3", L"lpt4", + L"lpt5", L"lpt6", L"lpt7", L"lpt8", L"lpt9", L"clock$" + }; + string16 filename_lower = StringToLowerASCII(filename); + + for (int i = 0; i < arraysize(known_devices); ++i) { + // Exact match. + if (filename_lower == known_devices[i]) + return true; + // Starts with "DEVICE.". + if (filename_lower.find(string16(known_devices[i]) + L".") == 0) + return true; + } + + static const wchar_t* const magic_names[] = { + // These file names are used by the "Customize folder" feature of the shell. + L"desktop.ini", + L"thumbs.db", + }; + + for (int i = 0; i < arraysize(magic_names); ++i) { + if (filename_lower == magic_names[i]) + return true; + } + + return false; +} +#endif // OS_WIN + +// Create an extension based on the file name and mime type. +// From chrome/browser/download/download_util.cc +void GenerateExtension(const FilePath& file_name, + const std::string& mime_type, + FilePath::StringType* generated_extension) { + // We're worried about two things here: + // + // 1) Usability. If the site fails to provide a file extension, we want to + // guess a reasonable file extension based on the content type. + // + // 2) Shell integration. Some file extensions automatically integrate with + // the shell. We block these extensions to prevent a malicious web site + // from integrating with the user's shell. + + // See if our file name already contains an extension. + FilePath::StringType extension = file_name.Extension(); + if (!extension.empty()) + extension.erase(extension.begin()); // Erase preceding '.'. + +#if defined(OS_WIN) + static const FilePath::CharType default_extension[] = + FILE_PATH_LITERAL("download"); + + // Rename shell-integrated extensions. + if (IsShellIntegratedExtension(extension)) + extension.assign(default_extension); +#endif + + if (extension.empty()) { + // The GetPreferredExtensionForMimeType call will end up going to disk. Do + // this on another thread to avoid slowing the IO thread. + // http://crbug.com/61827 + base::ThreadRestrictions::ScopedAllowIO allow_io; + net::GetPreferredExtensionForMimeType(mime_type, &extension); + } + + generated_extension->swap(extension); +} + +// Used to make sure we have a safe file extension and filename for a +// download. |file_name| can either be just the file name or it can be a +// full path to a file. +// From chrome/browser/download/download_util.cc +void GenerateSafeFileName(const std::string& mime_type, FilePath* file_name) { + // Make sure we get the right file extension + FilePath::StringType extension; + GenerateExtension(*file_name, mime_type, &extension); + *file_name = file_name->ReplaceExtension(extension); + +#if defined(OS_WIN) + // Prepend "_" to the file name if it's a reserved name + FilePath::StringType leaf_name = file_name->BaseName().value(); + DCHECK(!leaf_name.empty()); + if (IsReservedName(leaf_name)) { + leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name; + *file_name = file_name->DirName(); + if (file_name->value() == FilePath::kCurrentDirectory) { + *file_name = FilePath(leaf_name); + } else { + *file_name = file_name->Append(leaf_name); + } + } +#endif +} + +} // namespace + +namespace download_util { + +// Create a file name based on the response from the server. +// From chrome/browser/download/download_util.cc +void GenerateFileName(const GURL& url, + const std::string& content_disposition, + const std::string& referrer_charset, + const std::string& mime_type, + const std::string& suggested_name, + FilePath* generated_name) { + string16 new_name = net::GetSuggestedFilename(GURL(url), + content_disposition, + referrer_charset, + suggested_name, + mime_type, + "download"); + + // TODO(evan): this code is totally wrong -- we should just generate + // Unicode filenames and do all this encoding switching at the end. + // However, I'm just shuffling wrong code around, at least not adding + // to it. +#if defined(OS_WIN) + *generated_name = FilePath(new_name); +#else + *generated_name = FilePath(base::SysWideToNativeMB(UTF16ToWide(new_name))); +#endif + + DCHECK(!generated_name->empty()); + + GenerateSafeFileName(mime_type, generated_name); +} + +} // namespace download_util diff --git a/cef1/libcef/download_util.h b/cef1/libcef/download_util.h new file mode 100644 index 000000000..c2d45afe5 --- /dev/null +++ b/cef1/libcef/download_util.h @@ -0,0 +1,27 @@ +// 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. + +#ifndef CEF_LIBCEF_DOWNLOAD_UTIL_H_ +#define CEF_LIBCEF_DOWNLOAD_UTIL_H_ +#pragma once + +#include + +class GURL; +class FilePath; + +namespace download_util { + +// Create a file name based on the response from the server. +void GenerateFileName(const GURL& url, + const std::string& content_disposition, + const std::string& referrer_charset, + const std::string& mime_type, + const std::string& suggested_name, + FilePath* generated_name); + +} // namespace download_util + +#endif // CEF_LIBCEF_DOWNLOAD_UTIL_H_ diff --git a/cef1/libcef/drag_data_impl.cc b/cef1/libcef/drag_data_impl.cc new file mode 100644 index 000000000..00be5e75a --- /dev/null +++ b/cef1/libcef/drag_data_impl.cc @@ -0,0 +1,63 @@ +// 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/drag_data_impl.h" +#include "base/file_path.h" + +CefDragDataImpl::CefDragDataImpl(const WebDropData& data) + : data_(data) { +} + +bool CefDragDataImpl::IsLink() { + return (data_.url.is_valid() && data_.file_description_filename.empty()); +} + +bool CefDragDataImpl::IsFragment() { + return (!data_.url.is_valid() && data_.file_description_filename.empty() && + data_.filenames.empty()); +} + +bool CefDragDataImpl::IsFile() { + return (!data_.file_description_filename.empty() || !data_.filenames.empty()); +} + +CefString CefDragDataImpl::GetLinkURL() { + return data_.url.spec(); +} + +CefString CefDragDataImpl::GetLinkTitle() { + return data_.url_title; +} + +CefString CefDragDataImpl::GetLinkMetadata() { + return data_.download_metadata; +} + +CefString CefDragDataImpl::GetFragmentText() { + return data_.text.is_null() ? CefString() : CefString(data_.text.string()); +} + +CefString CefDragDataImpl::GetFragmentHtml() { + return data_.html.is_null() ? CefString() : CefString(data_.html.string()); +} + +CefString CefDragDataImpl::GetFragmentBaseURL() { + return data_.html_base_url.spec(); +} + +CefString CefDragDataImpl::GetFileName() { + return data_.file_description_filename; +} + +bool CefDragDataImpl::GetFileNames(std::vector& names) { + 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); + + return true; +} diff --git a/cef1/libcef/drag_data_impl.h b/cef1/libcef/drag_data_impl.h new file mode 100644 index 000000000..b3c0c0ca8 --- /dev/null +++ b/cef1/libcef/drag_data_impl.h @@ -0,0 +1,37 @@ +// 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_LIBCEF_DRAG_DATA_IMPL_H_ +#define CEF_LIBCEF_DRAG_DATA_IMPL_H_ +#pragma once + +#include + +#include "include/cef_drag_data.h" +#include "webkit/glue/webdropdata.h" + +// Implementation of CefDragData. +class CefDragDataImpl : public CefDragData { + public: + explicit CefDragDataImpl(const WebDropData& data); + + virtual bool IsLink(); + virtual bool IsFragment(); + virtual bool IsFile(); + virtual CefString GetLinkURL(); + virtual CefString GetLinkTitle(); + virtual CefString GetLinkMetadata(); + virtual CefString GetFragmentText(); + virtual CefString GetFragmentHtml(); + virtual CefString GetFragmentBaseURL(); + virtual CefString GetFileName(); + virtual bool GetFileNames(std::vector& names); + + protected: + WebDropData data_; + + IMPLEMENT_REFCOUNTING(CefDragDataImpl); +}; + +#endif // CEF_LIBCEF_DRAG_DATA_IMPL_H_ diff --git a/cef1/libcef/drag_download_file.cc b/cef1/libcef/drag_download_file.cc new file mode 100644 index 000000000..5e979a8f9 --- /dev/null +++ b/cef1/libcef/drag_download_file.cc @@ -0,0 +1,160 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2009-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 "libcef/drag_download_file.h" +#include "libcef/browser_impl.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "base/file_util.h" +#include "base/message_loop.h" +#include "net/base/file_stream.h" + +DragDownloadFile::DragDownloadFile( + const FilePath& file_name_or_path, + linked_ptr file_stream, + const GURL& url, + const GURL& referrer, + const std::string& referrer_encoding, + BrowserWebViewDelegate* view) + : file_stream_(file_stream), + url_(url), + referrer_(referrer), + referrer_encoding_(referrer_encoding), + view_(view), + drag_message_loop_(MessageLoop::current()), + is_started_(false), + is_successful_(false) { +#if defined(OS_WIN) + DCHECK(!file_name_or_path.empty() && !file_stream.get()); + file_name_ = file_name_or_path; +#elif defined(OS_POSIX) + DCHECK(!file_name_or_path.empty() && file_stream.get()); + file_path_ = file_name_or_path; +#endif +} + +DragDownloadFile::~DragDownloadFile() { + AssertCurrentlyOnDragThread(); + + // Since the target application can still hold and use the dragged file, + // we do not know the time that it can be safely deleted. To solve this + // problem, we schedule it to be removed after the system is restarted. +#if defined(OS_WIN) + if (!temp_dir_path_.empty()) { + if (!file_path_.empty()) + file_util::DeleteAfterReboot(file_path_); + file_util::DeleteAfterReboot(temp_dir_path_); + } +#endif +} + +bool DragDownloadFile::Start(ui::DownloadFileObserver* observer) { + AssertCurrentlyOnDragThread(); + + if (is_started_) + return true; + is_started_ = true; + + DCHECK(!observer_.get()); + observer_ = observer; + + if (!file_stream_.get()) { + // Create a temporary directory to save the temporary download file. We do + // not want to use the default download directory since we do not want the + // twisted file name shown in the download shelf if the file with the same + // name already exists. + if (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("chrome"), + &temp_dir_path_)) + return false; + + file_path_ = temp_dir_path_.Append(file_name_); + } + + InitiateDownload(); + + // On Windows, we need to wait till the download file is completed. +#if defined(OS_WIN) + StartNestedMessageLoop(); +#endif + + return is_successful_; +} + +void DragDownloadFile::Stop() { +} + +void DragDownloadFile::InitiateDownload() { +#if defined(OS_WIN) + // DownloadManager could only be invoked from the UI thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&DragDownloadFile::InitiateDownload, this)); + return; + } +#endif + + // TODO(cef): You seem to have found an example of HTML5 drag and drop + // download. Please report it to the CEF developers so that we can add support + // for it. + NOTREACHED(); + bool is_successful = false; + DownloadCompleted(is_successful); +} + +void DragDownloadFile::DownloadCompleted(bool is_successful) { +#if defined(OS_WIN) + // If not in drag-and-drop thread, defer the running to it. + if (drag_message_loop_ != MessageLoop::current()) { + drag_message_loop_->PostTask( + FROM_HERE, + base::Bind(&DragDownloadFile::DownloadCompleted, this, is_successful)); + return; + } +#endif + + is_successful_ = is_successful; + + // On Windows, we need to stop the waiting. +#if defined(OS_WIN) + QuitNestedMessageLoop(); +#endif +} + +void DragDownloadFile::AssertCurrentlyOnDragThread() { + // Only do the check on Windows where two threads are involved. +#if defined(OS_WIN) + DCHECK(drag_message_loop_ == MessageLoop::current()); +#endif +} + +void DragDownloadFile::AssertCurrentlyOnUIThread() { + // Only do the check on Windows where two threads are involved. +#if defined(OS_WIN) + DCHECK(CefThread::CurrentlyOn(CefThread::UI)); +#endif +} + +#if defined(OS_WIN) +void DragDownloadFile::StartNestedMessageLoop() { + AssertCurrentlyOnDragThread(); + + bool old_state = MessageLoop::current()->NestableTasksAllowed(); + MessageLoop::current()->SetNestableTasksAllowed(true); + is_running_nested_message_loop_ = true; + MessageLoop::current()->Run(); + MessageLoop::current()->SetNestableTasksAllowed(old_state); +} + +void DragDownloadFile::QuitNestedMessageLoop() { + AssertCurrentlyOnDragThread(); + + if (is_running_nested_message_loop_) { + is_running_nested_message_loop_ = false; + MessageLoop::current()->Quit(); + } +} +#endif diff --git a/cef1/libcef/drag_download_file.h b/cef1/libcef/drag_download_file.h new file mode 100644 index 000000000..7640176ee --- /dev/null +++ b/cef1/libcef/drag_download_file.h @@ -0,0 +1,98 @@ +// Copyright (c) 2011 The Chromium Embedded Framework Authors. +// Portions copyright (c) 2009-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. + +#ifndef CEF_LIBCEF_DRAG_DOWNLOAD_FILE_H_ +#define CEF_LIBCEF_DRAG_DOWNLOAD_FILE_H_ +#pragma once + +#include + +#include "base/file_path.h" +#include "base/memory/linked_ptr.h" +#include "base/message_loop.h" +#include "googleurl/src/gurl.h" +#include "ui/base/dragdrop/download_file_interface.h" + +class BrowserWebViewDelegate; + +namespace net { +class FileStream; +} + +class DragDownloadFile : public ui::DownloadFileProvider { + public: + // On Windows, we need to download into a temporary file. Two threads are + // involved: background drag-and-drop thread and UI thread. + // The first parameter file_name_or_path should contain file name while the + // second parameter file_stream should be NULL. + // + // On MacOSX, we need to download into a file stream that has already been + // created. Only UI thread is involved. + // The file path and file stream should be provided as the first two + // parameters. + DragDownloadFile(const FilePath& file_name_or_path, + linked_ptr file_stream, + const GURL& url, + const GURL& referrer, + const std::string& referrer_encoding, + BrowserWebViewDelegate* view); + + // DownloadFileProvider methods. + // Called on drag-and-drop thread (Windows). + // Called on UI thread (MacOSX). + virtual bool Start(ui::DownloadFileObserver* observer); + virtual void Stop(); +#if defined(OS_WIN) + virtual IStream* GetStream() { return NULL; } +#endif + + private: + // Called on drag-and-drop thread (Windows). + // Called on UI thread (Windows). + virtual ~DragDownloadFile(); + + // Called on drag-and-drop thread (Windows only). +#if defined(OS_WIN) + void StartNestedMessageLoop(); + void QuitNestedMessageLoop(); +#endif + + // Called on either drag-and-drop thread or UI thread (Windows). + // Called on UI thread (MacOSX). + void InitiateDownload(); + void DownloadCompleted(bool is_successful); + + // Helper methods to make sure we're in the correct thread. + void AssertCurrentlyOnDragThread(); + void AssertCurrentlyOnUIThread(); + + // Initialized on drag-and-drop thread. Accessed on either thread after that + // (Windows). + // Accessed on UI thread (MacOSX). + FilePath file_path_; + FilePath file_name_; + linked_ptr file_stream_; + GURL url_; + GURL referrer_; + std::string referrer_encoding_; + BrowserWebViewDelegate* view_; + MessageLoop* drag_message_loop_; + FilePath temp_dir_path_; + + // Accessed on drag-and-drop thread (Windows). + // Accessed on UI thread (MacOSX). + bool is_started_; + bool is_successful_; + scoped_refptr observer_; + + // Accessed on drag-and-drop thread (Windows only). +#if defined(OS_WIN) + bool is_running_nested_message_loop_; +#endif + + DISALLOW_COPY_AND_ASSIGN(DragDownloadFile); +}; + +#endif // CEF_LIBCEF_DRAG_DOWNLOAD_FILE_H_ diff --git a/cef1/libcef/drag_download_util.cc b/cef1/libcef/drag_download_util.cc new file mode 100644 index 000000000..f64872f86 --- /dev/null +++ b/cef1/libcef/drag_download_util.cc @@ -0,0 +1,113 @@ +// 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/cef_thread.h" +#include "libcef/drag_download_util.h" + +#include "base/bind.h" +#include "base/string_util.h" +#include "base/file_path.h" +#include "base/file_util.h" +#include "base/memory/scoped_ptr.h" +#include "base/string_number_conversions.h" +#include "base/utf_string_conversions.h" +#include "googleurl/src/gurl.h" +#include "net/base/file_stream.h" +#include "net/base/net_errors.h" + +using net::FileStream; + +namespace drag_download_util { + +bool ParseDownloadMetadata(const string16& metadata, + string16* mime_type, + FilePath* file_name, + GURL* url) { + const char16 separator = L':'; + + size_t mime_type_end_pos = metadata.find(separator); + if (mime_type_end_pos == string16::npos) + return false; + + size_t file_name_end_pos = metadata.find(separator, mime_type_end_pos + 1); + if (file_name_end_pos == string16::npos) + return false; + + GURL parsed_url = GURL(metadata.substr(file_name_end_pos + 1)); + if (!parsed_url.is_valid()) + return false; + + if (mime_type) + *mime_type = metadata.substr(0, mime_type_end_pos); + if (file_name) { + string16 file_name_str = metadata.substr( + mime_type_end_pos + 1, file_name_end_pos - mime_type_end_pos - 1); +#if defined(OS_WIN) + *file_name = FilePath(file_name_str); +#else + *file_name = FilePath(UTF16ToUTF8(file_name_str)); +#endif + } + if (url) + *url = parsed_url; + + return true; +} + +FileStream* CreateFileStreamForDrop(FilePath* file_path) { + DCHECK(file_path && !file_path->empty()); + + scoped_ptr file_stream(new FileStream(NULL)); + const int kMaxSeq = 99; + for (int seq = 0; seq <= kMaxSeq; seq++) { + FilePath new_file_path; + if (seq == 0) { + new_file_path = *file_path; + } else { +#if defined(OS_WIN) + string16 suffix = ASCIIToUTF16("-") + base::IntToString16(seq); +#else + std::string suffix = std::string("-") + base::IntToString(seq); +#endif + new_file_path = file_path->InsertBeforeExtension(suffix); + } + + // Explicitly (and redundantly check) for file -- despite the fact that our + // open won't overwrite -- just to avoid log spew. + if (!file_util::PathExists(new_file_path) && + file_stream->OpenSync(new_file_path, base::PLATFORM_FILE_CREATE | + base::PLATFORM_FILE_WRITE) == net::OK) { + *file_path = new_file_path; + return file_stream.release(); + } + } + + return NULL; +} + +PromiseFileFinalizer::PromiseFileFinalizer( + DragDownloadFile* drag_file_downloader) + : drag_file_downloader_(drag_file_downloader) { +} + +PromiseFileFinalizer::~PromiseFileFinalizer() {} + +void PromiseFileFinalizer::Cleanup() { + if (drag_file_downloader_.get()) + drag_file_downloader_ = NULL; +} + +void PromiseFileFinalizer::OnDownloadCompleted(const FilePath& file_path) { + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&PromiseFileFinalizer::Cleanup, this)); +} + +void PromiseFileFinalizer::OnDownloadAborted() { + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&PromiseFileFinalizer::Cleanup, this)); +} + +} // namespace drag_download_util diff --git a/cef1/libcef/drag_download_util.h b/cef1/libcef/drag_download_util.h new file mode 100644 index 000000000..e698ffc09 --- /dev/null +++ b/cef1/libcef/drag_download_util.h @@ -0,0 +1,63 @@ +// 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_DRAG_DOWNLOAD_UTIL_H_ +#define CEF_LIBCEF_DRAG_DOWNLOAD_UTIL_H_ +#pragma once + +#include "libcef/drag_download_file.h" + +#include "base/basictypes.h" +#include "base/memory/ref_counted.h" +#include "base/string16.h" +#include "ui/base/dragdrop/download_file_interface.h" + +class FilePath; +class GURL; +namespace net { +class FileStream; +} + +namespace drag_download_util { + +// Parse the download metadata set in DataTransfer.setData. The metadata +// consists of a set of the following values separated by ":" +// * MIME type +// * File name +// * URL +// If the file name contains special characters, they need to be escaped +// appropriately. +// For example, we can have +// text/plain:example.txt:http://example.com/example.txt +bool ParseDownloadMetadata(const string16& metadata, + string16* mime_type, + FilePath* file_name, + GURL* url); + +// Create a new file at the specified path. If the file already exists, try to +// insert the sequential unifier to produce a new file, like foo-01.txt. +// Return a FileStream if successful. +net::FileStream* CreateFileStreamForDrop(FilePath* file_path); + +// Implementation of DownloadFileObserver to finalize the download process. +class PromiseFileFinalizer : public ui::DownloadFileObserver { + public: + explicit PromiseFileFinalizer(DragDownloadFile* drag_file_downloader); + virtual ~PromiseFileFinalizer(); + + // DownloadFileObserver methods. + virtual void OnDownloadCompleted(const FilePath& file_path); + virtual void OnDownloadAborted(); + + private: + void Cleanup(); + + scoped_refptr drag_file_downloader_; + + DISALLOW_COPY_AND_ASSIGN(PromiseFileFinalizer); +}; + +} // namespace drag_download_util + +#endif // CEF_LIBCEF_DRAG_DOWNLOAD_UTIL_H_ diff --git a/cef1/libcef/external_popup_menu_mac.h b/cef1/libcef/external_popup_menu_mac.h new file mode 100644 index 000000000..7beb29096 --- /dev/null +++ b/cef1/libcef/external_popup_menu_mac.h @@ -0,0 +1,38 @@ +// Copyright (c) 2011 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. + +#ifndef CEF_LIBCEF_EXTERNAL_POPUP_MENU_MAC_H_ +#define CEF_LIBCEF_EXTERNAL_POPUP_MENU_MAC_H_ +#pragma once + +#include "base/basictypes.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebExternalPopupMenu.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenuInfo.h" + +class BrowserWebViewDelegate; +namespace WebKit { +class WebExternalPopupMenuClient; +} + +class ExternalPopupMenu : public WebKit::WebExternalPopupMenu { + public: + ExternalPopupMenu(BrowserWebViewDelegate* delegate, + const WebKit::WebPopupMenuInfo& popup_menu_info, + WebKit::WebExternalPopupMenuClient* popup_menu_client); + virtual ~ExternalPopupMenu() {} + + // WebKit::WebExternalPopupMenu implementation: + virtual void show(const WebKit::WebRect& bounds); + virtual void close(); + + private: + BrowserWebViewDelegate* delegate_; + WebKit::WebPopupMenuInfo popup_menu_info_; + WebKit::WebExternalPopupMenuClient* popup_menu_client_; + + DISALLOW_COPY_AND_ASSIGN(ExternalPopupMenu); +}; + +#endif // CEF_LIBCEF_EXTERNAL_POPUP_MENU_MAC_H_ diff --git a/cef1/libcef/external_popup_menu_mac.mm b/cef1/libcef/external_popup_menu_mac.mm new file mode 100644 index 000000000..b895598c9 --- /dev/null +++ b/cef1/libcef/external_popup_menu_mac.mm @@ -0,0 +1,90 @@ +// Copyright (c) 2011 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. + +#include "libcef/external_popup_menu_mac.h" +#include "libcef/browser_impl.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebExternalPopupMenuClient.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenuInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "webkit/glue/webmenurunner_mac.h" + +ExternalPopupMenu::ExternalPopupMenu( + BrowserWebViewDelegate* delegate, + const WebKit::WebPopupMenuInfo& popup_menu_info, + WebKit::WebExternalPopupMenuClient* popup_menu_client) + : delegate_(delegate), + popup_menu_info_(popup_menu_info), + popup_menu_client_(popup_menu_client) { +} + +void ExternalPopupMenu::show(const WebKit::WebRect& bounds) { + // Display a HTML select menu. + + std::vector items; + for (size_t i = 0; i < popup_menu_info_.items.size(); ++i) + items.push_back(popup_menu_info_.items[i]); + + double font_size = popup_menu_info_.itemFontSize; + int selected_index = popup_menu_info_.selectedIndex; + bool right_aligned = popup_menu_info_.rightAligned; + + CefBrowserImpl* browser = delegate_->GetBrowser(); + + NSView* view = nil; + NSRect view_rect; + + if (!browser->IsWindowRenderingDisabled()) { + view = browser->UIT_GetWebViewWndHandle(); + view_rect = [view bounds]; + } else { + view = browser->UIT_GetMainWndHandle(); + if (view != nil) { + CefRefPtr client = browser->GetClient(); + if (client.get()) { + // Retrieve the view rect. + CefRect rect; + CefRefPtr render_handler = client->GetRenderHandler(); + if (render_handler.get() && + render_handler->GetViewRect(browser, rect)) { + view_rect = NSMakeRect(rect.x, rect.y, rect.width, rect.height); + } + } + } + } + + if (view == nil || view_rect.size.width == 0 || view_rect.size.height == 0) { + popup_menu_client_->didCancel(); + delegate_->ClosePopupMenu(); + return; + } + + // Set up the menu position. + int y_offset = bounds.y + bounds.height; + NSRect position = NSMakeRect(bounds.x, view_rect.size.height - y_offset, + bounds.width, bounds.height); + + // Display the menu. + scoped_nsobject menu_runner; + menu_runner.reset([[WebMenuRunner alloc] initWithItems:items + fontSize:font_size + rightAligned:right_aligned]); + + [menu_runner runMenuInView:view + withBounds:position + initialIndex:selected_index]; + + if ([menu_runner menuItemWasChosen]) + popup_menu_client_->didAcceptIndex([menu_runner indexOfSelectedItem]); + else + popup_menu_client_->didCancel(); + + delegate_->ClosePopupMenu(); +} + +void ExternalPopupMenu::close() { + popup_menu_client_ = NULL; + delegate_ = NULL; +} diff --git a/cef1/libcef/external_protocol_handler.h b/cef1/libcef/external_protocol_handler.h new file mode 100644 index 000000000..67f94387b --- /dev/null +++ b/cef1/libcef/external_protocol_handler.h @@ -0,0 +1,23 @@ +// 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_LIBCEF_EXTERNAL_PROTOCOL_HANDLER_H_ +#define CEF_LIBCEF_EXTERNAL_PROTOCOL_HANDLER_H_ +#pragma once + +#include + +class GURL; + +namespace ExternalProtocolHandler { + +// Returns true if the OS provides external support for the specified |scheme|. +bool HasExternalHandler(const std::string& scheme); + +// Pass handling of the specified |gurl| to the OS. +bool HandleExternalProtocol(const GURL& gurl); + +} // namespace ExternalProtocolHandler + +#endif // CEF_LIBCEF_EXTERNAL_PROTOCOL_HANDLER_H_ diff --git a/cef1/libcef/external_protocol_handler_gtk.cc b/cef1/libcef/external_protocol_handler_gtk.cc new file mode 100644 index 000000000..7efb413eb --- /dev/null +++ b/cef1/libcef/external_protocol_handler_gtk.cc @@ -0,0 +1,17 @@ +// 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/external_protocol_handler.h" + +namespace ExternalProtocolHandler { + +bool HasExternalHandler(const std::string& scheme) { + return false; +} + +bool HandleExternalProtocol(const GURL& gurl) { + return false; +} + +} // namespace ExternalProtocolHandler diff --git a/cef1/libcef/external_protocol_handler_mac.mm b/cef1/libcef/external_protocol_handler_mac.mm new file mode 100644 index 000000000..7efb413eb --- /dev/null +++ b/cef1/libcef/external_protocol_handler_mac.mm @@ -0,0 +1,17 @@ +// 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/external_protocol_handler.h" + +namespace ExternalProtocolHandler { + +bool HasExternalHandler(const std::string& scheme) { + return false; +} + +bool HandleExternalProtocol(const GURL& gurl) { + return false; +} + +} // namespace ExternalProtocolHandler diff --git a/cef1/libcef/external_protocol_handler_win.cc b/cef1/libcef/external_protocol_handler_win.cc new file mode 100644 index 000000000..12f3a3fce --- /dev/null +++ b/cef1/libcef/external_protocol_handler_win.cc @@ -0,0 +1,53 @@ +// 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/external_protocol_handler.h" + +#include +#include + +#include "base/utf_string_conversions.h" +#include "base/win/registry.h" +#include "googleurl/src/gurl.h" + +namespace ExternalProtocolHandler { + +// 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 = + ASCIIToWide(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; +} + +bool HandleExternalProtocol(const GURL& gurl) { + if (!HasExternalHandler(gurl.scheme())) + return false; + + const std::string& address = gurl.spec(); + if (address.length() > kMaxAddressLengthChars) + return false; + + ShellExecuteA(NULL, "open", address.c_str(), NULL, NULL, SW_SHOWNORMAL); + + return true; +} + +} // namespace ExternalProtocolHandler diff --git a/cef1/libcef/http_header_utils.cc b/cef1/libcef/http_header_utils.cc new file mode 100644 index 000000000..1fb4648a6 --- /dev/null +++ b/cef1/libcef/http_header_utils.cc @@ -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. + +#include "libcef/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 + std::string headerStr = "HTTP/1.1 200 OK\n"; + headerStr += header_str; + scoped_refptr headers = + new HttpResponseHeaders(net::HttpUtil::AssembleRawHeaders( + headerStr.c_str(), headerStr.length())); + void* iter = NULL; + std::string name, value; + while (headers->EnumerateHeaderLines(&iter, &name, &value)) + map.insert(std::make_pair(name, value)); +} + +} // namespace HttpHeaderUtils diff --git a/cef1/libcef/http_header_utils.h b/cef1/libcef/http_header_utils.h new file mode 100644 index 000000000..c762d1347 --- /dev/null +++ b/cef1/libcef/http_header_utils.h @@ -0,0 +1,37 @@ +// 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_LIBCEF_HTTP_HEADER_UTILS_H_ +#define CEF_LIBCEF_HTTP_HEADER_UTILS_H_ +#pragma once + +#include + +#include "include/cef_request.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebHTTPHeaderVisitor.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" + +namespace HttpHeaderUtils { + +typedef CefRequest::HeaderMap HeaderMap; + +class HeaderVisitor : public WebKit::WebHTTPHeaderVisitor { + public: + explicit HeaderVisitor(HeaderMap* map) : map_(map) {} + + virtual void visitHeader(const WebKit::WebString& name, + const WebKit::WebString& value) { + map_->insert(std::make_pair(string16(name), string16(value))); + } + + private: + HeaderMap* map_; +}; + +std::string GenerateHeaders(const HeaderMap& map); +void ParseHeaders(const std::string& header_str, HeaderMap& map); + +}; // namespace HttpHeaderUtils + +#endif // CEF_LIBCEF_HTTP_HEADER_UTILS_H_ diff --git a/cef1/libcef/nplugin_impl.cc b/cef1/libcef/nplugin_impl.cc new file mode 100644 index 000000000..326e20089 --- /dev/null +++ b/cef1/libcef/nplugin_impl.cc @@ -0,0 +1,79 @@ +// 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_nplugin.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "base/string_split.h" +#include "base/utf_string_conversions.h" +#include "webkit/plugins/npapi/plugin_list.h" + +namespace { + +void UIT_RegisterPlugin(CefPluginInfo* plugin_info) { + REQUIRE_UIT(); + + webkit::WebPluginInfo info; + + info.path = FilePath(CefString(&plugin_info->unique_name)); + info.name = CefString(&plugin_info->display_name); + info.version = CefString(&plugin_info->version); + info.desc = CefString(&plugin_info->description); + + typedef std::vector VectorType; + VectorType mime_types, file_extensions, descriptions, file_extensions_parts; + base::SplitString(CefString(&plugin_info->mime_types), '|', &mime_types); + base::SplitString(CefString(&plugin_info->file_extensions), '|', + &file_extensions); + base::SplitString(CefString(&plugin_info->type_descriptions), '|', + &descriptions); + + for (size_t i = 0; i < mime_types.size(); ++i) { + webkit::WebPluginMimeType mimeType; + + mimeType.mime_type = mime_types[i]; + + if (file_extensions.size() > i) { + base::SplitString(file_extensions[i], ',', &file_extensions_parts); + VectorType::const_iterator it = file_extensions_parts.begin(); + for (; it != file_extensions_parts.end(); ++it) + mimeType.file_extensions.push_back(*(it)); + file_extensions_parts.clear(); + } + + if (descriptions.size() > i) + mimeType.description = UTF8ToUTF16(descriptions[i]); + + info.mime_types.push_back(mimeType); + } + + webkit::npapi::PluginEntryPoints entry_points; +#if !defined(OS_POSIX) || defined(OS_MACOSX) + entry_points.np_getentrypoints = plugin_info->np_getentrypoints; +#endif + entry_points.np_initialize = plugin_info->np_initialize; + entry_points.np_shutdown = plugin_info->np_shutdown; + + webkit::npapi::PluginList::Singleton()->RegisterInternalPluginWithEntryPoints( + info, true, entry_points); + + delete plugin_info; +} + +} // namespace + +bool CefRegisterPlugin(const CefPluginInfo& plugin_info) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return false; + } + + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(UIT_RegisterPlugin, new CefPluginInfo(plugin_info))); + + return true; +} diff --git a/cef1/libcef/origin_whitelist_impl.cc b/cef1/libcef/origin_whitelist_impl.cc new file mode 100644 index 000000000..548a09d72 --- /dev/null +++ b/cef1/libcef/origin_whitelist_impl.cc @@ -0,0 +1,102 @@ +// 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_origin_whitelist.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h" + +using WebKit::WebSecurityPolicy; +using WebKit::WebString; + +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 (CefThread::CurrentlyOn(CefThread::UI)) { + std::string target_protocol_str = target_protocol; + std::string target_domain_str = target_domain; + WebSecurityPolicy::addOriginAccessWhitelistEntry( + gurl, + WebString::fromUTF8(target_protocol_str), + WebString::fromUTF8(target_domain_str), + allow_target_subdomains); + } else { + CefThread::PostTask(CefThread::UI, FROM_HERE, + 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 (CefThread::CurrentlyOn(CefThread::UI)) { + std::string target_protocol_str = target_protocol; + std::string target_domain_str = target_domain; + WebSecurityPolicy::removeOriginAccessWhitelistEntry( + gurl, + WebString::fromUTF8(target_protocol_str), + WebString::fromUTF8(target_domain_str), + allow_target_subdomains); + } else { + CefThread::PostTask(CefThread::UI, FROM_HERE, + 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 (CefThread::CurrentlyOn(CefThread::UI)) { + WebSecurityPolicy::resetOriginAccessWhitelists(); + } else { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(base::IgnoreResult(&CefClearCrossOriginWhitelist))); + } + + return true; +} diff --git a/cef1/libcef/printing/print_settings.cc b/cef1/libcef/printing/print_settings.cc new file mode 100644 index 000000000..216b2e287 --- /dev/null +++ b/cef1/libcef/printing/print_settings.cc @@ -0,0 +1,266 @@ +// 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. + +#include "libcef/printing/print_settings.h" + +#include "base/atomic_sequence_num.h" +#include "base/logging.h" +#include "printing/units.h" + +namespace printing { + +// Global SequenceNumber used for generating unique cookie values. +static base::AtomicSequenceNumber cookie_seq; + +PageMeasurements::PageMeasurements() + : page_type(PT_LETTER), + page_length(0.0f), + page_width(0.0f) { +} + +void PageMeasurements::Clear() { + page_type = PT_LETTER; + page_length = 0.0f; + page_width = 0.0f; +} + +bool PageMeasurements::Equals(const PageMeasurements& rhs) const { + return page_type == rhs.page_type && + page_length == rhs.page_length && + page_width == rhs.page_width; +} + +PrintSettings::PrintSettings() + : min_shrink(1.25), + max_shrink(2.0), + desired_dpi(72), + selection_only(false), + to_file(false), + dpi_(0), + landscape(false) { + ResetRequestedPageMargins(); +} + +void PrintSettings::Clear() { + ranges.clear(); + min_shrink = 1.25; + max_shrink = 2.; + desired_dpi = 72; + selection_only = false; + to_file = false; + printer_name_.clear(); + device_name_.clear(); + page_setup_pixels_.Clear(); + dpi_ = 0; + landscape = false; + page_measurements.Clear(); + ResetRequestedPageMargins(); +} + +void PrintSettings::ResetRequestedPageMargins() { + // Initial requested margins to = 1.0cm = ~2/5 of inch + const int margin_printer_units = + ConvertUnit(1000, kHundrethsMMPerInch, desired_dpi); + // Initial requested header/footer margins to = 0.5cm = ~1/5 of inch + const int header_footer_margins = + ConvertUnit(500, kHundrethsMMPerInch, desired_dpi); + requested_margins.header = header_footer_margins; + requested_margins.footer = header_footer_margins; + requested_margins.left = margin_printer_units; + requested_margins.top = margin_printer_units; + requested_margins.right = margin_printer_units; + requested_margins.bottom = margin_printer_units; +} + +#ifdef WIN32 +void PrintSettings::Init(HDC hdc, + const DEVMODE& dev_mode, + const PageRanges& new_ranges, + const CefString& new_device_name, + bool print_selection_only, + bool print_to_file) { + DCHECK(hdc); + printer_name_ = std::wstring(dev_mode.dmDeviceName); + device_name_ = new_device_name; + ranges = new_ranges; + landscape = dev_mode.dmOrientation == DMORIENT_LANDSCAPE; + selection_only = print_selection_only; + to_file = print_to_file; + + bool is_custom_paper = true; + if (dev_mode.dmFields & DM_PAPERSIZE) { + switch (dev_mode.dmPaperSize) { + case DMPAPER_LETTER: + page_measurements.page_type = PT_LETTER; + is_custom_paper = false; + break; + case DMPAPER_LEGAL: + page_measurements.page_type = PT_LEGAL; + is_custom_paper = false; + break; + case DMPAPER_EXECUTIVE: + page_measurements.page_type = PT_EXECUTIVE; + is_custom_paper = false; + break; + case DMPAPER_A3: + page_measurements.page_type = PT_A3; + is_custom_paper = false; + break; + case DMPAPER_A4: + page_measurements.page_type = PT_A4; + is_custom_paper = false; + break; + default: + // We'll translate it as a custom paper size. + break; + } + } + + dpi_ = GetDeviceCaps(hdc, LOGPIXELSX); + // No printer device is known to advertise different dpi in X and Y axis; even + // the fax device using the 200x100 dpi setting. It's ought to break so many + // applications that it's not even needed to care about. WebKit doesn't + // support different dpi settings in X and Y axis. + DCHECK_EQ(dpi_, GetDeviceCaps(hdc, LOGPIXELSY)); + + DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORX), 0); + DCHECK_EQ(GetDeviceCaps(hdc, SCALINGFACTORY), 0); + + // Initialize page_setup_pixels_. + gfx::Size physical_size_pixels(GetDeviceCaps(hdc, PHYSICALWIDTH), + GetDeviceCaps(hdc, PHYSICALHEIGHT)); + gfx::Rect printable_area_pixels(GetDeviceCaps(hdc, PHYSICALOFFSETX), + GetDeviceCaps(hdc, PHYSICALOFFSETY), + GetDeviceCaps(hdc, HORZRES), + GetDeviceCaps(hdc, VERTRES)); + + if (is_custom_paper) { + page_measurements.page_length = ConvertUnitDouble( + static_cast(physical_size_pixels.height()), + static_cast(dpi_), + static_cast(desired_dpi)); + page_measurements.page_width = ConvertUnitDouble( + static_cast(physical_size_pixels.width()), + static_cast(dpi_), + static_cast(desired_dpi)); + if (landscape) { + double temp = page_measurements.page_length; + page_measurements.page_length = page_measurements.page_width; + page_measurements.page_width = temp; + } + } + SetPrinterPrintableArea(physical_size_pixels, printable_area_pixels); +} +#endif + +void PrintSettings::SetPrinterPrintableArea( + gfx::Size const& physical_size_pixels, + gfx::Rect const& printable_area_pixels) { + + // Hard-code text_height = 0.5cm = ~1/5 of inch + const int text_height = ConvertUnit(500, kHundrethsMMPerInch, dpi_); + + // Start by setting the user configuration + page_setup_pixels_.Init(physical_size_pixels, + printable_area_pixels, + text_height); + + // Now adjust requested margins to the appropriate dpi. + PageMargins margins; + margins.header = ConvertUnit(requested_margins.header, desired_dpi, dpi_); + margins.footer = ConvertUnit(requested_margins.footer, desired_dpi, dpi_); + margins.left = ConvertUnit(requested_margins.left, desired_dpi, dpi_); + margins.top = ConvertUnit(requested_margins.top, desired_dpi, dpi_); + margins.right = ConvertUnit(requested_margins.right, desired_dpi, dpi_); + margins.bottom = ConvertUnit(requested_margins.bottom, desired_dpi, dpi_); + page_setup_pixels_.SetRequestedMargins(margins); +} + +void PrintSettings::RenderParams(PrintParams* params) const { + DCHECK(params); + params->printable_size.SetSize(page_setup_pixels_.content_area().width(), + page_setup_pixels_.content_area().height()); + params->dpi = dpi_; + // Currently hardcoded at 1.25. See PrintSettings' constructor. + params->min_shrink = min_shrink; + // Currently hardcoded at 2.0. See PrintSettings' constructor. + params->max_shrink = max_shrink; + // Currently hardcoded at 72dpi. See PrintSettings' constructor. + params->desired_dpi = desired_dpi; + // Always use an invalid cookie. + params->document_cookie = 0; + params->selection_only = selection_only; + params->to_file = to_file; +} + +bool PrintSettings::Equals(const PrintSettings& rhs) const { + // Do not test the display device name (printer_name_) for equality since it + // may sometimes be chopped off at 30 chars. As long as device_name is the + // same, that's fine. + return ranges == rhs.ranges && + min_shrink == rhs.min_shrink && + max_shrink == rhs.max_shrink && + desired_dpi == rhs.desired_dpi && + device_name_ == rhs.device_name_ && + page_setup_pixels_.Equals(rhs.page_setup_pixels_) && + dpi_ == rhs.dpi_ && + landscape == rhs.landscape && + page_measurements.Equals(rhs.page_measurements) && + requested_margins.Equals(rhs.requested_margins); +} + +int PrintSettings::NewCookie() { + // A cookie of 0 is used to mark a document as unassigned, count from 1. + return cookie_seq.GetNext() + 1; +} + +void PrintSettings::UpdatePrintOptions(cef_print_options_t& print_options) { + print_options.page_orientation = (landscape) ? LANDSCAPE : PORTRAIT; + print_options.paper_metrics.paper_type = page_measurements.page_type; + + if (page_measurements.page_type == PT_CUSTOM) { + print_options.paper_metrics.length = ConvertUnitDouble( + page_measurements.page_length, desired_dpi, 1); + print_options.paper_metrics.width = ConvertUnitDouble( + page_measurements.page_width, desired_dpi, 1); + } + print_options.paper_margins.left = ConvertUnitDouble( + requested_margins.left, desired_dpi, 1); + print_options.paper_margins.top = ConvertUnitDouble( + requested_margins.top, desired_dpi, 1); + print_options.paper_margins.right = ConvertUnitDouble( + requested_margins.right, desired_dpi, 1); + print_options.paper_margins.bottom = ConvertUnitDouble( + requested_margins.bottom, desired_dpi, 1); + print_options.paper_margins.header = ConvertUnitDouble( + requested_margins.header, desired_dpi, 1); + print_options.paper_margins.footer = ConvertUnitDouble( + requested_margins.footer, desired_dpi, 1); +} +void PrintSettings::UpdateFromPrintOptions( + const cef_print_options_t& print_options) { + landscape = print_options.page_orientation == LANDSCAPE; + page_measurements.page_type = print_options.paper_metrics.paper_type; + if (page_measurements.page_type == PT_CUSTOM) { + page_measurements.page_length = ConvertUnitDouble( + print_options.paper_metrics.length, 1, desired_dpi); + page_measurements.page_width = ConvertUnitDouble( + print_options.paper_metrics.width, 1, desired_dpi); + } + requested_margins.left = static_cast(ConvertUnitDouble( + print_options.paper_margins.left, 1, desired_dpi)); + requested_margins.top = static_cast(ConvertUnitDouble( + print_options.paper_margins.top, 1, desired_dpi)); + requested_margins.right = static_cast(ConvertUnitDouble( + print_options.paper_margins.right, 1, desired_dpi)); + requested_margins.bottom = static_cast(ConvertUnitDouble( + print_options.paper_margins.bottom, 1, desired_dpi)); + requested_margins.header = static_cast(ConvertUnitDouble( + print_options.paper_margins.header, 1, desired_dpi)); + requested_margins.footer = static_cast(ConvertUnitDouble( + print_options.paper_margins.footer, 1, desired_dpi)); +} + +} // namespace printing + diff --git a/cef1/libcef/printing/print_settings.h b/cef1/libcef/printing/print_settings.h new file mode 100644 index 000000000..d1f2335ac --- /dev/null +++ b/cef1/libcef/printing/print_settings.h @@ -0,0 +1,180 @@ +// 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. + +#ifndef CEF_LIBCEF_PRINTING_PRINT_SETTINGS_H_ +#define CEF_LIBCEF_PRINTING_PRINT_SETTINGS_H_ +#pragma once + +#include "include/internal/cef_types.h" + +#include "printing/page_range.h" +#include "printing/page_setup.h" +#include "ui/gfx/rect.h" + +typedef struct HDC__* HDC; +typedef struct _devicemodeW DEVMODE; + +namespace printing { + +// Parameters for a render request. +struct PrintParams { + // In pixels according to dpi_x and dpi_y. + gfx::Size printable_size; + + // Specifies dots per inch. + double dpi; + + // Minimum shrink factor. See PrintSettings::min_shrink for more information. + double min_shrink; + + // Maximum shrink factor. See PrintSettings::max_shrink for more information. + double max_shrink; + + // Desired apparent dpi on paper. + int desired_dpi; + + // Cookie for the document to ensure correctness. + int document_cookie; + + // Indicates if the user only wants to print the current selection. + bool selection_only; + + // Indicates if the user wants to print to file. + bool to_file; + + // Warning: do not compare document_cookie. + bool Equals(const PrintParams& rhs) const { + return printable_size == rhs.printable_size && + dpi == rhs.dpi && + min_shrink == rhs.min_shrink && + max_shrink == rhs.max_shrink && + desired_dpi == rhs.desired_dpi && + selection_only == rhs.selection_only && + to_file == rhs.to_file; + } +}; + +// Page measurements information. +class PageMeasurements { + public: + PageMeasurements(); + void Clear(); + + // Equality operator. + bool Equals(const PageMeasurements& rhs) const; + + enum cef_paper_type_t page_type; + // Page length and width represented in inches. + // These should be filled in if page_type is PT_CUSTOM. + double page_length; + double page_width; +}; + +// OS-independent print settings. +class PrintSettings { + public: + PrintSettings(); + + // Reinitialize the settings to the default values. + void Clear(); + +#ifdef WIN32 + // Reads the settings from the selected device context. Calculates derived + // values like printable_area_. + void Init(HDC hdc, + const DEVMODE& dev_mode, + const PageRanges& new_ranges, + const CefString& new_device_name, + bool selection_only, + bool to_file); +#endif + + // Set printer printable area in pixels. + void SetPrinterPrintableArea(gfx::Size const& physical_size_pixels, + gfx::Rect const& printable_area_pixels); + + // Initializes the print parameters that needs to be sent to the renderer + // process. + void RenderParams(PrintParams* params) const; + + // Equality operator. + // NOTE: printer_name is NOT tested for equality since it doesn't affect the + // output. + bool Equals(const PrintSettings& rhs) const; + + const CefString& printer_name() const { return printer_name_; } + void set_device_name(const CefString& device_name) { + device_name_ = device_name; + } + const CefString& device_name() const { return device_name_; } + int dpi() const { return dpi_; } + const PageSetup& page_setup_pixels() const { return page_setup_pixels_; } + + void UpdatePrintOptions(cef_print_options_t& print_options); + void UpdateFromPrintOptions(const cef_print_options_t& print_options); + + // Multi-page printing. Each PageRange describes a from-to page combination. + // This permits printing selected pages only. + PageRanges ranges; + + // By imaging to a width a little wider than the available pixels, thin pages + // will be scaled down a little, matching the way they print in IE and Camino. + // This lets them use fewer sheets than they would otherwise, which is + // presumably why other browsers do this. Wide pages will be scaled down more + // than this. + double min_shrink; + + // This number determines how small we are willing to reduce the page content + // in order to accommodate the widest line. If the page would have to be + // reduced smaller to make the widest line fit, we just clip instead (this + // behavior matches MacIE and Mozilla, at least) + double max_shrink; + + // Desired visible dots per inch rendering for output. Printing should be + // scaled to ScreenDpi/dpix*desired_dpi. + int desired_dpi; + + // Indicates if the user only wants to print the current selection. + bool selection_only; + + // Indicates if the user wants to print to file. + bool to_file; + + // Cookie generator. It is used to initialize PrintedDocument with its + // associated PrintSettings, to be sure that each generated PrintedPage is + // correctly associated with its corresponding PrintedDocument. + static int NewCookie(); + + // Requested Page Margins in pixels based on desired_dpi. + // These are in terms of desired_dpi since printer dpi may vary. + PageMargins requested_margins; + + // Is the orientation landscape or portrait. + bool landscape; + + // Page Measurements. + PageMeasurements page_measurements; + + private: + void ResetRequestedPageMargins(); + ////////////////////////////////////////////////////////////////////////////// + // Settings that can't be changed without side-effects. + + // Printer name as shown to the user. + CefString printer_name_; + + // Printer device name as opened by the OS. + CefString device_name_; + + // Page setup in pixel units, dpi adjusted. + PageSetup page_setup_pixels_; + + // Printer's device effective dots per inch in both axis. + int dpi_; +}; + +} // namespace printing + +#endif // CEF_LIBCEF_PRINTING_PRINT_SETTINGS_H_ + diff --git a/cef1/libcef/printing/win_printing_context.cc b/cef1/libcef/printing/win_printing_context.cc new file mode 100644 index 000000000..aca730b26 --- /dev/null +++ b/cef1/libcef/printing/win_printing_context.cc @@ -0,0 +1,606 @@ +// 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. + +#include "libcef/printing/win_printing_context.h" + +#include + +#include "base/file_util.h" +#include "base/i18n/time_formatting.h" +#include "base/message_loop.h" +#include "base/time.h" +#include "skia/ext/bitmap_platform_device_win.h" + +#include "printing/units.h" + +using base::Time; + +namespace { + +// Retrieves the content of a GetPrinter call. +void GetPrinterHelper(HANDLE printer, int level, scoped_array* buffer) { + DWORD buf_size = 0; + GetPrinter(printer, level, NULL, 0, &buf_size); + if (buf_size) { + buffer->reset(new uint8[buf_size]); + memset(buffer->get(), 0, buf_size); + if (!GetPrinter(printer, level, buffer->get(), buf_size, &buf_size)) { + buffer->reset(); + } + } +} + +} // namespace + +namespace printing { + +PrintingContext::PrintingContext() + : hdc_(NULL), +#ifndef NDEBUG + page_number_(-1), +#endif + dialog_box_(NULL), + dialog_box_dismissed_(false), + abort_printing_(false), + in_print_job_(false) { +} + +PrintingContext::~PrintingContext() { + ResetSettings(); +} + +PrintingContext::Result PrintingContext::AskUserForSettings( + HWND window, + int max_pages, + bool has_selection) { + DCHECK(window); + DCHECK(!in_print_job_); + dialog_box_dismissed_ = false; + // Show the OS-dependent dialog box. + // If the user press + // - OK, the settings are reset and reinitialized with the new settings. OK is + // returned. + // - Apply then Cancel, the settings are reset and reinitialized with the new + // settings. CANCEL is returned. + // - Cancel, the settings are not changed, the previous setting, if it was + // initialized before, are kept. CANCEL is returned. + // On failure, the settings are reset and FAILED is returned. + PRINTDLGEX dialog_options = { sizeof(PRINTDLGEX) }; + dialog_options.hwndOwner = window; + // Disable options we don't support currently. + // TODO(maruel): Reuse the previously loaded settings! + dialog_options.Flags = PD_RETURNDC | PD_USEDEVMODECOPIESANDCOLLATE | + PD_NOCURRENTPAGE; + if (!has_selection) + dialog_options.Flags |= PD_NOSELECTION; + + PRINTPAGERANGE ranges[32]; + dialog_options.nStartPage = START_PAGE_GENERAL; + if (max_pages) { + // Default initialize to print all the pages. + memset(ranges, 0, sizeof(ranges)); + ranges[0].nFromPage = 1; + ranges[0].nToPage = max_pages; + dialog_options.nPageRanges = 1; + dialog_options.nMaxPageRanges = arraysize(ranges); + dialog_options.nMinPage = 1; + dialog_options.nMaxPage = max_pages; + dialog_options.lpPageRanges = ranges; + } else { + // No need to bother, we don't know how many pages are available. + dialog_options.Flags |= PD_NOPAGENUMS; + } + + // Adjust the default dev mode for the printdlg settings. + DEVMODE dev_mode; + memset(&dev_mode, 0, sizeof(dev_mode)); + dev_mode.dmSpecVersion = DM_SPECVERSION; + dev_mode.dmSize = sizeof(DEVMODE); + AdjustDevMode(dev_mode); + + dialog_options.hDevMode = GlobalAlloc(GMEM_MOVEABLE, sizeof(DEVMODE)); + DEVMODE* locked_dev_mode = + reinterpret_cast(GlobalLock(dialog_options.hDevMode)); + memcpy(locked_dev_mode, &dev_mode, sizeof(DEVMODE)); + GlobalUnlock(dialog_options.hDevMode); + { + if (PrintDlgEx(&dialog_options) != S_OK) { + ResetSettings(); + return FAILED; + } + } + return ParseDialogResultEx(dialog_options); +} + +PrintingContext::Result PrintingContext::UseDefaultSettings() { + DCHECK(!in_print_job_); + + PRINTDLG dialog_options = { sizeof(PRINTDLG) }; + dialog_options.Flags = PD_RETURNDC | PD_RETURNDEFAULT; + if (PrintDlg(&dialog_options) == 0) { + ResetSettings(); + return FAILED; + } + return ParseDialogResult(dialog_options); +} + +void PrintingContext::AdjustDevMode(DEVMODE& dev_mode) { + dev_mode.dmFields |= DM_ORIENTATION; + dev_mode.dmOrientation = + (settings_.landscape) ? DMORIENT_LANDSCAPE : DMORIENT_PORTRAIT; + + dev_mode.dmFields |= DM_PAPERSIZE; + switch (settings_.page_measurements.page_type) { + case PT_LETTER: + dev_mode.dmPaperSize = DMPAPER_LETTER; + break; + case PT_LEGAL: + dev_mode.dmPaperSize = DMPAPER_LEGAL; + break; + case PT_EXECUTIVE: + dev_mode.dmPaperSize = DMPAPER_EXECUTIVE; + break; + case PT_A3: + dev_mode.dmPaperSize = DMPAPER_A3; + break; + case PT_A4: + dev_mode.dmPaperSize = DMPAPER_A4; + break; + case PT_CUSTOM: + { + dev_mode.dmPaperSize = DMPAPER_USER; + dev_mode.dmFields |= DM_PAPERLENGTH | DM_PAPERWIDTH; + DCHECK_GT(settings_.page_measurements.page_length, 0); + DCHECK_GT(settings_.page_measurements.page_width, 0); + // Convert from desired_dpi to tenths of a mm. + dev_mode.dmPaperLength = + static_cast(ConvertUnitDouble( // NOLINT(runtime/int) + abs(settings_.page_measurements.page_length), + 10.0 * settings_.desired_dpi, + static_cast(kHundrethsMMPerInch)) + 0.5); + dev_mode.dmPaperWidth = + static_cast(ConvertUnitDouble( // NOLINT(runtime/int) + abs(settings_.page_measurements.page_width), + 10.0 * settings_.desired_dpi, + static_cast(kHundrethsMMPerInch)) + 0.5); + break; + } + default: + // We shouldn't ever hit this case. + DCHECK(false); + dev_mode.dmPaperSize = DMPAPER_LETTER; + break; + } +} + +PrintingContext::Result PrintingContext::Init() { + DCHECK(!in_print_job_); + TCHAR printername[512]; + DWORD size = sizeof(printername)-1; + if (GetDefaultPrinter(printername, &size)) { + return Init(CefString(printername), false); + } + return FAILED; +} + +PrintingContext::Result PrintingContext::InitWithSettings( + const PrintSettings& settings) { + DCHECK(!in_print_job_); + settings_ = settings; + + return Init(settings_.device_name(), true); +} + +PrintingContext::Result PrintingContext::Init(const CefString& device_name, + bool adjust_dev_mode) { + HANDLE printer; + std::wstring deviceNameStr = device_name; + if (!OpenPrinter(const_cast(deviceNameStr.c_str()), + &printer, + NULL)) + return FAILED; + + Result status = OK; + + if (!GetPrinterSettings(printer, device_name, adjust_dev_mode)) + status = FAILED; + + // Close the printer after retrieving the context. + ClosePrinter(printer); + + if (status != OK) + ResetSettings(); + return status; +} + +void PrintingContext::ResetSettings() { + if (hdc_ != NULL) { + DeleteDC(hdc_); + hdc_ = NULL; + } + settings_.Clear(); + in_print_job_ = false; + +#ifndef NDEBUG + page_number_ = -1; +#endif +} + +PrintingContext::Result PrintingContext::NewDocument( + const CefString& document_name) { + DCHECK(!in_print_job_); + if (!hdc_) + return OnError(); + + // Set the flag used by the AbortPrintJob dialog procedure. + abort_printing_ = false; + + in_print_job_ = true; + + // Register the application's AbortProc function with GDI. + if (SP_ERROR == SetAbortProc(hdc_, &AbortProc)) + return OnError(); + + DOCINFO di = { sizeof(DOCINFO) }; + std::wstring documentNameStr = document_name; + di.lpszDocName = documentNameStr.c_str(); + + wchar_t szFileName[MAX_PATH] = L""; + if (settings_.to_file) { + // Prompt for the file name to use for the printed output. + OPENFILENAME ofn = { sizeof(ofn) }; + + ofn.lpstrFilter = L"PostScript Files (*.ps)\0*.ps\0All Files (*.*)\0*.*\0"; + ofn.lpstrFile = szFileName; + ofn.nMaxFile = MAX_PATH; + ofn.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY | + OFN_NOREADONLYRETURN | OFN_ENABLESIZING; + ofn.lpstrDefExt = L"ps"; + + if (GetSaveFileName(&ofn)) + di.lpszOutput = szFileName; + else + return OnError(); + } + + DCHECK_EQ(MessageLoop::current()->NestableTasksAllowed(), false); + // Begin a print job by calling the StartDoc function. + // NOTE: StartDoc() starts a message loop. That causes a lot of problems with + // IPC. Make sure recursive task processing is disabled. + if (StartDoc(hdc_, &di) <= 0) + return OnError(); + +#ifndef NDEBUG + page_number_ = 0; +#endif + return OK; +} + +PrintingContext::Result PrintingContext::NewPage() { + if (abort_printing_) + return CANCEL; + DCHECK(in_print_job_); + + // Inform the driver that the application is about to begin sending data. + if (StartPage(hdc_) <= 0) + return OnError(); + +#ifndef NDEBUG + ++page_number_; +#endif + + return OK; +} + +PrintingContext::Result PrintingContext::PageDone() { + if (abort_printing_) + return CANCEL; + DCHECK(in_print_job_); + + if (EndPage(hdc_) <= 0) + return OnError(); + return OK; +} + +PrintingContext::Result PrintingContext::DocumentDone() { + if (abort_printing_) + return CANCEL; + DCHECK(in_print_job_); + + // Inform the driver that document has ended. + if (EndDoc(hdc_) <= 0) + return OnError(); + + ResetSettings(); + return OK; +} + +void PrintingContext::Cancel() { + abort_printing_ = true; + in_print_job_ = false; + if (hdc_) + CancelDC(hdc_); + DismissDialog(); +} + +void PrintingContext::DismissDialog() { + if (dialog_box_) { + DestroyWindow(dialog_box_); + dialog_box_dismissed_ = true; + } +} + +PrintingContext::Result PrintingContext::OnError() { + // This will close hdc_ and clear settings_. + ResetSettings(); + return abort_printing_ ? CANCEL : FAILED; +} + +// static +BOOL PrintingContext::AbortProc(HDC hdc, int nCode) { + if (nCode) { + // TODO(maruel): Need a way to find the right instance to set. Should + // leverage PrintJobManager here? + // abort_printing_ = true; + } + return true; +} + +bool PrintingContext::InitializeSettings(const DEVMODE& dev_mode, + const CefString& new_device_name, + const PRINTPAGERANGE* ranges, + int number_ranges, + bool selection_only, + bool to_file) { + skia::InitializeDC(hdc_); + DCHECK(GetDeviceCaps(hdc_, CLIPCAPS)); + DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_STRETCHDIB); + DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_BITMAP64); + // Some printers don't advertise these. + // DCHECK(GetDeviceCaps(hdc_, RASTERCAPS) & RC_SCALING); + // DCHECK(GetDeviceCaps(hdc_, SHADEBLENDCAPS) & SB_CONST_ALPHA); + // DCHECK(GetDeviceCaps(hdc_, SHADEBLENDCAPS) & SB_PIXEL_ALPHA); + + // StretchDIBits() support is needed for printing. + if (!(GetDeviceCaps(hdc_, RASTERCAPS) & RC_STRETCHDIB) || + !(GetDeviceCaps(hdc_, RASTERCAPS) & RC_BITMAP64)) { + NOTREACHED(); + ResetSettings(); + return false; + } + + DCHECK(!in_print_job_); + DCHECK(hdc_); + PageRanges ranges_vector; + if (!selection_only) { + // Convert the PRINTPAGERANGE array to a PrintSettings::PageRanges vector. + ranges_vector.reserve(number_ranges); + for (int i = 0; i < number_ranges; ++i) { + PageRange range; + // Transfer from 1-based to 0-based. + range.from = ranges[i].nFromPage - 1; + range.to = ranges[i].nToPage - 1; + ranges_vector.push_back(range); + } + } + settings_.Init(hdc_, + dev_mode, + ranges_vector, + new_device_name, + selection_only, + to_file); + return true; +} + +bool PrintingContext::GetPrinterSettings(HANDLE printer, + const CefString& device_name, + bool adjust_dev_mode) { + DCHECK(!in_print_job_); + scoped_array buffer; + + // A PRINTER_INFO_9 structure specifying the per-user default printer + // settings. + GetPrinterHelper(printer, 9, &buffer); + if (buffer.get()) { + PRINTER_INFO_9* info_9 = reinterpret_cast(buffer.get()); + if (info_9->pDevMode != NULL) { + if (adjust_dev_mode) + AdjustDevMode(*info_9->pDevMode); + if (!AllocateContext(device_name, info_9->pDevMode)) { + ResetSettings(); + return false; + } + return InitializeSettings(*info_9->pDevMode, device_name, NULL, 0, false, + false); + } + buffer.reset(); + } + + // A PRINTER_INFO_8 structure specifying the global default printer settings. + GetPrinterHelper(printer, 8, &buffer); + if (buffer.get()) { + PRINTER_INFO_8* info_8 = reinterpret_cast(buffer.get()); + if (info_8->pDevMode != NULL) { + if (adjust_dev_mode) + AdjustDevMode(*info_8->pDevMode); + if (!AllocateContext(device_name, info_8->pDevMode)) { + ResetSettings(); + return false; + } + return InitializeSettings(*info_8->pDevMode, device_name, NULL, 0, false, + false); + } + buffer.reset(); + } + + // A PRINTER_INFO_2 structure specifying the driver's default printer + // settings. + GetPrinterHelper(printer, 2, &buffer); + if (buffer.get()) { + PRINTER_INFO_2* info_2 = reinterpret_cast(buffer.get()); + if (info_2->pDevMode != NULL) { + if (adjust_dev_mode) + AdjustDevMode(*info_2->pDevMode); + if (!AllocateContext(device_name, info_2->pDevMode)) { + ResetSettings(); + return false; + } + return InitializeSettings(*info_2->pDevMode, device_name, NULL, 0, false, + false); + } + buffer.reset(); + } + // Failed to retrieve the printer settings. + ResetSettings(); + return false; +} + +bool PrintingContext::AllocateContext(const CefString& printer_name, + const DEVMODE* dev_mode) { + std::wstring printerNameStr = printer_name; + hdc_ = CreateDC(L"WINSPOOL", printerNameStr.c_str(), NULL, dev_mode); + DCHECK(hdc_); + return hdc_ != NULL; +} + +PrintingContext::Result PrintingContext::ParseDialogResultEx( + const PRINTDLGEX& dialog_options) { + // If the user clicked OK or Apply then Cancel, but not only Cancel. + if (dialog_options.dwResultAction != PD_RESULT_CANCEL) { + PageMargins requested_margins = settings_.requested_margins; + // Start fresh except for page margins since that isn't controlled by this + // dialog. + ResetSettings(); + settings_.requested_margins = requested_margins; + + DEVMODE* dev_mode = NULL; + if (dialog_options.hDevMode) { + dev_mode = + reinterpret_cast(GlobalLock(dialog_options.hDevMode)); + DCHECK(dev_mode); + } + + std::wstring device_name; + if (dialog_options.hDevNames) { + DEVNAMES* dev_names = + reinterpret_cast(GlobalLock(dialog_options.hDevNames)); + DCHECK(dev_names); + if (dev_names) { + device_name = + reinterpret_cast( + reinterpret_cast(dev_names) + + dev_names->wDeviceOffset); + GlobalUnlock(dialog_options.hDevNames); + } + } + + bool success = false; + if (dev_mode && !device_name.empty()) { + hdc_ = dialog_options.hDC; + PRINTPAGERANGE* page_ranges = NULL; + DWORD num_page_ranges = 0; + bool print_selection_only = false; + bool print_to_file = false; + if (dialog_options.Flags & PD_PAGENUMS) { + page_ranges = dialog_options.lpPageRanges; + num_page_ranges = dialog_options.nPageRanges; + } + if (dialog_options.Flags & PD_SELECTION) { + print_selection_only = true; + } + if (dialog_options.Flags & PD_PRINTTOFILE) { + print_to_file = true; + } + success = InitializeSettings(*dev_mode, + device_name, + page_ranges, + num_page_ranges, + print_selection_only, + print_to_file); + } + + if (!success && dialog_options.hDC) { + DeleteDC(dialog_options.hDC); + hdc_ = NULL; + } + + if (dev_mode) { + GlobalUnlock(dialog_options.hDevMode); + } + } else { + if (dialog_options.hDC) { + DeleteDC(dialog_options.hDC); + } + } + + if (dialog_options.hDevMode != NULL) + GlobalFree(dialog_options.hDevMode); + if (dialog_options.hDevNames != NULL) + GlobalFree(dialog_options.hDevNames); + + switch (dialog_options.dwResultAction) { + case PD_RESULT_PRINT: + return hdc_ ? OK : FAILED; + case PD_RESULT_APPLY: + return hdc_ ? CANCEL : FAILED; + case PD_RESULT_CANCEL: + return CANCEL; + default: + return FAILED; + } +} + +PrintingContext::Result PrintingContext::ParseDialogResult( + const PRINTDLG& dialog_options) { + // If the user clicked OK or Apply then Cancel, but not only Cancel. + // Start fresh. + ResetSettings(); + + DEVMODE* dev_mode = NULL; + if (dialog_options.hDevMode) { + dev_mode = + reinterpret_cast(GlobalLock(dialog_options.hDevMode)); + DCHECK(dev_mode); + } + + std::wstring device_name; + if (dialog_options.hDevNames) { + DEVNAMES* dev_names = + reinterpret_cast(GlobalLock(dialog_options.hDevNames)); + DCHECK(dev_names); + if (dev_names) { + device_name = + reinterpret_cast( + reinterpret_cast(dev_names) + + dev_names->wDeviceOffset); + GlobalUnlock(dialog_options.hDevNames); + } + } + + bool success = false; + if (dev_mode && !device_name.empty()) { + hdc_ = dialog_options.hDC; + success = InitializeSettings(*dev_mode, device_name, NULL, 0, false, + false); + } + + if (!success && dialog_options.hDC) { + DeleteDC(dialog_options.hDC); + hdc_ = NULL; + } + + if (dev_mode) { + GlobalUnlock(dialog_options.hDevMode); + } + + if (dialog_options.hDevMode != NULL) + GlobalFree(dialog_options.hDevMode); + if (dialog_options.hDevNames != NULL) + GlobalFree(dialog_options.hDevNames); + + return hdc_ ? OK : FAILED; +} + +} // namespace printing + diff --git a/cef1/libcef/printing/win_printing_context.h b/cef1/libcef/printing/win_printing_context.h new file mode 100644 index 000000000..1326d2f8e --- /dev/null +++ b/cef1/libcef/printing/win_printing_context.h @@ -0,0 +1,151 @@ +// 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. + +#ifndef CEF_LIBCEF_PRINTING_WIN_PRINTING_CONTEXT_H_ +#define CEF_LIBCEF_PRINTING_WIN_PRINTING_CONTEXT_H_ +#pragma once + +#include +#include +#include + +#include "libcef/printing/print_settings.h" +#include "base/basictypes.h" + +namespace printing { + +// Describe the user selected printing context for Windows. This includes the +// OS-dependent UI to ask the user about the print settings. This class directly +// talk to the printer and manages the document and pages breaks. +class PrintingContext { + public: + // Tri-state result for user behavior-dependent functions. + enum Result { + OK, + CANCEL, + FAILED, + }; + + PrintingContext(); + ~PrintingContext(); + + // Asks the user what printer and format should be used to print. Updates the + // context with the select device settings. + Result AskUserForSettings(HWND window, int max_pages, bool has_selection); + + // Selects the user's default printer and format. Updates the context with the + // default device settings. + Result UseDefaultSettings(); + + // Initializes with printer default's settings. + Result Init(); + + // Initializes with predefined settings. + Result InitWithSettings(const PrintSettings& settings); + + // Reinitializes the settings to uninitialized for object reuse. + void ResetSettings(); + + // Does platform specific setup of the printer before the printing. Signal the + // printer that a document is about to be spooled. + // Warning: This function enters a message loop. That may cause side effects + // like IPC message processing! Some printers have side-effects on this call + // like virtual printers that ask the user for the path of the saved document; + // for example a PDF printer. + Result NewDocument(const CefString& document_name); + + // Starts a new page. + Result NewPage(); + + // Closes the printed page. + Result PageDone(); + + // Closes the printing job. After this call the object is ready to start a new + // document. + Result DocumentDone(); + + // Cancels printing. Can be used in a multithreaded context. Takes effect + // immediately. + void Cancel(); + + // Dismiss the Print... dialog box if shown. + void DismissDialog(); + + HDC context() { + return hdc_; + } + + const PrintSettings& settings() const { + return settings_; + } + + private: + // Class that manages the PrintDlgEx() callbacks. This is meant to be a + // temporary object used during the Print... dialog display. + class CallbackHandler; + + // Does bookkeeping when an error occurs. + PrintingContext::Result OnError(); + + // Used in response to the user canceling the printing. + static BOOL CALLBACK AbortProc(HDC hdc, int nCode); + + // Reads the settings from the selected device context. Updates settings_ and + // its margins. + bool InitializeSettings(const DEVMODE& dev_mode, + const CefString& new_device_name, + const PRINTPAGERANGE* ranges, + int number_ranges, + bool selection_only, + bool to_file); + + // Retrieves the printer's default low-level settings. hdc_ is allocated with + // this call. + bool GetPrinterSettings(HANDLE printer, + const CefString& device_name, + bool adjust_dev_mode); + + // Allocates the HDC for a specific DEVMODE. + bool AllocateContext(const CefString& printer_name, + const DEVMODE* dev_mode); + + // Updates printer dev_mode with settings_ + void PrintingContext::AdjustDevMode(DEVMODE& dev_mode); + + // Initializes the hdc_ either with setting_ or with just printer defaults. + Result Init(const CefString& device_name, bool adjust_dev_mode); + + // Parses the result of a PRINTDLGEX result. + Result ParseDialogResultEx(const PRINTDLGEX& dialog_options); + Result ParseDialogResult(const PRINTDLG& dialog_options); + + // The selected printer context. + HDC hdc_; + + // Complete print context settings. + PrintSettings settings_; + +#ifndef NDEBUG + // Current page number in the print job. + int page_number_; +#endif + + // The dialog box for the time it is shown. + volatile HWND dialog_box_; + + // The dialog box has been dismissed. + volatile bool dialog_box_dismissed_; + + // Is a print job being done. + volatile bool in_print_job_; + + // Did the user cancel the print job. + volatile bool abort_printing_; + + DISALLOW_EVIL_CONSTRUCTORS(PrintingContext); +}; + +} // namespace printing + +#endif // CEF_LIBCEF_PRINTING_WIN_PRINTING_CONTEXT_H_ diff --git a/cef1/libcef/request_impl.cc b/cef1/libcef/request_impl.cc new file mode 100644 index 000000000..547a069c2 --- /dev/null +++ b/cef1/libcef/request_impl.cc @@ -0,0 +1,493 @@ +// 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 "libcef/request_impl.h" + +#include +#include + +#include "libcef/http_header_utils.h" + +#include "base/logging.h" +#include "net/url_request/url_request.h" + +using WebKit::WebHTTPBody; +using WebKit::WebString; +using WebKit::WebURL; +using WebKit::WebURLRequest; + +CefRefPtr CefRequest::CreateRequest() { + CefRefPtr request(new CefRequestImpl()); + return request; +} + +CefRequestImpl::CefRequestImpl() + : method_("GET"), + flags_(WUR_FLAG_NONE) { +} + +CefString CefRequestImpl::GetURL() { + AutoLock lock_scope(this); + return url_; +} + +void CefRequestImpl::SetURL(const CefString& url) { + AutoLock lock_scope(this); + url_ = url; +} + +CefString CefRequestImpl::GetMethod() { + AutoLock lock_scope(this); + return method_; +} + +void CefRequestImpl::SetMethod(const CefString& method) { + AutoLock lock_scope(this); + method_ = method; +} + +CefRefPtr CefRequestImpl::GetPostData() { + AutoLock lock_scope(this); + return postdata_; +} + +void CefRequestImpl::SetPostData(CefRefPtr postData) { + AutoLock lock_scope(this); + postdata_ = postData; +} + +void CefRequestImpl::GetHeaderMap(HeaderMap& headerMap) { + AutoLock lock_scope(this); + headerMap = headermap_; +} + +void CefRequestImpl::SetHeaderMap(const HeaderMap& headerMap) { + AutoLock lock_scope(this); + headermap_ = headerMap; +} + +void CefRequestImpl::Set(const CefString& url, + const CefString& method, + CefRefPtr postData, + const HeaderMap& headerMap) { + AutoLock lock_scope(this); + url_ = url; + method_ = method; + postdata_ = postData; + headermap_ = headerMap; +} + +void CefRequestImpl::Set(net::URLRequest* request) { + AutoLock lock_scope(this); + + url_ = request->url().spec(); + method_ = request->method(); + + net::HttpRequestHeaders headers = request->extra_request_headers(); + + // Ensure that we do not send username and password fields in the referrer. + GURL referrer(request->GetSanitizedReferrer()); + + // 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 + net::UploadData* data = request->get_upload(); + if (data) { + postdata_ = CefPostData::CreatePostData(); + static_cast(postdata_.get())->Set(*data); + } +} + +void CefRequestImpl::Set(const WebKit::WebURLRequest& request) { + DCHECK(!request.isNull()); + AutoLock lock_scope(this); + + url_ = request.url().spec().utf16(); + method_ = request.httpMethod(); + + const 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_); + + int flags = WUR_FLAG_NONE; + if (request.cachePolicy() == WebURLRequest::ReloadIgnoringCacheData) + flags |= WUR_FLAG_SKIP_CACHE; + if (request.allowStoredCredentials()) + flags |= WUR_FLAG_ALLOW_CACHED_CREDENTIALS; + if (request.allowCookies()) + flags |= WUR_FLAG_ALLOW_COOKIES; + if (request.reportUploadProgress()) + flags |= WUR_FLAG_REPORT_UPLOAD_PROGRESS; + if (request.reportLoadTiming()) + flags |= WUR_FLAG_REPORT_LOAD_TIMING; + if (request.reportRawHeaders()) + flags |= WUR_FLAG_REPORT_RAW_HEADERS; + flags_ = static_cast(flags); + + first_party_for_cookies_ = request.firstPartyForCookies().spec().utf16(); +} + +#define SETBOOLFLAG(obj, flags, method, FLAG) \ + obj.method((flags & (FLAG)) == (FLAG)) + +void CefRequestImpl::Get(WebKit::WebURLRequest& request) { + request.initialize(); + AutoLock lock_scope(this); + + std::string urlStr(url_); + GURL gurl = GURL(urlStr); + request.setURL(WebURL(gurl)); + + std::string method(method_); + request.setHTTPMethod(WebString::fromUTF8(method.c_str())); + request.setTargetType(WebURLRequest::TargetIsMainFrame); + + WebHTTPBody body; + if (postdata_.get()) { + body.initialize(); + static_cast(postdata_.get())->Get(body); + request.setHTTPBody(body); + } + + SetHeaderMap(headermap_, request); + + request.setCachePolicy((flags_ & WUR_FLAG_SKIP_CACHE) ? + WebURLRequest::ReloadIgnoringCacheData : + WebURLRequest::UseProtocolCachePolicy); + + SETBOOLFLAG(request, flags_, setAllowStoredCredentials, + WUR_FLAG_ALLOW_CACHED_CREDENTIALS); + SETBOOLFLAG(request, flags_, setAllowCookies, + WUR_FLAG_ALLOW_COOKIES); + SETBOOLFLAG(request, flags_, setReportUploadProgress, + WUR_FLAG_REPORT_UPLOAD_PROGRESS); + SETBOOLFLAG(request, flags_, setReportLoadTiming, + WUR_FLAG_REPORT_LOAD_TIMING); + SETBOOLFLAG(request, flags_, setReportRawHeaders, + WUR_FLAG_REPORT_RAW_HEADERS); + + if (!first_party_for_cookies_.empty()) { + std::string cookiesStr(first_party_for_cookies_); + GURL gurl = GURL(cookiesStr); + request.setFirstPartyForCookies(WebURL(gurl)); + } +} + +CefRequest::RequestFlags CefRequestImpl::GetFlags() { + AutoLock lock_scope(this); + return flags_; +} +void CefRequestImpl::SetFlags(RequestFlags flags) { + AutoLock lock_scope(this); + flags_ = flags; +} + +CefString CefRequestImpl::GetFirstPartyForCookies() { + AutoLock lock_scope(this); + return first_party_for_cookies_; +} +void CefRequestImpl::SetFirstPartyForCookies(const CefString& url) { + AutoLock lock_scope(this); + first_party_for_cookies_ = url; +} + +// static +void CefRequestImpl::GetHeaderMap(const net::HttpRequestHeaders& headers, + HeaderMap& map) { + net::HttpRequestHeaders::Iterator it(headers); + do { + map.insert(std::make_pair(it.name(), it.value())); + } while (it.GetNext()); +} + +// static +void CefRequestImpl::GetHeaderMap(const WebKit::WebURLRequest& request, + HeaderMap& map) { + HttpHeaderUtils::HeaderVisitor visitor(&map); + request.visitHTTPHeaderFields(&visitor); +} + +// static +void CefRequestImpl::SetHeaderMap(const HeaderMap& map, + WebKit::WebURLRequest& request) { + HeaderMap::const_iterator it = map.begin(); + for (; it != map.end(); ++it) + request.setHTTPHeaderField(string16(it->first), string16(it->second)); +} + +CefRefPtr CefPostData::CreatePostData() { + CefRefPtr postdata(new CefPostDataImpl()); + return postdata; +} + +CefPostDataImpl::CefPostDataImpl() { +} + +size_t CefPostDataImpl::GetElementCount() { + AutoLock lock_scope(this); + return elements_.size(); +} + +void CefPostDataImpl::GetElements(ElementVector& elements) { + AutoLock lock_scope(this); + elements = elements_; +} + +bool CefPostDataImpl::RemoveElement(CefRefPtr element) { + AutoLock lock_scope(this); + + 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; + + AutoLock lock_scope(this); + + // 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() { + AutoLock lock_scope(this); + elements_.clear(); +} + +void CefPostDataImpl::Set(net::UploadData& data) { + AutoLock lock_scope(this); + + CefRefPtr postelem; + + std::vector* elements = data.elements(); + std::vector::const_iterator it = elements->begin(); + for (; it != elements->end(); ++it) { + postelem = CefPostDataElement::CreatePostDataElement(); + static_cast(postelem.get())->Set(*it); + AddElement(postelem); + } +} + +void CefPostDataImpl::Get(net::UploadData& data) { + AutoLock lock_scope(this); + + net::UploadData::Element element; + std::vector data_elements; + ElementVector::iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + static_cast(it->get())->Get(element); + data_elements.push_back(element); + } + data.SetElements(data_elements); +} + +void CefPostDataImpl::Set(const WebKit::WebHTTPBody& data) { + AutoLock lock_scope(this); + + CefRefPtr postelem; + WebKit::WebHTTPBody::Element element; + size_t size = data.elementCount(); + for (size_t i = 0; i < size; ++i) { + if (data.elementAt(i, element)) { + postelem = CefPostDataElement::CreatePostDataElement(); + static_cast(postelem.get())->Set(element); + AddElement(postelem); + } + } +} + +void CefPostDataImpl::Get(WebKit::WebHTTPBody& data) { + AutoLock lock_scope(this); + + WebKit::WebHTTPBody::Element element; + ElementVector::iterator it = elements_.begin(); + for (; it != elements_.end(); ++it) { + static_cast(it->get())->Get(element); + if (element.type == WebKit::WebHTTPBody::Element::TypeData) { + data.appendData(element.data); + } else if (element.type == WebKit::WebHTTPBody::Element::TypeFile) { + data.appendFile(element.filePath); + } else { + NOTREACHED(); + } + } +} + +CefRefPtr CefPostDataElement::CreatePostDataElement() { + CefRefPtr element(new CefPostDataElementImpl()); + return element; +} + +CefPostDataElementImpl::CefPostDataElementImpl() { + type_ = PDE_TYPE_EMPTY; + memset(&data_, 0, sizeof(data_)); +} + +CefPostDataElementImpl::~CefPostDataElementImpl() { + SetToEmpty(); +} + +void CefPostDataElementImpl::SetToEmpty() { + AutoLock lock_scope(this); + 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_)); +} + +void CefPostDataElementImpl::SetToFile(const CefString& fileName) { + AutoLock lock_scope(this); + // Clear any data currently in the element + SetToEmpty(); + + // 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) { + AutoLock lock_scope(this); + // Clear any data currently in the element + SetToEmpty(); + + // 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() { + AutoLock lock_scope(this); + return type_; +} + +CefString CefPostDataElementImpl::GetFile() { + AutoLock lock_scope(this); + 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() { + AutoLock lock_scope(this); + 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) { + AutoLock lock_scope(this); + 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::UploadData::Element& element) { + AutoLock lock_scope(this); + + if (element.type() == net::UploadData::TYPE_BYTES) { + SetToBytes(element.bytes().size(), + static_cast( + std::string(element.bytes().begin(), + element.bytes().end()).c_str())); + } else if (element.type() == net::UploadData::TYPE_FILE) { + SetToFile(element.file_path().value()); + } else { + NOTREACHED(); + } +} + +void CefPostDataElementImpl::Get(net::UploadData::Element& element) { + AutoLock lock_scope(this); + + if (type_ == PDE_TYPE_BYTES) { + element.SetToBytes(static_cast(data_.bytes.bytes), data_.bytes.size); + } else if (type_ == PDE_TYPE_FILE) { + FilePath path = FilePath(CefString(&data_.filename)); + element.SetToFilePath(path); + } else { + NOTREACHED(); + } +} + +void CefPostDataElementImpl::Set(const WebKit::WebHTTPBody::Element& element) { + AutoLock lock_scope(this); + + if (element.type == WebKit::WebHTTPBody::Element::TypeData) { + SetToBytes(element.data.size(), + static_cast(element.data.data())); + } else if (element.type == WebKit::WebHTTPBody::Element::TypeFile) { + SetToFile(string16(element.filePath)); + } else { + NOTREACHED(); + } +} + +void CefPostDataElementImpl::Get(WebKit::WebHTTPBody::Element& element) { + AutoLock lock_scope(this); + + if (type_ == PDE_TYPE_BYTES) { + element.type = WebKit::WebHTTPBody::Element::TypeData; + element.data.assign( + static_cast(data_.bytes.bytes), data_.bytes.size); + } else if (type_ == PDE_TYPE_FILE) { + element.type = WebKit::WebHTTPBody::Element::TypeFile; + element.filePath.assign(string16(CefString(&data_.filename))); + } else { + NOTREACHED(); + } +} diff --git a/cef1/libcef/request_impl.h b/cef1/libcef/request_impl.h new file mode 100644 index 000000000..a4b9a0799 --- /dev/null +++ b/cef1/libcef/request_impl.h @@ -0,0 +1,126 @@ +// 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. + +#ifndef CEF_LIBCEF_REQUEST_IMPL_H_ +#define CEF_LIBCEF_REQUEST_IMPL_H_ +#pragma once + +#include "include/cef_request.h" +#include "net/base/upload_data.h" +#include "net/http/http_request_headers.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebHTTPBody.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" + +namespace net { +class URLRequest; +}; + +// Implementation of CefRequest +class CefRequestImpl : public CefRequest { + public: + CefRequestImpl(); + ~CefRequestImpl() {} + + 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 RequestFlags GetFlags() OVERRIDE; + virtual void SetFlags(RequestFlags flags) OVERRIDE; + virtual CefString GetFirstPartyForCookies() OVERRIDE; + virtual void SetFirstPartyForCookies(const CefString& url) OVERRIDE; + + void Set(net::URLRequest* request); + void Set(const WebKit::WebURLRequest& request); + void Get(WebKit::WebURLRequest& request); + + static void GetHeaderMap(const net::HttpRequestHeaders& headers, + HeaderMap& map); + static void GetHeaderMap(const WebKit::WebURLRequest& request, + HeaderMap& map); + static void SetHeaderMap(const HeaderMap& map, + WebKit::WebURLRequest& request); + + protected: + CefString url_; + CefString method_; + CefRefPtr postdata_; + HeaderMap headermap_; + + // The below methods are used by WebURLRequest. + RequestFlags flags_; + CefString first_party_for_cookies_; + + IMPLEMENT_REFCOUNTING(CefRequestImpl); + IMPLEMENT_LOCKING(CefRequestImpl); +}; + +// Implementation of CefPostData +class CefPostDataImpl : public CefPostData { + public: + CefPostDataImpl(); + ~CefPostDataImpl() {} + + 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(); + + void Set(net::UploadData& data); + void Get(net::UploadData& data); + void Set(const WebKit::WebHTTPBody& data); + void Get(WebKit::WebHTTPBody& data); + + protected: + ElementVector elements_; + + IMPLEMENT_REFCOUNTING(CefPostDataImpl); + IMPLEMENT_LOCKING(CefPostDataImpl); +}; + +// Implementation of CefPostDataElement +class CefPostDataElementImpl : public CefPostDataElement { + public: + CefPostDataElementImpl(); + ~CefPostDataElementImpl(); + + 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; + + void* GetBytes() { return data_.bytes.bytes; } + + void Set(const net::UploadData::Element& element); + void Get(net::UploadData::Element& element); + void Set(const WebKit::WebHTTPBody::Element& element); + void Get(WebKit::WebHTTPBody::Element& element); + + protected: + Type type_; + union { + struct { + void* bytes; + size_t size; + } bytes; + cef_string_t filename; + } data_; + + IMPLEMENT_REFCOUNTING(CefPostDataElementImpl); + IMPLEMENT_LOCKING(CefPostDataElementImpl); +}; + +#endif // CEF_LIBCEF_REQUEST_IMPL_H_ diff --git a/cef1/libcef/response_impl.cc b/cef1/libcef/response_impl.cc new file mode 100644 index 000000000..0dc9c6807 --- /dev/null +++ b/cef1/libcef/response_impl.cc @@ -0,0 +1,115 @@ +// 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/response_impl.h" +#include "libcef/http_header_utils.h" + +#include "base/logging.h" +#include "base/stringprintf.h" +#include "net/http/http_response_headers.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h" + +CefResponseImpl::CefResponseImpl() + : status_code_(0) { +} + +CefResponseImpl::CefResponseImpl(const WebKit::WebURLResponse &response) { + DCHECK(!response.isNull()); + + WebKit::WebString str; + status_code_ = response.httpStatusCode(); + str = response.httpStatusText(); + status_text_ = CefString(str); + str = response.mimeType(); + mime_type_ = CefString(str); + + HttpHeaderUtils::HeaderVisitor visitor(&header_map_); + response.visitHTTPHeaderFields(&visitor); +} + +int CefResponseImpl::GetStatus() { + AutoLock lock_scope(this); + return status_code_; +} + +void CefResponseImpl::SetStatus(int status) { + AutoLock lock_scope(this); + status_code_ = status; +} + +CefString CefResponseImpl::GetStatusText() { + AutoLock lock_scope(this); + return status_text_; +} + +void CefResponseImpl::SetStatusText(const CefString& statusText) { + AutoLock lock_scope(this); + status_text_ = statusText; +} + +CefString CefResponseImpl::GetMimeType() { + AutoLock lock_scope(this); + return mime_type_; +} + +void CefResponseImpl::SetMimeType(const CefString& mimeType) { + AutoLock lock_scope(this); + mime_type_ = mimeType; +} + +CefString CefResponseImpl::GetHeader(const CefString& name) { + AutoLock lock_scope(this); + + 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) { + AutoLock lock_scope(this); + map = header_map_; +} + +void CefResponseImpl::SetHeaderMap(const HeaderMap& headerMap) { + AutoLock lock_scope(this); + header_map_ = headerMap; +} + +net::HttpResponseHeaders* CefResponseImpl::GetResponseHeaders() { + AutoLock lock_scope(this); + + std::string response; + std::string status_text; + + if (status_text_.empty()) + status_text = (status_code_ == 200)?"OK":"ERROR"; + else + status_text = status_text_; + + 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()); + } + } + } + + return new net::HttpResponseHeaders(response); +} diff --git a/cef1/libcef/response_impl.h b/cef1/libcef/response_impl.h new file mode 100644 index 000000000..e4c7a49de --- /dev/null +++ b/cef1/libcef/response_impl.h @@ -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. + +#ifndef CEF_LIBCEF_RESPONSE_IMPL_H_ +#define CEF_LIBCEF_RESPONSE_IMPL_H_ +#pragma once + +#include "include/cef_response.h" + +namespace net { +class HttpResponseHeaders; +} +namespace WebKit { +class WebURLResponse; +}; + +// Implementation of CefResponse. +class CefResponseImpl : public CefResponse { + public: + CefResponseImpl(); + explicit CefResponseImpl(const WebKit::WebURLResponse& response); + ~CefResponseImpl() {} + + // CefResponse API + virtual int GetStatus(); + virtual void SetStatus(int status); + virtual CefString GetStatusText(); + virtual void SetStatusText(const CefString& statusText); + virtual CefString GetMimeType(); + virtual void SetMimeType(const CefString& mimeType); + virtual CefString GetHeader(const CefString& name); + virtual void GetHeaderMap(HeaderMap& headerMap); + virtual void SetHeaderMap(const HeaderMap& headerMap); + + net::HttpResponseHeaders* GetResponseHeaders(); + + protected: + int status_code_; + CefString status_text_; + CefString mime_type_; + HeaderMap header_map_; + + IMPLEMENT_REFCOUNTING(CefResponseImpl); + IMPLEMENT_LOCKING(CefResponseImpl); +}; + +#endif // CEF_LIBCEF_RESPONSE_IMPL_H_ diff --git a/cef1/libcef/scheme_impl.cc b/cef1/libcef/scheme_impl.cc new file mode 100644 index 000000000..4d84143d1 --- /dev/null +++ b/cef1/libcef/scheme_impl.cc @@ -0,0 +1,855 @@ +// Copyright (c) 2011 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_scheme.h" +#include "libcef/browser_devtools_scheme_handler.h" +#include "libcef/browser_impl.h" +#include "libcef/browser_resource_loader_bridge.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" +#include "libcef/request_impl.h" +#include "libcef/response_impl.h" + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "base/logging.h" +#include "base/message_loop.h" +#include "base/string_util.h" +#include "base/synchronization/lock.h" +#include "googleurl/src/url_util.h" +#include "net/base/completion_callback.h" +#include "net/base/load_flags.h" +#include "net/cookies/cookie_monster.h" +#include "net/base/io_buffer.h" +#include "net/base/upload_data.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_about_job.h" +#include "net/url_request/url_request_data_job.h" +#include "net/url_request/url_request_error_job.h" +#include "net/url_request/url_request_file_job.h" +#include "net/url_request/url_request_filter.h" +#include "net/url_request/url_request_ftp_job.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.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" + +using net::URLRequestStatus; +using WebKit::WebSecurityPolicy; +using WebKit::WebString; + +namespace { + +bool IsStandardScheme(const std::string& scheme) { + url_parse::Component scheme_comp(0, scheme.length()); + return url_util::IsStandard(scheme.c_str(), scheme_comp); +} + +void RegisterStandardScheme(const std::string& scheme) { + REQUIRE_UIT(); + url_parse::Component scheme_comp(0, scheme.length()); + if (!url_util::IsStandard(scheme.c_str(), scheme_comp)) + url_util::AddStandardScheme(scheme.c_str()); +} + +// 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 }, + { "file", net::URLRequestFileJob::Factory }, + { "ftp", net::URLRequestFtpJob::Factory }, + { "about", net::URLRequestAboutJob::Factory }, + { "data", net::URLRequestDataJob::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, + 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, 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; +} + + +// net::URLRequestJob implementation. +class CefUrlRequestJob : public net::URLRequestJob { + public: + CefUrlRequestJob(net::URLRequest* request, + CefRefPtr handler) + : net::URLRequestJob(request), + handler_(handler), + remaining_bytes_(0), + response_cookies_save_index_(0), + ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) { + } + + virtual ~CefUrlRequestJob() { + } + + virtual void Start() OVERRIDE { + REQUIRE_IOT(); + + cef_request_ = CefRequest::CreateRequest(); + + // 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::const_iterator it; + CefRequest::HeaderMap headerMap; + cef_request_->GetHeaderMap(headerMap); + bool changed = false; + + if (!context->accept_language().empty()) { + it = headerMap.find(net::HttpRequestHeaders::kAcceptLanguage); + if (it == headerMap.end()) { + headerMap.insert( + std::make_pair(net::HttpRequestHeaders::kAcceptLanguage, + context->accept_language())); + } + changed = true; + } + + if (!context->accept_charset().empty()) { + it = headerMap.find(net::HttpRequestHeaders::kAcceptCharset); + if (it == headerMap.end()) { + headerMap.insert( + std::make_pair(net::HttpRequestHeaders::kAcceptCharset, + context->accept_charset())); + } + changed = true; + } + + it = headerMap.find(net::HttpRequestHeaders::kUserAgent); + if (it == headerMap.end()) { + headerMap.insert( + std::make_pair(net::HttpRequestHeaders::kUserAgent, + context->GetUserAgent(request_->url()))); + changed = true; + } + + if (changed) + cef_request_->SetHeaderMap(headerMap); + } + + AddCookieHeaderAndStart(); + } + + void 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(&CefUrlRequestJob::CheckCookiePolicyAndLoad, + weak_factory_.GetWeakPtr())); + } else { + DoLoadCookies(); + } + } else { + DoStartTransaction(); + } + } + + void DoLoadCookies() { + net::CookieOptions options; + options.set_include_httponly(); + request_->context()->cookie_store()->GetCookiesWithInfoAsync( + request_->url(), options, + base::Bind(&CefUrlRequestJob::OnCookiesLoaded, + weak_factory_.GetWeakPtr())); + } + + void CheckCookiePolicyAndLoad( + const net::CookieList& cookie_list) { + if (CanGetCookies(cookie_list)) + DoLoadCookies(); + else + DoStartTransaction(); + } + + void OnCookiesLoaded( + const std::string& cookie_line, + const std::vector& cookie_infos) { + 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 DoStartTransaction() { + // We may have been canceled while retrieving cookies. + if (GetStatus().is_success()) { + StartTransaction(); + } else { + NotifyCanceled(); + } + } + + void StartTransaction() { + if (!callback_) + callback_ = new Callback(this); + + // 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(); + } + } + + virtual void Kill() OVERRIDE { + REQUIRE_IOT(); + + // Notify the handler that the request has been canceled. + handler_->Cancel(); + + if (callback_) { + callback_->Detach(); + callback_ = NULL; + } + + net::URLRequestJob::Kill(); + } + + virtual bool ReadRawData(net::IOBuffer* dest, int dest_size, int *bytes_read) + OVERRIDE { + REQUIRE_IOT(); + + DCHECK_NE(dest_size, 0); + DCHECK(bytes_read); + + if (remaining_bytes_ == 0) { + // No more data to read. + *bytes_read = 0; + return true; + } else if (remaining_bytes_ > 0 && remaining_bytes_ < dest_size) { + // The handler knows the content size beforehand. + dest_size = static_cast(remaining_bytes_); + } + + // 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; + return true; + } else if (*bytes_read == 0) { + if (!GetStatus().is_io_pending()) { + // Report our status as 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; + } + + virtual void GetResponseInfo(net::HttpResponseInfo* info) OVERRIDE { + REQUIRE_IOT(); + + info->headers = GetResponseHeaders(); + } + + virtual bool IsRedirectResponse(GURL* location, int* http_status_code) + OVERRIDE { + 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; + } + + virtual bool GetMimeType(std::string* mime_type) const OVERRIDE { + REQUIRE_IOT(); + + if (response_.get()) + *mime_type = response_->GetMimeType(); + return true; + } + + CefRefPtr handler_; + CefRefPtr response_; + + private: + void SendHeaders() { + REQUIRE_IOT(); + + // We may have been orphaned... + if (!request()) + return; + + response_ = new CefResponseImpl(); + remaining_bytes_ = 0; + + CefString redirectUrl; + + // Get header information from the handler. + handler_->GetResponseHeaders(response_, remaining_bytes_, redirectUrl); + 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(); + } + + net::HttpResponseHeaders* GetResponseHeaders() { + DCHECK(response_); + if (!response_headers_.get()) { + CefResponseImpl* responseImpl = + static_cast(response_.get()); + response_headers_ = responseImpl->GetResponseHeaders(); + } + return response_headers_; + } + + void 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 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(); + if (CanSetCookie( + response_cookies_[response_cookies_save_index_], &options)) { + request_->context()->cookie_store()->SetCookieWithOptionsAsync( + request_->url(), response_cookies_[response_cookies_save_index_], + options, base::Bind(&CefUrlRequestJob::OnCookieSaved, + weak_factory_.GetWeakPtr())); + return; + } + + CookieHandled(); + } + + void OnCookieSaved(bool cookie_status) { + CookieHandled(); + } + + void CookieHandled() { + response_cookies_save_index_++; + // We may have been canceled within OnSetCookie. + if (GetStatus().is_success()) { + SaveNextCookie(); + } else { + NotifyCanceled(); + } + } + + void 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); + } + } + + // Client callback for asynchronous response continuation. + class Callback : public CefSchemeHandlerCallback { + public: + explicit Callback(CefUrlRequestJob* job) + : job_(job), + dest_(NULL), + dest_size_() {} + + virtual void HeadersAvailable() OVERRIDE { + if (CefThread::CurrentlyOn(CefThread::IO)) { + // Currently on IO thread. + if (job_ && !job_->has_response_started()) { + // Send header information. + job_->SendHeaders(); + } + } else { + // Execute this method on the IO thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(&Callback::HeadersAvailable, this)); + } + } + + virtual void BytesAvailable() OVERRIDE { + if (CefThread::CurrentlyOn(CefThread::IO)) { + // Currently on IO thread. + if (job_ && 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)) { + if (bytes_read > 0) { + // Clear the IO_PENDING status. + job_->SetStatus(URLRequestStatus()); + + // Notify about the available bytes. + job_->NotifyReadComplete(bytes_read); + + dest_ = NULL; + dest_size_ = 0; + } else { + // All done. + job_->NotifyDone(URLRequestStatus()); + } + } else if (!job_->GetStatus().is_io_pending()) { + // Failed due to an error. + NOTREACHED() << + "ReadRawData returned false without setting IO as pending"; + job_->NotifyDone(URLRequestStatus()); + } + } + } else { + // Execute this method on the IO thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(&Callback::BytesAvailable, this)); + } + } + + virtual void Cancel() OVERRIDE { + if (CefThread::CurrentlyOn(CefThread::IO)) { + // Currently on IO thread. + if (job_) + job_->Kill(); + } else { + // Execute this method on the IO thread. + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(&Callback::Cancel, this)); + } + } + + void Detach() { + REQUIRE_IOT(); + job_ = NULL; + } + + void SetDestination(net::IOBuffer* dest, int dest_size) { + dest_ = dest; + dest_size_ = dest_size; + } + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + + private: + CefUrlRequestJob* job_; + + net::IOBuffer* dest_; + int dest_size_; + + IMPLEMENT_REFCOUNTING(Callback); + }; + + 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::WeakPtrFactory weak_factory_; + + DISALLOW_COPY_AND_ASSIGN(CefUrlRequestJob); +}; + + +// 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 + virtual net::URLRequestJob* MaybeCreateJob( + net::URLRequest* request) const OVERRIDE { + REQUIRE_IOT(); + return CefUrlRequestManager::GetInstance()->GetRequestJob(request, + 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; + } + + 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(); + + handler_map_[make_pair(scheme_lower, domain_lower)] = factory; + + net::URLRequestJobFactory* job_factory = + const_cast( + _Context->request_context()->job_factory()); + + job_factory->SetProtocolHandler(scheme_lower, + new ProtocolHandler(scheme_lower)); + + return true; + } + + void RemoveFactory(const std::string& scheme, + const std::string& domain) { + 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); + } + + // Clear all the existing URL handlers and unregister the ProtocolFactory. + void ClearFactories() { + REQUIRE_IOT(); + + net::URLRequestJobFactory* job_factory = + const_cast( + _Context->request_context()->job_factory()); + + // Unregister with the ProtocolFactory. + 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) { + job_factory->SetProtocolHandler(*scheme, NULL); + } + + handler_map_.clear(); + } + + // Check if a scheme has already been registered. + bool HasRegisteredScheme(const std::string& scheme) { + std::string scheme_lower = ToLower(scheme); + + // Don't register builtin schemes. + if (IsBuiltinScheme(scheme_lower)) + return true; + + scheme_set_lock_.Acquire(); + bool registered = (scheme_set_.find(scheme_lower) != scheme_set_.end()); + scheme_set_lock_.Release(); + return registered; + } + + // Register a scheme. + bool RegisterScheme(const std::string& scheme, + bool is_standard, + bool is_local, + bool is_display_isolated) { + if (HasRegisteredScheme(scheme)) { + NOTREACHED() << "Scheme already registered: " << scheme; + return false; + } + + std::string scheme_lower = ToLower(scheme); + + scheme_set_lock_.Acquire(); + scheme_set_.insert(scheme_lower); + scheme_set_lock_.Release(); + + if (is_standard) + RegisterStandardScheme(scheme_lower); + if (is_local) { + WebSecurityPolicy::registerURLSchemeAsLocal( + WebString::fromUTF8(scheme_lower)); + } + if (is_display_isolated) { + WebSecurityPolicy::registerURLSchemeAsDisplayIsolated( + WebString::fromUTF8(scheme_lower)); + } + + return true; + } + + private: + // 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, + const std::string& scheme) { + net::URLRequestJob* job = NULL; + CefRefPtr factory = + GetHandlerFactory(request, scheme); + if (factory) { + // Call the handler factory to create the handler for the request. + CefRefPtr requestPtr(new CefRequestImpl()); + static_cast(requestPtr.get())->Set(request); + CefRefPtr browser = + BrowserResourceLoaderBridge::GetBrowserForRequest(request); + CefRefPtr handler = + factory->Create(browser.get(), scheme, requestPtr); + if (handler.get()) + job = new CefUrlRequestJob(request, handler); + } + + if (!job && IsBuiltinScheme(scheme)) { + // Give the built-in scheme handler a chance to handle the request. + job = GetBuiltinSchemeRequestJob(request, scheme); + } + +#ifndef NDEBUG + if (job) + DLOG(INFO) << "CefUrlRequestManager hit for " << request->url().spec(); +#endif + + return job; + } + + // Map (scheme, domain) to factories. This map will only be accessed on the IO + // thread. + typedef std::map, + CefRefPtr > HandlerMap; + HandlerMap handler_map_; + + // Set of registered schemes. This set may be accessed from multiple threads. + typedef std::set SchemeSet; + SchemeSet scheme_set_; + base::Lock scheme_set_lock_; + + DISALLOW_EVIL_CONSTRUCTORS(CefUrlRequestManager); +}; + +base::LazyInstance g_manager = LAZY_INSTANCE_INITIALIZER; + +CefUrlRequestManager* CefUrlRequestManager::GetInstance() { + return g_manager.Pointer(); +} + +} // namespace + + +bool CefRegisterCustomScheme(const CefString& scheme_name, + bool is_standard, + bool is_local, + bool is_display_isolated) { + // Verify that the context is in a valid state. + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return false; + } + + if (CefThread::CurrentlyOn(CefThread::UI)) { + // Must be executed on the UI thread because it calls WebKit APIs. + return CefUrlRequestManager::GetInstance()->RegisterScheme(scheme_name, + is_standard, is_local, is_display_isolated); + } else { + // Verify that the scheme has not already been registered. + if (CefUrlRequestManager::GetInstance()->HasRegisteredScheme(scheme_name)) { + NOTREACHED() << "Scheme already registered: " << scheme_name; + return false; + } + + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(base::IgnoreResult(&CefRegisterCustomScheme), scheme_name, + is_standard, is_local, is_display_isolated)); + return true; + } +} + +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()) { + NOTREACHED() << "context not valid"; + return false; + } + + if (CefThread::CurrentlyOn(CefThread::IO)) { + return CefUrlRequestManager::GetInstance()->AddFactory(scheme_name, + domain_name, + factory); + } else { + CefThread::PostTask(CefThread::IO, FROM_HERE, + 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()) { + NOTREACHED() << "context not valid"; + return false; + } + + if (CefThread::CurrentlyOn(CefThread::IO)) { + CefUrlRequestManager::GetInstance()->ClearFactories(); + + // Re-register the DevTools scheme handler. + RegisterDevToolsSchemeHandler(false); + } else { + CefThread::PostTask(CefThread::IO, FROM_HERE, + base::Bind(base::IgnoreResult(&CefClearSchemeHandlerFactories))); + } + + return true; +} diff --git a/cef1/libcef/simple_clipboard_impl.cc b/cef1/libcef/simple_clipboard_impl.cc new file mode 100644 index 000000000..2fa02b8f9 --- /dev/null +++ b/cef1/libcef/simple_clipboard_impl.cc @@ -0,0 +1,117 @@ +// 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/simple_clipboard_impl.h" + +#include "base/lazy_instance.h" +#include "base/stl_util.h" +#include "base/string16.h" +#include "googleurl/src/gurl.h" +#include "third_party/skia/include/core/SkBitmap.h" +#if defined(USE_SYSTEM_ZLIB) +#include +#else +#include "third_party/zlib/zlib.h" +#endif +#include "ui/base/clipboard/clipboard.h" +#include "ui/gfx/codec/png_codec.h" +#include "ui/gfx/size.h" +#include "webkit/glue/webkit_glue.h" + +namespace { + +base::LazyInstance clipboard = LAZY_INSTANCE_INITIALIZER; + +} // anonymous namespace + +SimpleClipboardClient::SimpleClipboardClient() { +} + +SimpleClipboardClient::~SimpleClipboardClient() { +} + + +ui::Clipboard* SimpleClipboardClient::GetClipboard() { + return clipboard.Pointer(); +} + +uint64 SimpleClipboardClient::GetSequenceNumber(ui::Clipboard::Buffer buffer) { + return GetClipboard()->GetSequenceNumber(buffer); +} + +bool SimpleClipboardClient::IsFormatAvailable( + const ui::Clipboard::FormatType& format, + ui::Clipboard::Buffer buffer) { + return GetClipboard()->IsFormatAvailable(format, buffer); +} + +void SimpleClipboardClient::Clear(ui::Clipboard::Buffer buffer) { + GetClipboard()->Clear(buffer); +} + +void SimpleClipboardClient::ReadAvailableTypes(ui::Clipboard::Buffer buffer, + std::vector* types, + bool* contains_filenames) { + return GetClipboard()->ReadAvailableTypes(buffer, types, + contains_filenames); +} + +void SimpleClipboardClient::ReadText(ui::Clipboard::Buffer buffer, + string16* result) { + GetClipboard()->ReadText(buffer, result); +} + +void SimpleClipboardClient::ReadAsciiText(ui::Clipboard::Buffer buffer, + std::string* result) { + GetClipboard()->ReadAsciiText(buffer, result); +} + +void SimpleClipboardClient::ReadHTML(ui::Clipboard::Buffer buffer, + string16* markup, + GURL* url, uint32* fragment_start, + uint32* fragment_end) { + std::string url_str; + GetClipboard()->ReadHTML(buffer, markup, url ? &url_str : NULL, + fragment_start, fragment_end); + if (url) + *url = GURL(url_str); +} + +void SimpleClipboardClient::ReadRTF(ui::Clipboard::Buffer buffer, + std::string* result) { + GetClipboard()->ReadRTF(buffer, result); +} + +void SimpleClipboardClient::ReadImage(ui::Clipboard::Buffer buffer, + std::string* data) { + SkBitmap bitmap = GetClipboard()->ReadImage(buffer); + if (bitmap.isNull()) + return; + + std::vector png_data; + SkAutoLockPixels lock(bitmap); + if (gfx::PNGCodec::EncodeWithCompressionLevel( + static_cast(bitmap.getPixels()), + gfx::PNGCodec::FORMAT_BGRA, + gfx::Size(bitmap.width(), bitmap.height()), + bitmap.rowBytes(), + false, + std::vector(), + Z_BEST_SPEED, + &png_data)) { + data->assign(reinterpret_cast(vector_as_array(&png_data)), + png_data.size()); + } +} + +void SimpleClipboardClient::ReadCustomData(ui::Clipboard::Buffer buffer, + const string16& type, + string16* data) { + GetClipboard()->ReadCustomData(buffer, type, data); +} + +webkit_glue::ClipboardClient::WriteContext* +SimpleClipboardClient::CreateWriteContext() { + return NULL; +} diff --git a/cef1/libcef/simple_clipboard_impl.h b/cef1/libcef/simple_clipboard_impl.h new file mode 100644 index 000000000..509b5c6ca --- /dev/null +++ b/cef1/libcef/simple_clipboard_impl.h @@ -0,0 +1,45 @@ +// 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_SIMPLE_CLIPBOARD_IMPL_H_ +#define CEF_LIBCEF_SIMPLE_CLIPBOARD_IMPL_H_ +#pragma once + +#include +#include + +#include "base/compiler_specific.h" +#include "webkit/glue/clipboard_client.h" + +class SimpleClipboardClient : public webkit_glue::ClipboardClient { + public: + SimpleClipboardClient(); + virtual ~SimpleClipboardClient(); + + virtual ui::Clipboard* GetClipboard() OVERRIDE; + virtual uint64 GetSequenceNumber(ui::Clipboard::Buffer buffer) OVERRIDE; + virtual bool IsFormatAvailable(const ui::Clipboard::FormatType& format, + ui::Clipboard::Buffer buffer) OVERRIDE; + virtual void Clear(ui::Clipboard::Buffer buffer) OVERRIDE; + virtual void ReadAvailableTypes(ui::Clipboard::Buffer buffer, + std::vector* types, + bool* contains_filenames) OVERRIDE; + virtual void ReadText(ui::Clipboard::Buffer buffer, + string16* result) OVERRIDE; + virtual void ReadAsciiText(ui::Clipboard::Buffer buffer, + std::string* result) OVERRIDE; + virtual void ReadHTML(ui::Clipboard::Buffer buffer, string16* markup, + GURL* url, uint32* fragment_start, + uint32* fragment_end) OVERRIDE; + virtual void ReadRTF(ui::Clipboard::Buffer buffer, + std::string* result) OVERRIDE; + virtual void ReadImage(ui::Clipboard::Buffer buffer, + std::string* data) OVERRIDE; + virtual void ReadCustomData(ui::Clipboard::Buffer buffer, + const string16& type, + string16* data) OVERRIDE; + virtual WriteContext* CreateWriteContext() OVERRIDE; +}; + +#endif // CEF_LIBCEF_SIMPLE_CLIPBOARD_IMPL_H_ diff --git a/cef1/libcef/sqlite_diagnostics_stub.cc b/cef1/libcef/sqlite_diagnostics_stub.cc new file mode 100644 index 000000000..a5b9fcf85 --- /dev/null +++ b/cef1/libcef/sqlite_diagnostics_stub.cc @@ -0,0 +1,26 @@ +// 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 "chrome/browser/diagnostics/sqlite_diagnostics.h" +#include "content/public/common/url_constants.h" + +// Used by SQLitePersistentCookieStore +sql::ErrorDelegate* GetErrorHandlerForCookieDb() { + return NULL; +} + +namespace chrome { + +// Used by ClearOnExitPolicy +const char kHttpScheme[] = "http"; +const char kHttpsScheme[] = "https"; + +} // namespace chrome + +namespace content { + +// Used by ClearOnExitPolicy +const char kStandardSchemeSeparator[] = "://"; + +} // namespace content diff --git a/cef1/libcef/stream_impl.cc b/cef1/libcef/stream_impl.cc new file mode 100644 index 000000000..2f5afee1a --- /dev/null +++ b/cef1/libcef/stream_impl.cc @@ -0,0 +1,309 @@ +// 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/stream_impl.h" +#include +#include "base/logging.h" + +// Static functions + +CefRefPtr CefStreamReader::CreateForFile( + const CefString& fileName) { + CefRefPtr reader; + std::string fileNameStr = fileName; + FILE* file = fopen(fileNameStr.c_str(), "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()); + CefRefPtr writer; + std::string fileNameStr = fileName; + FILE* file = fopen(fileNameStr.c_str(), "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() { + AutoLock lock_scope(this); + if (close_) + fclose(file_); +} + +size_t CefFileReader::Read(void* ptr, size_t size, size_t n) { + AutoLock lock_scope(this); + return fread(ptr, size, n, file_); +} + +int CefFileReader::Seek(int64 offset, int whence) { + AutoLock lock_scope(this); +#if defined(OS_WIN) + return _fseeki64(file_, offset, whence); +#else + return fseek(file_, offset, whence); +#endif +} + +int64 CefFileReader::Tell() { + AutoLock lock_scope(this); +#if defined(OS_WIN) + return _ftelli64(file_); +#else + return ftell(file_); +#endif +} + +int CefFileReader::Eof() { + AutoLock lock_scope(this); + return feof(file_); +} + + +// CefFileWriter + +CefFileWriter::CefFileWriter(FILE* file, bool close) + : file_(file), + close_(close) { +} + +CefFileWriter::~CefFileWriter() { + AutoLock lock_scope(this); + if (close_) + fclose(file_); +} + +size_t CefFileWriter::Write(const void* ptr, size_t size, size_t n) { + AutoLock lock_scope(this); + return (size_t)fwrite(ptr, size, n, file_); +} + +int CefFileWriter::Seek(int64 offset, int whence) { + AutoLock lock_scope(this); + return fseek(file_, offset, whence); +} + +int64 CefFileWriter::Tell() { + AutoLock lock_scope(this); + return ftell(file_); +} + +int CefFileWriter::Flush() { + AutoLock lock_scope(this); + 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) { + AutoLock lock_scope(this); + 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; + AutoLock lock_scope(this); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > datasize_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { + int64 offset_abs = 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() { + AutoLock lock_scope(this); + return offset_; +} + +int CefBytesReader::Eof() { + AutoLock lock_scope(this); + return (offset_ >= datasize_); +} + +void CefBytesReader::SetData(void* data, int64 datasize, bool copy) { + AutoLock lock_scope(this); + 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() { + AutoLock lock_scope(this); + if (data_) + free(data_); +} + +size_t CefBytesWriter::Write(const void* ptr, size_t size, size_t n) { + AutoLock lock_scope(this); + 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; + AutoLock lock_scope(this); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > datasize_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { + int64 offset_abs = 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() { + AutoLock lock_scope(this); + return offset_; +} + +int CefBytesWriter::Flush() { + return 0; +} + +std::string CefBytesWriter::GetDataString() { + AutoLock lock_scope(this); + std::string str(reinterpret_cast(data_), offset_); + return str; +} + +size_t CefBytesWriter::Grow(size_t size) { + AutoLock lock_scope(this); + 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/cef1/libcef/stream_impl.h b/cef1/libcef/stream_impl.h new file mode 100644 index 000000000..034baa7d9 --- /dev/null +++ b/cef1/libcef/stream_impl.h @@ -0,0 +1,154 @@ +// 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. + +#ifndef CEF_LIBCEF_STREAM_IMPL_H_ +#define CEF_LIBCEF_STREAM_IMPL_H_ +#pragma once + +#include +#include +#include "include/cef_stream.h" + +// Implementation of CefStreamReader for files. +class CefFileReader : public CefStreamReader { + public: + CefFileReader(FILE* file, bool close); + virtual ~CefFileReader(); + + 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; + + protected: + bool close_; + FILE* file_; + + IMPLEMENT_REFCOUNTING(CefFileReader); + IMPLEMENT_LOCKING(CefFileReader); +}; + +// Implementation of CefStreamWriter for files. +class CefFileWriter : public CefStreamWriter { + public: + CefFileWriter(FILE* file, bool close); + virtual ~CefFileWriter(); + + 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; + + protected: + FILE* file_; + bool close_; + + IMPLEMENT_REFCOUNTING(CefFileWriter); + IMPLEMENT_LOCKING(CefFileWriter); +}; + +// Implementation of CefStreamReader for byte buffers. +class CefBytesReader : public CefStreamReader { + public: + CefBytesReader(void* data, int64 datasize, bool copy); + virtual ~CefBytesReader(); + + 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; + + 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_; + + IMPLEMENT_REFCOUNTING(CefBytesReader); + IMPLEMENT_LOCKING(CefBytesReader); +}; + +// Implementation of CefStreamWriter for byte buffers. +class CefBytesWriter : public CefStreamWriter { + public: + explicit CefBytesWriter(size_t grow); + virtual ~CefBytesWriter(); + + 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; + + 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_; + + IMPLEMENT_REFCOUNTING(CefBytesWriter); + IMPLEMENT_LOCKING(CefBytesWriter); +}; + +// Implementation of CefStreamReader for handlers. +class CefHandlerReader : public CefStreamReader { + public: + explicit CefHandlerReader(CefRefPtr handler) + : handler_(handler) {} + + virtual size_t Read(void* ptr, size_t size, size_t n) OVERRIDE { + return handler_->Read(ptr, size, n); + } + virtual int Seek(int64 offset, int whence) OVERRIDE { + return handler_->Seek(offset, whence); + } + virtual int64 Tell() OVERRIDE { + return handler_->Tell(); + } + virtual int Eof() OVERRIDE { + return handler_->Eof(); + } + + protected: + CefRefPtr handler_; + + IMPLEMENT_REFCOUNTING(CefHandlerReader); +}; + +// Implementation of CefStreamWriter for handlers. +class CefHandlerWriter : public CefStreamWriter { + public: + explicit CefHandlerWriter(CefRefPtr handler) + : handler_(handler) {} + + virtual size_t Write(const void* ptr, size_t size, size_t n) OVERRIDE { + return handler_->Write(ptr, size, n); + } + virtual int Seek(int64 offset, int whence) OVERRIDE { + return handler_->Seek(offset, whence); + } + virtual int64 Tell() OVERRIDE { + return handler_->Tell(); + } + virtual int Flush() OVERRIDE { + return handler_->Flush(); + } + + protected: + CefRefPtr handler_; + + IMPLEMENT_REFCOUNTING(CefHandlerWriter); +}; + +#endif // CEF_LIBCEF_STREAM_IMPL_H_ diff --git a/cef1/libcef/task_impl.cc b/cef1/libcef/task_impl.cc new file mode 100644 index 000000000..bce6348a4 --- /dev/null +++ b/cef1/libcef/task_impl.cc @@ -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 "include/cef_task.h" +#include "libcef/cef_thread.h" +#include "base/bind.h" + +namespace { + +int GetThreadId(CefThreadId threadId) { + switch (threadId) { + case TID_UI: return CefThread::UI; + case TID_IO: return CefThread::IO; + case TID_FILE: return CefThread::FILE; + }; + NOTREACHED(); + return -1; +} + +} // namespace + +bool CefCurrentlyOn(CefThreadId threadId) { + int id = GetThreadId(threadId); + if (id < 0) + return false; + + return CefThread::CurrentlyOn(static_cast(id)); +} + +bool CefPostTask(CefThreadId threadId, CefRefPtr task) { + int id = GetThreadId(threadId); + if (id < 0) + return false; + + return CefThread::PostTask(static_cast(id), FROM_HERE, + base::Bind(&CefTask::Execute, task, threadId)); +} + +bool CefPostDelayedTask(CefThreadId threadId, CefRefPtr task, + int64 delay_ms) { + int id = GetThreadId(threadId); + if (id < 0) + return false; + + return CefThread::PostDelayedTask(static_cast(id), FROM_HERE, + base::Bind(&CefTask::Execute, task, threadId), delay_ms); +} diff --git a/cef1/libcef/tracker.h b/cef1/libcef/tracker.h new file mode 100644 index 000000000..eb122f022 --- /dev/null +++ b/cef1/libcef/tracker.h @@ -0,0 +1,129 @@ +// 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_TRACKER_H_ +#define CEF_LIBCEF_TRACKER_H_ +#pragma once + +#include "include/cef_base.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() { + track_next_ = NULL; + track_prev_ = NULL; + } + virtual ~CefTrackNode() { + } + + // Returns true if the object is currently being tracked. + bool IsTracked() { return (track_prev_ || track_next_); } + + private: + CefTrackNode* GetTrackPrev() { return track_prev_; } + void SetTrackPrev(CefTrackNode* base) { track_prev_ = base; } + CefTrackNode* GetTrackNext() { return track_next_; } + void SetTrackNext(CefTrackNode* base) { track_next_ = base; } + + // Insert a new object into the tracking list before this object. + void InsertTrackPrev(CefTrackNode* object) { + if (track_prev_) + track_prev_->SetTrackNext(object); + object->SetTrackNext(this); + object->SetTrackPrev(track_prev_); + track_prev_ = object; + } + + // Insert a new object into the tracking list after this object. + void InsertTrackNext(CefTrackNode* object) { + if (track_next_) + track_next_->SetTrackPrev(object); + object->SetTrackPrev(this); + object->SetTrackNext(track_next_); + track_next_ = object; + } + + // Remove this object from the tracking list. + void RemoveTracking() { + if (track_next_) + track_next_->SetTrackPrev(track_prev_); + if (track_prev_) + track_prev_->SetTrackNext(track_next_); + track_next_ = NULL; + track_prev_ = NULL; + } + + 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() : object_count_(0) {} + virtual ~CefTrackManager() { + DeleteAll(); + } + + // Add an object to be tracked by this manager. + void Add(CefTrackNode* object) { + Lock(); + if (!object->IsTracked()) { + tracker_.InsertTrackNext(object); + ++object_count_; + } + Unlock(); + } + + // Delete an object tracked by this manager. + bool Delete(CefTrackNode* object) { + bool rv = false; + Lock(); + if (object->IsTracked()) { + object->RemoveTracking(); + delete object; + --object_count_; + rv = true; + } + Unlock(); + return rv; + } + + // Delete all objects tracked by this manager. + void DeleteAll() { + Lock(); + CefTrackNode* next; + do { + next = tracker_.GetTrackNext(); + if (next) { + next->RemoveTracking(); + delete next; + } + } while (next != NULL); + object_count_ = 0; + Unlock(); + } + + // Returns the number of objects currently being tracked. + int GetCount() { return object_count_; } + + private: + CefTrackNode tracker_; + int object_count_; + + IMPLEMENT_REFCOUNTING(CefTrackManager); + IMPLEMENT_LOCKING(CefTrackManager); +}; + +#endif // CEF_LIBCEF_TRACKER_H_ diff --git a/cef1/libcef/url_impl.cc b/cef1/libcef/url_impl.cc new file mode 100644 index 000000000..4ba6818ab --- /dev/null +++ b/cef1/libcef/url_impl.cc @@ -0,0 +1,68 @@ +// 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/cef_url.h" +#include "googleurl/src/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.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; +} diff --git a/cef1/libcef/v8_impl.cc b/cef1/libcef/v8_impl.cc new file mode 100644 index 000000000..064c53407 --- /dev/null +++ b/cef1/libcef/v8_impl.cc @@ -0,0 +1,1475 @@ +// 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 "base/compiler_specific.h" + +#include "third_party/WebKit/Source/WebCore/config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "V8Proxy.h" // NOLINT(build/include) +#include "V8RecursionScope.h" // NOLINT(build/include) +MSVC_POP_WARNING(); +#undef LOG + +#include "libcef/v8_impl.h" + +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/tracker.h" + +#include "base/bind.h" +#include "base/lazy_instance.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptController.h" + +#define CEF_REQUIRE_UI_THREAD(var) \ + if (!CefThread::CurrentlyOn(CefThread::UI)) { \ + NOTREACHED() << "called on invalid thread"; \ + return var; \ + } + +#define CEF_REQUIRE_VALID_CONTEXT(var) \ + if (!CONTEXT_STATE_VALID()) { \ + NOTREACHED() << "context not valid"; \ + return var; \ + } + +namespace { + +static const char kCefTrackObject[] = "Cef::TrackObject"; + +// Memory manager. + +base::LazyInstance g_v8_tracker = LAZY_INSTANCE_INITIALIZER; + +class V8TrackObject : public CefTrackNode { + public: + V8TrackObject() + : external_memory_(0) { + } + ~V8TrackObject() { + if (external_memory_ != 0) + v8::V8::AdjustAmountOfExternalAllocatedMemory(-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) + v8::V8::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::New(kCefTrackObject), + v8::External::Wrap(this)); + } + + // Retrieve the track object for the specified V8 object. + static V8TrackObject* Unwrap(v8::Handle object) { + v8::Local value = + object->GetHiddenValue(v8::String::New(kCefTrackObject)); + if (!value.IsEmpty()) + return static_cast(v8::External::Unwrap(value)); + + return NULL; + } + + private: + 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_; +}; + +void TrackAdd(CefTrackNode* object) { + g_v8_tracker.Pointer()->Add(object); +} + +void TrackDelete(CefTrackNode* object) { + g_v8_tracker.Pointer()->Delete(object); +} + +// Callback for weak persistent reference destruction. +void TrackDestructor(v8::Persistent object, void* parameter) { + if (parameter) + TrackDelete(static_cast(parameter)); + + object.Dispose(); + object.Clear(); +} + + +// Return the browser associated with the specified WebFrame. +CefRefPtr FindBrowserForFrame(WebKit::WebFrame *frame) { + CefContext::AutoLock lock_scope(_Context); + + CefContext::BrowserList *list = _Context->GetBrowserList(); + CefContext::BrowserList::const_iterator i; + i = list->begin(); + for (; i != list->end(); ++i) { + WebKit::WebFrame* thisframe = i->get()->UIT_GetMainWebFrame(); + if (thisframe == frame) + return i->get(); + } + + return NULL; +} + +// Convert a CefString to a V8::String. +v8::Handle GetV8String(const CefString& str) { +#if defined(CEF_STRING_TYPE_UTF16) + // Already a UTF16 string. + return v8::String::New( + reinterpret_cast( + const_cast(str.c_str())), + str.length()); +#elif defined(CEF_STRING_TYPE_UTF8) + // Already a UTF8 string. + return v8::String::New(const_cast(str.c_str()), str.length()); +#else + // Convert the string to UTF8. + std::string tmpStr = str; + return v8::String::New(tmpStr.c_str(), 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. +v8::Handle FunctionCallbackImpl(const v8::Arguments& args) { + v8::HandleScope handle_scope; + + CefV8Handler* handler = + static_cast(v8::External::Unwrap(args.Data())); + + CefV8ValueList params; + for (int i = 0; i < args.Length(); i++) + params.push_back(new CefV8ValueImpl(args[i])); + + CefString func_name; + GetCefString(v8::Handle::Cast(args.Callee()->GetName()), + func_name); + CefRefPtr object = new CefV8ValueImpl(args.This()); + CefRefPtr retval; + CefString exception; + + if (handler->Execute(func_name, object, params, retval, exception)) { + if (!exception.empty()) { + return v8::ThrowException(v8::Exception::Error(GetV8String(exception))); + } else { + CefV8ValueImpl* rv = static_cast(retval.get()); + if (rv) + return rv->GetHandle(); + } + } + + return v8::Undefined(); +} + +// V8 Accessor callbacks +v8::Handle AccessorGetterCallbackImpl(v8::Local property, + const v8::AccessorInfo& info) { + v8::HandleScope handle_scope; + + v8::Handle obj = info.This(); + + CefRefPtr accessorPtr; + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) + accessorPtr = tracker->GetAccessor(); + + if (accessorPtr.get()) { + CefRefPtr retval; + CefRefPtr object = new CefV8ValueImpl(obj); + CefString name, exception; + GetCefString(property, name); + if (accessorPtr->Get(name, object, retval, exception)) { + if (!exception.empty()) { + return v8::ThrowException( + v8::Exception::Error(GetV8String(exception))); + } else { + CefV8ValueImpl* rv = static_cast(retval.get()); + if (rv) + return rv->GetHandle(); + } + } + } + + return v8::Undefined(); +} + +void AccessorSetterCallbackImpl(v8::Local property, + v8::Local value, + const v8::AccessorInfo& info) { + v8::HandleScope handle_scope; + + v8::Handle obj = info.This(); + + CefRefPtr accessorPtr; + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) + accessorPtr = tracker->GetAccessor(); + + if (accessorPtr.get()) { + CefRefPtr object = new CefV8ValueImpl(obj); + CefRefPtr cefValue = new CefV8ValueImpl(value); + CefString name, exception; + GetCefString(property, name); + accessorPtr->Set(name, object, cefValue, exception); + if (!exception.empty()) { + v8::ThrowException(v8::Exception::Error(GetV8String(exception))); + return; + } + } +} + +// 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) { + if (handler) { + // The reference will be released when the process exits. + V8TrackObject* object = new V8TrackObject; + object->SetHandler(handler); + TrackAdd(object); + } + } + + virtual v8::Handle GetNativeFunction( + v8::Handle name) { + if (!handler_) + return v8::Handle(); + + return v8::FunctionTemplate::New(FunctionCallbackImpl, + v8::External::Wrap(handler_)); + } + + void UIT_RegisterExtension() { + WebKit::WebScriptController::registerExtension(this); + } + + void AddRef() {} + void Release() {} + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + + 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(); + } + + virtual CefString GetMessage() OVERRIDE { return message_; } + virtual CefString GetSourceLine() OVERRIDE { return source_line_; } + virtual CefString GetScriptResourceName() OVERRIDE { return script_; } + virtual int GetLineNumber() OVERRIDE { return line_number_; } + virtual int GetStartPosition() OVERRIDE { return start_position_; } + virtual int GetEndPosition() OVERRIDE { return end_position_; } + virtual int GetStartColumn() OVERRIDE { return start_column_; } + virtual 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); +}; + +} // namespace + + +// Global functions. + +bool CefRegisterExtension(const CefString& extension_name, + const CefString& javascript_code, + CefRefPtr handler) { + // Verify that the context is in a valid state. + CEF_REQUIRE_VALID_CONTEXT(false); + + V8TrackString* name = new V8TrackString(extension_name); + TrackAdd(name); + V8TrackString* code = new V8TrackString(javascript_code); + TrackAdd(code); + + ExtensionWrapper* wrapper = new ExtensionWrapper(name->GetString(), + code->GetString(), handler.get()); + + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&ExtensionWrapper::UIT_RegisterExtension, wrapper)); + return true; +} + + +// CefV8Context + +// static +CefRefPtr CefV8Context::GetCurrentContext() { + CefRefPtr context; + CEF_REQUIRE_VALID_CONTEXT(context); + CEF_REQUIRE_UI_THREAD(context); + if (v8::Context::InContext()) { + v8::HandleScope handle_scope; + context = new CefV8ContextImpl(v8::Context::GetCurrent()); + } + return context; +} + +// static +CefRefPtr CefV8Context::GetEnteredContext() { + CefRefPtr context; + CEF_REQUIRE_VALID_CONTEXT(context); + CEF_REQUIRE_UI_THREAD(context); + if (v8::Context::InContext()) { + v8::HandleScope handle_scope; + context = new CefV8ContextImpl(v8::Context::GetEntered()); + } + return context; +} + +// static +bool CefV8Context::InContext() { + CEF_REQUIRE_VALID_CONTEXT(false); + CEF_REQUIRE_UI_THREAD(false); + return v8::Context::InContext(); +} + + +// CefV8ContextImpl + +#define CEF_V8_REQUIRE_OBJECT_RETURN(ret) \ + if (!GetHandle()->IsObject()) { \ + NOTREACHED() << "V8 value is not an object"; \ + return ret; \ + } + +#define CEF_V8_REQUIRE_ARRAY_RETURN(ret) \ + if (!GetHandle()->IsArray()) { \ + NOTREACHED() << "V8 value is not an array"; \ + return ret; \ + } + +#define CEF_V8_REQUIRE_FUNCTION_RETURN(ret) \ + if (!GetHandle()->IsFunction()) { \ + NOTREACHED() << "V8 value is not a function"; \ + return ret; \ + } + +CefV8ContextImpl::CefV8ContextImpl(v8::Handle context) + : handle_(new Handle(context)) +#ifndef NDEBUG + , enter_count_(0) +#endif +{ // NOLINT(whitespace/braces) +} + +CefV8ContextImpl::~CefV8ContextImpl() { + DLOG_ASSERT(0 == enter_count_); +} + +CefRefPtr CefV8ContextImpl::GetBrowser() { + CefRefPtr browser; + CEF_REQUIRE_UI_THREAD(browser); + + WebKit::WebFrame* webframe = GetWebFrame(); + if (webframe) + browser = FindBrowserForFrame(webframe->top()); + + return browser; +} + +CefRefPtr CefV8ContextImpl::GetFrame() { + CefRefPtr frame; + CEF_REQUIRE_UI_THREAD(frame); + + WebKit::WebFrame* webframe = GetWebFrame(); + if (webframe) { + CefRefPtr browser; + browser = FindBrowserForFrame(webframe->top()); + if (browser.get()) + frame = browser->UIT_GetCefFrame(webframe); + } + + return frame; +} + +CefRefPtr CefV8ContextImpl::GetGlobal() { + CEF_REQUIRE_UI_THREAD(NULL); + + v8::HandleScope handle_scope; + v8::Context::Scope context_scope(GetHandle()); + return new CefV8ValueImpl(GetHandle()->Global()); +} + +bool CefV8ContextImpl::Enter() { + CEF_REQUIRE_UI_THREAD(false); + GetHandle()->Enter(); +#ifndef NDEBUG + ++enter_count_; +#endif + return true; +} + +bool CefV8ContextImpl::Exit() { + CEF_REQUIRE_UI_THREAD(false); + DLOG_ASSERT(enter_count_ > 0); + GetHandle()->Exit(); +#ifndef NDEBUG + --enter_count_; +#endif + return true; +} + +bool CefV8ContextImpl::IsSame(CefRefPtr that) { + CEF_REQUIRE_UI_THREAD(false); + + v8::HandleScope handle_scope; + + v8::Local thatHandle; + v8::Local thisHandle = GetContext(); + + CefV8ContextImpl* impl = static_cast(that.get()); + if (impl) + thatHandle = impl->GetContext(); + + return (thisHandle == thatHandle); +} + +bool CefV8ContextImpl::Eval(const CefString& code, + CefRefPtr& retval, + CefRefPtr& exception) { + CEF_REQUIRE_UI_THREAD(NULL); + + if (code.empty()) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope; + v8::Context::Scope context_scope(GetHandle()); + v8::Local obj = GetHandle()->Global(); + + // Retrieve the eval function. + v8::Local val = obj->Get(v8::String::New("eval")); + if (val.IsEmpty() || !val->IsFunction()) + return false; + + v8::Local func = v8::Local::Cast(val); + v8::Handle code_val = GetV8String(code); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + v8::Local func_rv; + + retval = NULL; + exception = NULL; + + // Execute the function call using the V8Proxy so that inspector + // instrumentation works. + WebCore::V8Proxy* proxy = WebCore::V8Proxy::retrieve(); + DCHECK(proxy); + if (proxy) + func_rv = proxy->callFunction(func, obj, 1, &code_val); + + if (try_catch.HasCaught()) { + exception = new CefV8ExceptionImpl(try_catch.Message()); + return false; + } else if (!func_rv.IsEmpty()) { + retval = new CefV8ValueImpl(func_rv); + } + return true; +} + +v8::Local CefV8ContextImpl::GetContext() { + return v8::Local::New(GetHandle()); +} + +WebKit::WebFrame* CefV8ContextImpl::GetWebFrame() { + v8::HandleScope handle_scope; + v8::Context::Scope context_scope(GetHandle()); + WebKit::WebFrame* frame = WebKit::WebFrame::frameForCurrentContext(); + return frame; +} + + +// CefV8ValueImpl::Handle + +CefV8ValueImpl::Handle::~Handle() { + if (tracker_) { + TrackAdd(tracker_); + handle_.MakeWeak(tracker_, TrackDestructor); + } else { + handle_.Dispose(); + handle_.Clear(); + } + tracker_ = NULL; +} + + +// CefV8Value + +// static +CefRefPtr CefV8Value::CreateUndefined() { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Undefined()); +} + +// static +CefRefPtr CefV8Value::CreateNull() { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Null()); +} + +// static +CefRefPtr CefV8Value::CreateBool(bool value) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Boolean::New(value)); +} + +// static +CefRefPtr CefV8Value::CreateInt(int32 value) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Int32::New(value)); +} + +// static +CefRefPtr CefV8Value::CreateUInt(uint32 value) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Int32::NewFromUnsigned(value)); +} + +// static +CefRefPtr CefV8Value::CreateDouble(double value) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(v8::Number::New(value)); +} + +// static +CefRefPtr CefV8Value::CreateDate(const CefTime& date) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + // Convert from seconds to milliseconds. + return new CefV8ValueImpl(v8::Date::New(date.GetDoubleT() * 1000)); +} + +// static +CefRefPtr CefV8Value::CreateString(const CefString& value) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + return new CefV8ValueImpl(GetV8String(value)); +} + +// static +CefRefPtr CefV8Value::CreateObject( + CefRefPtr accessor) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + + v8::HandleScope handle_scope; + + v8::Local context = v8::Context::GetCurrent(); + if (context.IsEmpty()) { + NOTREACHED() << "not currently in a V8 context"; + return NULL; + } + + // Create the new V8 object. + v8::Local obj = v8::Object::New(); + + // 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; + tracker->SetAccessor(accessor); + + // Attach the tracker object. + tracker->AttachTo(obj); + + return new CefV8ValueImpl(obj, tracker); +} + +// static +CefRefPtr CefV8Value::CreateArray(int length) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + + v8::HandleScope handle_scope; + + v8::Local context = v8::Context::GetCurrent(); + 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; + + // Create the new V8 array. + v8::Local arr = v8::Array::New(length); + + // Attach the tracker object. + tracker->AttachTo(arr); + + return new CefV8ValueImpl(arr, tracker); +} + +// static +CefRefPtr CefV8Value::CreateFunction( + const CefString& name, + CefRefPtr handler) { + CEF_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + + if (!handler.get()) { + NOTREACHED() << "invalid parameter"; + return NULL; + } + + v8::HandleScope handle_scope; + + v8::Local context = v8::Context::GetCurrent(); + if (context.IsEmpty()) { + NOTREACHED() << "not currently in a V8 context"; + return NULL; + } + + // Create a new V8 function template. + v8::Local tmpl = v8::FunctionTemplate::New(); + + v8::Local data = v8::External::Wrap(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(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; + 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. + return new CefV8ValueImpl(func, tracker); +} + + +// CefV8ValueImpl + +CefV8ValueImpl::CefV8ValueImpl(v8::Handle value, + CefTrackNode* tracker) + : handle_(new Handle(value, tracker)), + rethrow_exceptions_(false) { +} + +CefV8ValueImpl::~CefV8ValueImpl() { +} + +bool CefV8ValueImpl::IsUndefined() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsUndefined(); +} + +bool CefV8ValueImpl::IsNull() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsNull(); +} + +bool CefV8ValueImpl::IsBool() { + CEF_REQUIRE_UI_THREAD(false); + return (GetHandle()->IsBoolean() || GetHandle()->IsTrue() + || GetHandle()->IsFalse()); +} + +bool CefV8ValueImpl::IsInt() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsInt32(); +} + +bool CefV8ValueImpl::IsUInt() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsUint32(); +} + +bool CefV8ValueImpl::IsDouble() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsNumber(); +} + +bool CefV8ValueImpl::IsDate() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsDate(); +} + +bool CefV8ValueImpl::IsString() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsString(); +} + +bool CefV8ValueImpl::IsObject() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsObject(); +} + +bool CefV8ValueImpl::IsArray() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsArray(); +} + +bool CefV8ValueImpl::IsFunction() { + CEF_REQUIRE_UI_THREAD(false); + return GetHandle()->IsFunction(); +} + +bool CefV8ValueImpl::IsSame(CefRefPtr that) { + CEF_REQUIRE_UI_THREAD(false); + + v8::HandleScope handle_scope; + + v8::Handle thatHandle; + v8::Handle thisHandle = GetHandle(); + + CefV8ValueImpl* impl = static_cast(that.get()); + if (impl) + thatHandle = impl->GetHandle(); + + return (thisHandle == thatHandle); +} + +bool CefV8ValueImpl::GetBoolValue() { + CEF_REQUIRE_UI_THREAD(false); + if (GetHandle()->IsTrue()) { + return true; + } else if (GetHandle()->IsFalse()) { + return false; + } else { + v8::HandleScope handle_scope; + v8::Local val = GetHandle()->ToBoolean(); + return val->Value(); + } +} + +int32 CefV8ValueImpl::GetIntValue() { + CEF_REQUIRE_UI_THREAD(0); + v8::HandleScope handle_scope; + v8::Local val = GetHandle()->ToInt32(); + return val->Value(); +} + +uint32 CefV8ValueImpl::GetUIntValue() { + CEF_REQUIRE_UI_THREAD(0); + v8::HandleScope handle_scope; + v8::Local val = GetHandle()->ToUint32(); + return val->Value(); +} + +double CefV8ValueImpl::GetDoubleValue() { + CEF_REQUIRE_UI_THREAD(0.); + v8::HandleScope handle_scope; + v8::Local val = GetHandle()->ToNumber(); + return val->Value(); +} + +CefTime CefV8ValueImpl::GetDateValue() { + CEF_REQUIRE_UI_THREAD(CefTime(0.)); + v8::HandleScope handle_scope; + v8::Local val = GetHandle()->ToNumber(); + // Convert from milliseconds to seconds. + return CefTime(val->Value() / 1000); +} + +CefString CefV8ValueImpl::GetStringValue() { + CefString rv; + CEF_REQUIRE_UI_THREAD(rv); + v8::HandleScope handle_scope; + GetCefString(GetHandle()->ToString(), rv); + return rv; +} + +bool CefV8ValueImpl::IsUserCreated() { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + return (tracker != NULL); +} + +bool CefV8ValueImpl::HasException() { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + return (last_exception_.get() != NULL); +} + +CefRefPtr CefV8ValueImpl::GetException() { + CEF_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + return last_exception_; +} + +bool CefV8ValueImpl::ClearException() { + CEF_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + last_exception_ = NULL; + return true; +} + +bool CefV8ValueImpl::WillRethrowExceptions() { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + return rethrow_exceptions_; +} + +bool CefV8ValueImpl::SetRethrowExceptions(bool rethrow) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + rethrow_exceptions_ = rethrow; + return true; +} + +bool CefV8ValueImpl::HasValue(const CefString& key) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (key.empty()) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + return obj->Has(GetV8String(key)); +} + +bool CefV8ValueImpl::HasValue(int index) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + return obj->Has(index); +} + +bool CefV8ValueImpl::DeleteValue(const CefString& key) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (key.empty()) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool del = obj->Delete(GetV8String(key)); + return (!HasCaught(try_catch) && del); +} + +bool CefV8ValueImpl::DeleteValue(int index) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->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_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + if (key.empty()) { + NOTREACHED() << "invalid input parameter"; + return NULL; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + v8::Local value = obj->Get(GetV8String(key)); + if (!HasCaught(try_catch) && !value.IsEmpty()) + return new CefV8ValueImpl(value); + return NULL; +} + +CefRefPtr CefV8ValueImpl::GetValue(int index) { + CEF_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return NULL; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + v8::Local value = obj->Get(v8::Number::New(index)); + if (!HasCaught(try_catch) && !value.IsEmpty()) + return new CefV8ValueImpl(value); + return NULL; +} + +bool CefV8ValueImpl::SetValue(const CefString& key, + CefRefPtr value, + PropertyAttribute attribute) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + CefV8ValueImpl* impl = static_cast(value.get()); + if (impl && !key.empty()) { + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool set = obj->Set(GetV8String(key), impl->GetHandle(), + static_cast(attribute)); + return (!HasCaught(try_catch) && set); + } else { + NOTREACHED() << "invalid input parameter"; + return false; + } +} + +bool CefV8ValueImpl::SetValue(int index, CefRefPtr value) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (index < 0) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + CefV8ValueImpl* impl = static_cast(value.get()); + if (impl) { + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool set = obj->Set(index, impl->GetHandle()); + return (!HasCaught(try_catch) && set); + } else { + NOTREACHED() << "invalid input parameter"; + return false; + } +} + +bool CefV8ValueImpl::SetValue(const CefString& key, AccessControl settings, + PropertyAttribute attribute) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + if (key.empty()) { + NOTREACHED() << "invalid input parameter"; + return false; + } + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + CefRefPtr accessorPtr; + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) + accessorPtr = tracker->GetAccessor(); + + // Verify that an accessor exists for this object. + if (!accessorPtr.get()) + return false; + + v8::AccessorGetter getter = AccessorGetterCallbackImpl; + v8::AccessorSetter setter = (attribute & V8_PROPERTY_ATTRIBUTE_READONLY) ? + NULL : AccessorSetterCallbackImpl; + + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + bool set = obj->SetAccessor(GetV8String(key), getter, setter, obj, + static_cast(settings), + static_cast(attribute)); + return (!HasCaught(try_catch) && set); +} + +bool CefV8ValueImpl::GetKeys(std::vector& keys) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->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(i)); + CefString str; + GetCefString(value->ToString(), str); + keys.push_back(str); + } + return true; +} + +bool CefV8ValueImpl::SetUserData(CefRefPtr user_data) { + CEF_REQUIRE_UI_THREAD(false); + CEF_V8_REQUIRE_OBJECT_RETURN(false); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) { + tracker->SetUserData(user_data); + return true; + } + + return false; +} + +CefRefPtr CefV8ValueImpl::GetUserData() { + CEF_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_OBJECT_RETURN(NULL); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) + return tracker->GetUserData(); + + return NULL; +} + +int CefV8ValueImpl::GetExternallyAllocatedMemory() { + CEF_REQUIRE_UI_THREAD(0); + CEF_V8_REQUIRE_OBJECT_RETURN(0); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) + return tracker->GetExternallyAllocatedMemory(); + + return 0; +} + +int CefV8ValueImpl::AdjustExternallyAllocatedMemory(int change_in_bytes) { + CEF_REQUIRE_UI_THREAD(0); + CEF_V8_REQUIRE_OBJECT_RETURN(0); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(obj); + if (tracker) + return tracker->AdjustExternallyAllocatedMemory(change_in_bytes); + + return 0; +} + +int CefV8ValueImpl::GetArrayLength() { + CEF_REQUIRE_UI_THREAD(0); + CEF_V8_REQUIRE_ARRAY_RETURN(0); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + v8::Local arr = v8::Local::Cast(obj); + return arr->Length(); +} + +CefString CefV8ValueImpl::GetFunctionName() { + CefString rv; + CEF_REQUIRE_UI_THREAD(rv); + CEF_V8_REQUIRE_FUNCTION_RETURN(rv); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + v8::Local func = v8::Local::Cast(obj); + GetCefString(v8::Handle::Cast(func->GetName()), rv); + return rv; +} + +CefRefPtr CefV8ValueImpl::GetFunctionHandler() { + CEF_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_FUNCTION_RETURN(NULL); + + v8::HandleScope handle_scope; + v8::Local obj = GetHandle()->ToObject(); + + V8TrackObject* tracker = V8TrackObject::Unwrap(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_REQUIRE_UI_THREAD(NULL); + CEF_V8_REQUIRE_FUNCTION_RETURN(NULL); + + v8::HandleScope handle_scope; + + v8::Local context_local; + if (context.get()) { + CefV8ContextImpl* context_impl = + static_cast(context.get()); + context_local = context_impl->GetContext(); + } else { + context_local = v8::Context::GetCurrent(); + } + + v8::Context::Scope context_scope(context_local); + + v8::Local obj = GetHandle()->ToObject(); + v8::Local func = v8::Local::Cast(obj); + v8::Handle recv; + + // Default to the global object if no object or a non-object was provided. + if (object.get() && object->IsObject()) { + CefV8ValueImpl* recv_impl = static_cast(object.get()); + recv = v8::Handle::Cast(recv_impl->GetHandle()); + } else { + recv = context_local->Global(); + } + + int argc = arguments.size(); + 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())->GetHandle(); + } + + CefRefPtr retval; + + { + v8::TryCatch try_catch; + try_catch.SetVerbose(true); + v8::Local func_rv; + + // Execute the function call using the V8Proxy so that inspector + // instrumentation works. + WebCore::V8Proxy* proxy = WebCore::V8Proxy::retrieve(); + DCHECK(proxy); + if (proxy) + func_rv = proxy->callFunction(func, recv, argc, argv); + + if (!HasCaught(try_catch) && !func_rv.IsEmpty()) + retval = new CefV8ValueImpl(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_REQUIRE_VALID_CONTEXT(NULL); + CEF_REQUIRE_UI_THREAD(NULL); + + v8::Handle stackTrace = + v8::StackTrace::CurrentStackTrace( + frame_limit, v8::StackTrace::kDetailed); + if (stackTrace.IsEmpty()) + return NULL; + return new CefV8StackTraceImpl(stackTrace); +} + + +// CefV8StackTraceImpl + +CefV8StackTraceImpl::CefV8StackTraceImpl(v8::Handle handle) + : handle_(new Handle(handle)) { +} + +CefV8StackTraceImpl::~CefV8StackTraceImpl() { +} + +int CefV8StackTraceImpl::GetFrameCount() { + CEF_REQUIRE_UI_THREAD(0); + v8::HandleScope handle_scope; + return GetHandle()->GetFrameCount(); +} + +CefRefPtr CefV8StackTraceImpl::GetFrame(int index) { + CEF_REQUIRE_UI_THREAD(NULL); + v8::HandleScope handle_scope; + v8::Handle stackFrame = GetHandle()->GetFrame(index); + if (stackFrame.IsEmpty()) + return NULL; + return new CefV8StackFrameImpl(stackFrame); +} + + +// CefV8StackFrameImpl + +CefV8StackFrameImpl::CefV8StackFrameImpl(v8::Handle handle) + : handle_(new Handle(handle)) { +} + +CefV8StackFrameImpl::~CefV8StackFrameImpl() { +} + +CefString CefV8StackFrameImpl::GetScriptName() { + CefString rv; + CEF_REQUIRE_UI_THREAD(rv); + v8::HandleScope handle_scope; + GetCefString(v8::Handle::Cast(GetHandle()->GetScriptName()), rv); + return rv; +} + +CefString CefV8StackFrameImpl::GetScriptNameOrSourceURL() { + CefString rv; + CEF_REQUIRE_UI_THREAD(rv); + v8::HandleScope handle_scope; + GetCefString( + v8::Handle::Cast(GetHandle()->GetScriptNameOrSourceURL()), + rv); + return rv; +} + +CefString CefV8StackFrameImpl::GetFunctionName() { + CefString rv; + CEF_REQUIRE_UI_THREAD(rv); + v8::HandleScope handle_scope; + GetCefString( + v8::Handle::Cast(GetHandle()->GetFunctionName()), rv); + return rv; +} + +int CefV8StackFrameImpl::GetLineNumber() { + CEF_REQUIRE_UI_THREAD(0); + v8::HandleScope handle_scope; + return GetHandle()->GetLineNumber(); +} + +int CefV8StackFrameImpl::GetColumn() { + CEF_REQUIRE_UI_THREAD(0); + v8::HandleScope handle_scope; + return GetHandle()->GetColumn(); +} + +bool CefV8StackFrameImpl::IsEval() { + CEF_REQUIRE_UI_THREAD(false); + v8::HandleScope handle_scope; + return GetHandle()->IsEval(); +} + +bool CefV8StackFrameImpl::IsConstructor() { + CEF_REQUIRE_UI_THREAD(false); + v8::HandleScope handle_scope; + return GetHandle()->IsConstructor(); +} diff --git a/cef1/libcef/v8_impl.h b/cef1/libcef/v8_impl.h new file mode 100644 index 000000000..11dfc7d25 --- /dev/null +++ b/cef1/libcef/v8_impl.h @@ -0,0 +1,223 @@ +// 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_V8_IMPL_H_ +#define CEF_LIBCEF_V8_IMPL_H_ +#pragma once + +#include + +#include "include/cef_v8.h" +#include "v8/include/v8.h" +#include "libcef/cef_thread.h" +#include "base/memory/ref_counted.h" + +class CefTrackNode; + +namespace WebKit { +class WebFrame; +}; + +// Template for V8 Handle types. This class is used to ensure that V8 objects +// are only released on the UI thread. +template +class CefV8Handle : + public base::RefCountedThreadSafe, + CefThread::DeleteOnUIThread> { + public: + typedef v8::Handle handleType; + typedef v8::Persistent persistentType; + + CefV8Handle(handleType v) + : handle_(persistentType::New(v)) { + } + ~CefV8Handle() { + handle_.Dispose(); + handle_.Clear(); + } + + handleType GetHandle() { return handle_; } + + protected: + 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: + explicit CefV8ContextImpl(v8::Handle context); + virtual ~CefV8ContextImpl(); + + 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; + + v8::Local GetContext(); + WebKit::WebFrame* GetWebFrame(); + + v8::Handle GetHandle() { return handle_->GetHandle(); } + + 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: + CefV8ValueImpl(v8::Handle value, CefTrackNode* tracker = NULL); + virtual ~CefV8ValueImpl(); + + 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 value) 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; + + v8::Handle GetHandle() { return handle_->GetHandle(); } + + protected: + // Test for and record any exception. + bool HasCaught(v8::TryCatch& try_catch); + + class Handle : + public base::RefCountedThreadSafe { + public: + typedef v8::Handle handleType; + typedef v8::Persistent persistentType; + + Handle(handleType v, CefTrackNode* tracker) + : handle_(persistentType::New(v)), + tracker_(tracker) { + } + ~Handle(); + + handleType GetHandle() { return handle_; } + + private: + 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_; + + DISALLOW_COPY_AND_ASSIGN(Handle); + }; + scoped_refptr handle_; + + CefRefPtr last_exception_; + bool rethrow_exceptions_; + + IMPLEMENT_REFCOUNTING(CefV8ValueImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8ValueImpl); +}; + +class CefV8StackTraceImpl : public CefV8StackTrace { + public: + explicit CefV8StackTraceImpl(v8::Handle handle); + virtual ~CefV8StackTraceImpl(); + + virtual int GetFrameCount() OVERRIDE; + virtual CefRefPtr GetFrame(int index) OVERRIDE; + + v8::Handle GetHandle() { return handle_->GetHandle(); } + + protected: + typedef CefV8Handle Handle; + scoped_refptr handle_; + + IMPLEMENT_REFCOUNTING(CefV8StackTraceImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8StackTraceImpl); +}; + +class CefV8StackFrameImpl : public CefV8StackFrame { + public: + explicit CefV8StackFrameImpl(v8::Handle handle); + virtual ~CefV8StackFrameImpl(); + + 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; + + v8::Handle GetHandle() { return handle_->GetHandle(); } + + protected: + typedef CefV8Handle Handle; + scoped_refptr handle_; + + IMPLEMENT_REFCOUNTING(CefV8StackFrameImpl); + DISALLOW_COPY_AND_ASSIGN(CefV8StackFrameImpl); +}; + +#endif // CEF_LIBCEF_V8_IMPL_H_ diff --git a/cef1/libcef/web_drag_source_gtk.cc b/cef1/libcef/web_drag_source_gtk.cc new file mode 100644 index 000000000..cc4d92589 --- /dev/null +++ b/cef1/libcef/web_drag_source_gtk.cc @@ -0,0 +1,162 @@ +// 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/web_drag_source_gtk.h" + +#include +#include + +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/drag_data_impl.h" +#include "libcef/web_drop_target_gtk.h" + +#include "base/utf_string_conversions.h" +#include "googleurl/src/gurl.h" +#include "net/base/net_util.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebImage.h" +#include "ui/base/dragdrop/os_exchange_data.h" +#include "ui/base/dragdrop/os_exchange_data_provider_gtk.h" +#include "ui/base/dragdrop/drag_drop_types.h" +#include "ui/base/dragdrop/gtk_dnd_util.h" +#include "ui/gfx/gtk_util.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/window_open_disposition.h" + + +using WebKit::WebDragOperation; +using WebKit::WebDragOperationNone; +using WebKit::WebDragOperationCopy; +using WebKit::WebDragOperationLink; +using WebKit::WebDragOperationMove; +using WebKit::WebDragOperationGeneric; +using WebKit::WebPoint; +using WebKit::WebView; +using WebKit::WebDragOperationsMask; +using ui::DragDropTypes; + +namespace { + +void drag_end(GtkWidget* widget, GdkDragContext* context, + WebDragSource* user_data) { + user_data->OnDragEnd(widget, context); +} + +bool drag_failed(GtkWidget* widget, GdkDragContext* context, + GtkDragResult result, WebDragSource* user_data) { + return user_data->OnDragFailed(widget, context, result); +} + +void drag_data_get(GtkWidget* widget, GdkDragContext* context, + GtkSelectionData* selection_data, guint target_type, + guint time, WebDragSource* user_data) { + user_data->OnDragDataGet(widget, context, selection_data, target_type, time); +} + +} // namespace + +WebDragSource::WebDragSource(CefBrowserImpl* browser) + : browser_(browser) { + widget_ = gtk_invisible_new(); + // At some point we might want to listen to drag-begin + g_signal_connect(widget_, "drag-end", G_CALLBACK(&drag_end), this); + g_signal_connect(widget_, "drag-failed", G_CALLBACK(&drag_failed), this); + g_signal_connect(widget_, "drag-data-get", G_CALLBACK(&drag_data_get), this); +} + +WebDragSource::~WebDragSource() { + gtk_widget_destroy(widget_); +} + +void WebDragSource::StartDragging(const WebDropData& drop_data, + WebDragOperationsMask mask, + const WebKit::WebImage& image, + const WebKit::WebPoint& image_offset) { + drop_data_.reset(new WebDropData(drop_data)); + int targets_mask = 0; + if (!drop_data.text.is_null() && !drop_data.text.string().empty()) + targets_mask |= ui::TEXT_PLAIN; + if (drop_data.url.is_valid()) { + targets_mask |= ui::TEXT_URI_LIST; + targets_mask |= ui::CHROME_NAMED_URL; + targets_mask |= ui::NETSCAPE_URL; + } + if (!drop_data.html.is_null() && !drop_data.html.string().empty()) + targets_mask |= ui::TEXT_HTML; + GtkTargetList* tl = ui::GetTargetListFromCodeMask(targets_mask); + + GdkEvent* event = gtk_get_current_event(); + GdkDragContext* context = gtk_drag_begin(widget_, tl, + (GdkDragAction)DragDropTypes::DragOperationToGdkDragAction(mask), 1, + event); + if (!image.isNull()) { + const SkBitmap& bitmap = image.getSkBitmap(); + GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(bitmap); + gtk_drag_set_icon_pixbuf(context, pixbuf, image_offset.x, image_offset.y); + g_object_unref(pixbuf); + } else { + gtk_drag_set_icon_default(context); + } + gdk_event_free(event); +} + +void WebDragSource::OnDragEnd(GtkWidget* widget, GdkDragContext* context) { + gfx::Point client(0, 0); + gfx::Point screen(0, 0); + getView()->dragSourceEndedAt(client, screen, WebDragOperationNone); + getView()->dragSourceSystemDragEnded(); +} + +bool WebDragSource::OnDragFailed(GtkWidget* widget, GdkDragContext* context, + GtkDragResult result) { + gfx::Point client(0, 0); + gfx::Point screen(0, 0); + getView()->dragSourceEndedAt(client, screen, WebDragOperationNone); + return FALSE; +} + +void WebDragSource::OnDragDataGet(GtkWidget* sender, GdkDragContext* context, + GtkSelectionData* selection_data, + guint target_type, guint time) { + switch (target_type) { + case ui::TEXT_PLAIN: { + std::string utf8_text = drop_data_->text.is_null() ? + std::string() : UTF16ToUTF8(drop_data_->text.string()); + gtk_selection_data_set_text(selection_data, utf8_text.c_str(), + utf8_text.length()); + break; + } + + case ui::TEXT_HTML: { + std::string utf8_text = drop_data_->html.is_null() ? + std::string() : UTF16ToUTF8(drop_data_->html.string()); + gtk_selection_data_set(selection_data, + ui::GetAtomForTarget(ui::TEXT_HTML), + 8, + reinterpret_cast(utf8_text.c_str()), + utf8_text.length()); + break; + } + + case ui::TEXT_URI_LIST: + case ui::CHROME_NAMED_URL: + case ui::NETSCAPE_URL: { + ui::WriteURLWithName(selection_data, drop_data_->url, + drop_data_->url_title, target_type); + break; + } + + default: + NOTREACHED(); + } +} + +WebKit::WebView* WebDragSource::getView() { + return browser_->UIT_GetWebView(); +} + diff --git a/cef1/libcef/web_drag_source_gtk.h b/cef1/libcef/web_drag_source_gtk.h new file mode 100644 index 000000000..076747b65 --- /dev/null +++ b/cef1/libcef/web_drag_source_gtk.h @@ -0,0 +1,47 @@ +// Copyright (c) 2012 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. + +#ifndef CEF_LIBCEF_WEB_DRAG_SOURCE_GTK_H_ +#define CEF_LIBCEF_WEB_DRAG_SOURCE_GTK_H_ + +#include +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" + +class CefBrowserImpl; +class WebDropData; + +namespace WebKit { +class WebImage; +class WebPoint; +class WebView; +} + +class WebDragSource : public base::RefCounted { + public: + explicit WebDragSource(CefBrowserImpl* browser); + virtual ~WebDragSource(); + + void StartDragging(const WebDropData& drop_data, + WebKit::WebDragOperationsMask mask, + const WebKit::WebImage& image, + const WebKit::WebPoint& image_offset); + + void OnDragEnd(GtkWidget* widget, GdkDragContext* context); + bool OnDragFailed(GtkWidget* widget, GdkDragContext* context, + GtkDragResult result); + void OnDragDataGet(GtkWidget* sender, GdkDragContext* context, + GtkSelectionData* selection_data, guint target_type, + guint time); + + private: + WebKit::WebView* getView(); + scoped_ptr drop_data_; + CefBrowserImpl* browser_; + GtkWidget* widget_; +}; + +#endif // CEF_LIBCEF_WEB_DRAG_SOURCE_GTK_H_ diff --git a/cef1/libcef/web_drag_source_mac.h b/cef1/libcef/web_drag_source_mac.h new file mode 100644 index 000000000..80809ba1b --- /dev/null +++ b/cef1/libcef/web_drag_source_mac.h @@ -0,0 +1,91 @@ +// 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. + +#ifndef CEF_LIBCEF_WEB_DRAG_SOURCE_MAC_H_ +#define CEF_LIBCEF_WEB_DRAG_SOURCE_MAC_H_ +#pragma once + +#import + +#include "base/file_path.h" +#include "base/memory/scoped_nsobject.h" +#include "base/memory/scoped_ptr.h" +#include "googleurl/src/gurl.h" +#include "ui/gfx/native_widget_types.h" + +struct WebDropData; +@class BrowserWebView; + +// A class that handles tracking and event processing for a drag and drop +// originating from the content area. +@interface WebDragSource : NSObject { + @private + // Our web view. Weak reference (owns or co-owns us). + BrowserWebView* view_; + + // Our drop data. Should only be initialized once. + scoped_ptr dropData_; + + // The image to show as drag image. Can be nil. + scoped_nsobject dragImage_; + + // The offset to draw |dragImage_| at. + NSPoint imageOffset_; + + // Our pasteboard. + scoped_nsobject pasteboard_; + + // A mask of the allowed drag operations. + NSDragOperation dragOperationMask_; + + // The file name to be saved to for a drag-out download. + FilePath downloadFileName_; + + // The URL to download from for a drag-out download. + GURL downloadURL_; + + // The file extension associated with the file drag, if any. + NSString* fileExtension_; +} + +// Initialize a WebDragSource object for a drag (originating on the given +// BrowserWebView and with the given dropData and pboard). Fill the pasteboard +// with data types appropriate for dropData. +- (id)initWithWebView:(BrowserWebView*)view + dropData:(const WebDropData*)dropData + image:(NSImage*)image + offset:(NSPoint)offset + pasteboard:(NSPasteboard*)pboard + dragOperationMask:(NSDragOperation)dragOperationMask; + +// Returns a mask of the allowed drag operations. +- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal; + +// Call when asked to do a lazy write to the pasteboard; hook up to +// -pasteboard:provideDataForType: (on the BrowserWebView). +- (void)lazyWriteToPasteboard:(NSPasteboard*)pboard + forType:(NSString*)type; + +// Start the drag (on the originally provided BrowserWebView); can do this right +// after -initWithContentsView:.... +- (void)startDrag; + +// End the drag and clear the pasteboard; hook up to +// -draggedImage:endedAt:operation:. +- (void)endDragAt:(NSPoint)screenPoint + operation:(NSDragOperation)operation; + +// Drag moved; hook up to -draggedImage:movedTo:. +- (void)moveDragTo:(NSPoint)screenPoint; + +// Call to drag a promised file to the given path (should be called before +// -endDragAt:...); hook up to -namesOfPromisedFilesDroppedAtDestination:. +// Returns the file name (not including path) of the file deposited (or which +// will be deposited). +- (NSString*)dragPromisedFileTo:(NSString*)path; + +@end + +#endif // CEF_LIBCEF_WEB_DRAG_SOURCE_MAC_H_ diff --git a/cef1/libcef/web_drag_source_mac.mm b/cef1/libcef/web_drag_source_mac.mm new file mode 100644 index 000000000..d6bae9130 --- /dev/null +++ b/cef1/libcef/web_drag_source_mac.mm @@ -0,0 +1,435 @@ +// 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. + +#include + +#include "libcef/browser_impl.h" +#import "libcef/browser_webview_mac.h" +#include "libcef/cef_context.h" +#include "libcef/drag_download_util.h" +#include "libcef/download_util.h" +#import "libcef/web_drag_source_mac.h" + +#include "base/file_path.h" +#include "base/string_util.h" +#include "base/sys_string_conversions.h" +#include "base/threading/thread.h" +#include "base/threading/thread_restrictions.h" +#include "base/utf_string_conversions.h" +#include "net/base/file_stream.h" +#include "net/base/net_util.h" +#import "third_party/mozilla/NSPasteboard+Utils.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/gfx/mac/nsimage_cache.h" +#include "webkit/glue/webdropdata.h" + +using base::SysNSStringToUTF8; +using base::SysUTF8ToNSString; +using base::SysUTF16ToNSString; +using net::FileStream; +using WebKit::WebDragOperationNone; +using WebKit::WebView; + +namespace { + +// An unofficial standard pasteboard title type to be provided alongside the +// |NSURLPboardType|. +NSString* const kNSURLTitlePboardType = @"public.url-name"; + +// Converts a string16 into a FilePath. Use this method instead of +// -[NSString fileSystemRepresentation] to prevent exceptions from being thrown. +// See http://crbug.com/78782 for more info. +FilePath FilePathFromFilename(const string16& filename) { + NSString* str = SysUTF16ToNSString(filename); + char buf[MAXPATHLEN]; + if (![str getFileSystemRepresentation:buf maxLength:sizeof(buf)]) + return FilePath(); + return FilePath(buf); +} + +// Returns a filename appropriate for the drop data +// TODO(viettrungluu): Refactor to make it common across platforms, +// and move it somewhere sensible. +FilePath GetFileNameFromDragData(const WebDropData& drop_data) { + FilePath file_name(FilePathFromFilename(drop_data.file_description_filename)); + std::string extension = file_name.Extension(); + file_name = file_name.BaseName().RemoveExtension(); + + // 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.empty()) { + // Retrieve the name from the URL. + string16 suggested_filename = + net::GetSuggestedFilename(drop_data.url, "", "", "", "", ""); + file_name = FilePathFromFilename(suggested_filename); + } + + return file_name.ReplaceExtension(extension); +} + +// This helper's sole task is to write out data for a promised file; the caller +// is responsible for opening the file. It takes the drop data and an open file +// stream. +void PromiseWriterHelper(const WebDropData& drop_data, + net::FileStream* file_stream) { + DCHECK(file_stream); + file_stream->WriteSync(drop_data.file_contents.data(), + drop_data.file_contents.length()); + + file_stream->CloseSync(); +} + +} // namespace + + +@interface WebDragSource(Private) + +- (void)fillPasteboard; +- (NSImage*)dragImage; + +@end // @interface WebDragSource(Private) + + +@implementation WebDragSource + +- (id)initWithWebView:(BrowserWebView*)view + dropData:(const WebDropData*)dropData + image:(NSImage*)image + offset:(NSPoint)offset + pasteboard:(NSPasteboard*)pboard + dragOperationMask:(NSDragOperation)dragOperationMask { + if ((self = [super init])) { + view_ = view; + DCHECK(view_); + + dropData_.reset(new WebDropData(*dropData)); + DCHECK(dropData_.get()); + + if (image == nil) { + // No drag image was provided so create one. + FilePath path = _Context->GetResourcesFilePath(); + path = path.AppendASCII("urlIcon.png"); + image = [[NSImage alloc] + initWithContentsOfFile:SysUTF8ToNSString(path.value())]; + } + + dragImage_.reset([image retain]); + imageOffset_ = offset; + + pasteboard_.reset([pboard retain]); + DCHECK(pasteboard_.get()); + + dragOperationMask_ = dragOperationMask; + + fileExtension_ = nil; + + [self fillPasteboard]; + } + + return self; +} + +- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal { + return dragOperationMask_; +} + +- (void)lazyWriteToPasteboard:(NSPasteboard*)pboard forType:(NSString*)type { + // NSHTMLPboardType requires the character set to be declared. Otherwise, it + // assumes US-ASCII. Awesome. + static const string16 kHtmlHeader = + ASCIIToUTF16(""); + + // Be extra paranoid; avoid crashing. + if (!dropData_.get()) { + NOTREACHED() << "No drag-and-drop data available for lazy write."; + return; + } + + // HTML. + if ([type isEqualToString:NSHTMLPboardType]) { + DCHECK(!dropData_->html.is_null() && !dropData_->html.string().empty()); + // See comment on |kHtmlHeader| above. + [pboard setString:SysUTF16ToNSString(kHtmlHeader + dropData_->html.string()) + forType:NSHTMLPboardType]; + + // URL. + } else if ([type isEqualToString:NSURLPboardType]) { + DCHECK(dropData_->url.is_valid()); + NSString* urlStr = SysUTF8ToNSString(dropData_->url.spec()); + NSURL* url = [NSURL URLWithString:urlStr]; + // If NSURL creation failed, check for a badly-escaped javascript URL. + if (!url && urlStr && dropData_->url.SchemeIs("javascript")) { + NSString *escapedStr = + [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + url = [NSURL URLWithString:escapedStr]; + } + [url writeToPasteboard:pboard]; + // URL title. + } else if ([type isEqualToString:kNSURLTitlePboardType]) { + [pboard setString:SysUTF16ToNSString(dropData_->url_title) + forType:kNSURLTitlePboardType]; + + // File contents. + } else if ([type isEqualToString:NSFileContentsPboardType] || + (fileExtension_ && + [type isEqualToString:NSCreateFileContentsPboardType(fileExtension_)])) { + // TODO(viettrungluu: find something which is known to accept + // NSFileContentsPboardType to check that this actually works! + scoped_nsobject file_wrapper( + [[NSFileWrapper alloc] initRegularFileWithContents:[NSData + dataWithBytes:dropData_->file_contents.data() + length:dropData_->file_contents.length()]]); + [file_wrapper setPreferredFilename:SysUTF8ToNSString( + GetFileNameFromDragData(*dropData_).value())]; + [pboard writeFileWrapper:file_wrapper]; + + // TIFF. + } else if ([type isEqualToString:NSTIFFPboardType]) { + // TODO(viettrungluu): This is a bit odd since we rely on Cocoa to render + // our image into a TIFF. This is also suboptimal since this is all done + // synchronously. I'm not sure there's much we can easily do about it. + scoped_nsobject image( + [[NSImage alloc] initWithData:[NSData + dataWithBytes:dropData_->file_contents.data() + length:dropData_->file_contents.length()]]); + [pboard setData:[image TIFFRepresentation] forType:NSTIFFPboardType]; + + // Plain text. + } else if ([type isEqualToString:NSStringPboardType]) { + DCHECK(!dropData_->text.is_null() && !dropData_->text.string().empty()); + [pboard setString:SysUTF16ToNSString(dropData_->text.string()) + forType:NSStringPboardType]; + + // Oops! + } else { + NOTREACHED() << "Asked for a drag pasteboard type we didn't offer."; + } +} + +- (NSPoint)convertScreenPoint:(NSPoint)screenPoint { + NSPoint basePoint = [[view_ window] convertScreenToBase:screenPoint]; + return [view_ convertPoint:basePoint fromView:nil]; +} + +- (void)startDrag { + NSEvent* currentEvent = [NSApp currentEvent]; + + // Synthesize an event for dragging, since we can't be sure that + // [NSApp currentEvent] will return a valid dragging event. + NSWindow* window = [view_ window]; + NSPoint position = [window mouseLocationOutsideOfEventStream]; + NSTimeInterval eventTime = [currentEvent timestamp]; + NSEvent* dragEvent = [NSEvent mouseEventWithType:NSLeftMouseDragged + location:position + modifierFlags:NSLeftMouseDraggedMask + timestamp:eventTime + windowNumber:[window windowNumber] + context:nil + eventNumber:0 + clickCount:1 + pressure:1.0]; + + if (dragImage_) { + position.x -= imageOffset_.x; + // Deal with Cocoa's flipped coordinate system. + position.y -= [dragImage_.get() size].height - imageOffset_.y; + } + // Per kwebster, offset arg is ignored, see -_web_DragImageForElement: in + // third_party/WebKit/Source/WebKit/mac/Misc/WebNSViewExtras.m. + [window dragImage:[self dragImage] + at:position + offset:NSZeroSize + event:dragEvent + pasteboard:pasteboard_ + source:view_ + slideBack:YES]; +} + +- (void)endDragAt:(NSPoint)screenPoint + operation:(NSDragOperation)operation { + // Convert |screenPoint| to view coordinates and flip it. + NSWindow* window = [view_ window]; + NSPoint localPoint = [self convertScreenPoint:screenPoint]; + NSRect viewFrame = [window frame]; + localPoint.y = viewFrame.size.height - localPoint.y; + // Flip |screenPoint|. + NSRect screenFrame = [[window screen] frame]; + screenPoint.y = screenFrame.size.height - screenPoint.y; + + // If AppKit returns a copy and move operation, mask off the move bit + // because WebCore does not understand what it means to do both, which + // results in an assertion failure/renderer crash. + if (operation == (NSDragOperationMove | NSDragOperationCopy)) + operation &= ~NSDragOperationMove; + + WebView* webview = view_.browser->UIT_GetWebView(); + + gfx::Point client(localPoint.x, localPoint.y); + gfx::Point screen(screenPoint.x, screenPoint.y); + webview->dragSourceEndedAt(client, screen, + static_cast(operation)); + + // Make sure the pasteboard owner isn't us. + [pasteboard_ declareTypes:[NSArray array] owner:nil]; + + webview->dragSourceSystemDragEnded(); +} + +- (void)moveDragTo:(NSPoint)screenPoint { + // Convert |screenPoint| to view coordinates and flip it. + NSWindow* window = [view_ window]; + NSPoint localPoint = [self convertScreenPoint:screenPoint]; + NSRect viewFrame = [window frame]; + localPoint.y = viewFrame.size.height - localPoint.y; + // Flip |screenPoint|. + NSRect screenFrame = [[window screen] frame]; + screenPoint.y = screenFrame.size.height - screenPoint.y; + + WebView* webview = view_.browser->UIT_GetWebView(); + + gfx::Point client(localPoint.x, localPoint.y); + gfx::Point screen(screenPoint.x, screenPoint.y); + webview->dragSourceMovedTo(client, screen, WebDragOperationNone); +} + +- (NSString*)dragPromisedFileTo:(NSString*)path { + // Be extra paranoid; avoid crashing. + if (!dropData_.get()) { + NOTREACHED() << "No drag-and-drop data available for promised file."; + return nil; + } + + FilePath fileName = downloadFileName_.empty() ? + GetFileNameFromDragData(*dropData_) : downloadFileName_; + FilePath filePath(SysNSStringToUTF8(path)); + filePath = filePath.Append(fileName); + + // CreateFileStreamForDrop() will call file_util::PathExists(), + // which is blocking. Since this operation is already blocking the + // UI thread on OSX, it should be reasonable to let it happen. + base::ThreadRestrictions::ScopedAllowIO allowIO; + FileStream* fileStream = + drag_download_util::CreateFileStreamForDrop(&filePath); + if (!fileStream) + return nil; + + if (downloadURL_.is_valid()) { + WebView* webview = view_.browser->UIT_GetWebView(); + const GURL& page_url = webview->mainFrame()->document().url(); + const std::string& page_encoding = + webview->mainFrame()->document().encoding().utf8(); + + scoped_refptr dragFileDownloader(new DragDownloadFile( + filePath, + linked_ptr(fileStream), + downloadURL_, + page_url, + page_encoding, + view_.browser->UIT_GetWebViewDelegate())); + + // The finalizer will take care of closing and deletion. + dragFileDownloader->Start( + new drag_download_util::PromiseFileFinalizer(dragFileDownloader)); + } else { + // The writer will take care of closing and deletion. + CefThread::PostTask(CefThread::FILE, FROM_HERE, + base::Bind(PromiseWriterHelper, *dropData_, base::Owned(fileStream))); + } + + // Once we've created the file, we should return the file name. + return SysUTF8ToNSString(filePath.BaseName().value()); + + return nil; +} + +@end // @implementation WebDragSource + + +@implementation WebDragSource (Private) + +- (void)fillPasteboard { + DCHECK(pasteboard_.get()); + + [pasteboard_ declareTypes:[NSArray array] owner:view_]; + + // HTML. + if (!dropData_->html.is_null() && !dropData_->html.string().empty()) + [pasteboard_ addTypes:[NSArray arrayWithObject:NSHTMLPboardType] + owner:view_]; + + // URL (and title). + if (dropData_->url.is_valid()) + [pasteboard_ addTypes:[NSArray arrayWithObjects:NSURLPboardType, + kNSURLTitlePboardType, nil] + owner:view_]; + + std::string fileExtension; + + // File. + if (!dropData_->file_contents.empty() || + !dropData_->download_metadata.empty()) { + if (dropData_->download_metadata.empty()) { + fileExtension = GetFileNameFromDragData(*dropData_).Extension(); + } else { + string16 mimeType; + FilePath fileName; + if (drag_download_util::ParseDownloadMetadata( + dropData_->download_metadata, + &mimeType, + &fileName, + &downloadURL_)) { + download_util::GenerateFileName( + downloadURL_, + std::string(), + std::string(), + UTF16ToUTF8(mimeType), + fileName.value(), + &downloadFileName_); + fileExtension = downloadFileName_.Extension(); + } + } + + if (!fileExtension.empty()) { + // Strip the leading dot. + fileExtension_ = SysUTF8ToNSString(fileExtension.substr(1)); + // File contents (with and without specific type), and file (HFS) promise. + // TODO(viettrungluu): others? + NSArray* types = [NSArray arrayWithObjects: + NSFileContentsPboardType, + NSCreateFileContentsPboardType(fileExtension_), + NSFilesPromisePboardType, + nil]; + [pasteboard_ addTypes:types owner:view_]; + + if (!dropData_->file_contents.empty()) { + [pasteboard_ addTypes:[NSArray arrayWithObject:NSTIFFPboardType] + owner:view_]; + } + + // For the file promise, we need to specify the extension. + [pasteboard_ setPropertyList:[NSArray arrayWithObject:fileExtension_] + forType:NSFilesPromisePboardType]; + } + } + + // Plain text. + if (!dropData_->text.is_null() && !dropData_->text.string().empty()) + [pasteboard_ addTypes:[NSArray arrayWithObject:NSStringPboardType] + owner:view_]; +} + +- (NSImage*)dragImage { + if (dragImage_) + return dragImage_; + + // Default to returning a generic image. + return gfx::GetCachedImageWithName(@"nav.pdf"); +} + +@end // @implementation WebDragSource (Private) diff --git a/cef1/libcef/web_drag_source_win.cc b/cef1/libcef/web_drag_source_win.cc new file mode 100644 index 000000000..af307c978 --- /dev/null +++ b/cef1/libcef/web_drag_source_win.cc @@ -0,0 +1,100 @@ +// Copyright (c) 2011 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. + +#include "libcef/web_drag_source_win.h" +#include "libcef/web_drag_utils_win.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" + +using WebKit::WebDragOperationNone; +using WebKit::WebPoint; +using WebKit::WebView; + +namespace { + +static void GetCursorPositions(gfx::NativeWindow wnd, gfx::Point* client, + gfx::Point* screen) { + POINT cursor_pos; + GetCursorPos(&cursor_pos); + screen->SetPoint(cursor_pos.x, cursor_pos.y); + ScreenToClient(wnd, &cursor_pos); + client->SetPoint(cursor_pos.x, cursor_pos.y); +} + +} // namespace + +/////////////////////////////////////////////////////////////////////////////// +// WebDragSource, public: + +WebDragSource::WebDragSource(gfx::NativeWindow source_wnd, WebView* view) + : ui::DragSource(), + source_wnd_(source_wnd), + view_(view), + effect_(DROPEFFECT_NONE) { +} + +WebDragSource::~WebDragSource() { +} + +void WebDragSource::OnDragSourceCancel() { + // Delegate to the UI thread if we do drag-and-drop in the background thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&WebDragSource::OnDragSourceCancel, this)); + return; + } + + if (!view_) + return; + + gfx::Point client; + gfx::Point screen; + GetCursorPositions(source_wnd_, &client, &screen); + view_->dragSourceEndedAt(client, screen, WebDragOperationNone); +} + +void WebDragSource::OnDragSourceDrop() { + // On Windows, we check for drag end in IDropSource::QueryContinueDrag which + // happens before IDropTarget::Drop is called. HTML5 requires the "dragend" + // event to happen after the "drop" event. Since Windows calls these two + // directly after each other we can just post a task to handle the + // OnDragSourceDrop after the current task. + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&WebDragSource::DelayedOnDragSourceDrop, this)); +} + +void WebDragSource::DelayedOnDragSourceDrop() { + if (!view_) + return; + + gfx::Point client; + gfx::Point screen; + GetCursorPositions(source_wnd_, &client, &screen); + view_->dragSourceEndedAt(client, screen, + web_drag_utils_win::WinDragOpToWebDragOp(effect_)); +} + +void WebDragSource::OnDragSourceMove() { + // Delegate to the UI thread if we do drag-and-drop in the background thread. + if (!CefThread::CurrentlyOn(CefThread::UI)) { + CefThread::PostTask( + CefThread::UI, FROM_HERE, + base::Bind(&WebDragSource::OnDragSourceMove, this)); + return; + } + + if (!view_) + return; + + gfx::Point client; + gfx::Point screen; + GetCursorPositions(source_wnd_, &client, &screen); + view_->dragSourceMovedTo(client, screen, WebDragOperationNone); +} diff --git a/cef1/libcef/web_drag_source_win.h b/cef1/libcef/web_drag_source_win.h new file mode 100644 index 000000000..283735acb --- /dev/null +++ b/cef1/libcef/web_drag_source_win.h @@ -0,0 +1,58 @@ +// Copyright (c) 2011 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. + +#ifndef CEF_LIBCEF_WEB_DRAG_SOURCE_WIN_H_ +#define CEF_LIBCEF_WEB_DRAG_SOURCE_WIN_H_ +#pragma once + +#include "base/basictypes.h" +#include "ui/base/dragdrop/drag_source.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/point.h" + +namespace WebKit { +class WebView; +}; + +// An IDropSource implementation for a WebView. Handles notifications sent +// by an active drag-drop operation as the user mouses over other drop targets +// on their system. This object tells Windows whether or not the drag should +// continue, and supplies the appropriate cursors. +class WebDragSource : public ui::DragSource { + public: + // Create a new DragSource for a given HWND and WebView. + WebDragSource(gfx::NativeWindow source_wnd, WebKit::WebView* view); + virtual ~WebDragSource(); + + void set_effect(DWORD effect) { effect_ = effect; } + + protected: + // ui::DragSource + virtual void OnDragSourceCancel(); + virtual void OnDragSourceDrop(); + virtual void OnDragSourceMove(); + + private: + // Cannot construct thusly. + WebDragSource(); + + // OnDragSourceDrop schedules its main work to be done after IDropTarget::Drop + // by posting a task to this function. + void DelayedOnDragSourceDrop(); + + // Keep a reference to the window so we can translate the cursor position. + gfx::NativeWindow source_wnd_; + + // We use this as a channel to the web view to tell it about various drag + // drop events that it needs to know about (such as when a drag operation it + // initiated terminates). + WebKit::WebView* view_; + + DWORD effect_; + + DISALLOW_COPY_AND_ASSIGN(WebDragSource); +}; + +#endif // CEF_LIBCEF_WEB_DRAG_SOURCE_WIN_H_ diff --git a/cef1/libcef/web_drag_utils_mac.h b/cef1/libcef/web_drag_utils_mac.h new file mode 100644 index 000000000..3e9daaa80 --- /dev/null +++ b/cef1/libcef/web_drag_utils_mac.h @@ -0,0 +1,37 @@ +// 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_WEB_DRAG_UTILS_MAC_H_ +#define CEF_LIBCEF_WEB_DRAG_UTILS_MAC_H_ +#pragma once + +#import + +#include "base/basictypes.h" +#include "googleurl/src/gurl.h" + +namespace drag_util { + +// Populates the |url| and |title| with URL data in |pboard|. There may be more +// than one, but we only handle dropping the first. |url| must not be |NULL|; +// |title| is an optional parameter. Returns |YES| if URL data was obtained from +// the pasteboard, |NO| otherwise. If |convert_filenames| is |YES|, the function +// will also attempt to convert filenames in |pboard| to file URLs. +BOOL PopulateURLAndTitleFromPasteBoard(GURL* url, + string16* title, + NSPasteboard* pboard, + BOOL convert_filenames); + +// Returns the first file URL from |info|, if there is one. If |info| doesn't +// contain any file URLs, an empty |GURL| is returned. +GURL GetFileURLFromDropData(id info); + +// Determines whether the given drag and drop operation contains content that +// is supported by the web view. In particular, if the content is a local file +// URL, this checks if it is of a type that can be shown in the tab contents. +BOOL IsUnsupportedDropData(id info); + +} // namespace drag_util + +#endif // CEF_LIBCEF_WEB_DRAG_UTILS_MAC_H_ diff --git a/cef1/libcef/web_drag_utils_mac.mm b/cef1/libcef/web_drag_utils_mac.mm new file mode 100644 index 000000000..9570df418 --- /dev/null +++ b/cef1/libcef/web_drag_utils_mac.mm @@ -0,0 +1,109 @@ +// 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_webkit_glue.h" +#import "libcef/web_drag_utils_mac.h" + +#include "base/basictypes.h" +#include "base/logging.h" +#include "base/sys_string_conversions.h" +#include "googleurl/src/gurl.h" +#include "net/base/mime_util.h" +#include "net/base/net_util.h" +#import "third_party/mozilla/NSPasteboard+Utils.h" +#include "webkit/plugins/npapi/plugin_list.h" + +namespace drag_util { + +BOOL PopulateURLAndTitleFromPasteBoard(GURL* url, + string16* title, + NSPasteboard* pboard, + BOOL convert_filenames) { + CHECK(url); + + // Bail out early if there's no URL data. + if (![pboard containsURLData]) + return NO; + + // -getURLs:andTitles:convertingFilenames: will already validate URIs so we + // don't need to again. The arrays returned are both of NSStrings. + NSArray* url_array = nil; + NSArray* title_array = nil; + [pboard getURLs:&url_array andTitles:&title_array + convertingFilenames:convert_filenames]; + DCHECK_EQ([url_array count], [title_array count]); + // It's possible that no URLs were actually provided! + if (![url_array count]) + return NO; + NSString* url_string = [url_array objectAtIndex:0]; + if ([url_string length]) { + // Check again just to make sure to not assign NULL into a std::string, + // which throws an exception. + const char* utf8_url = [url_string UTF8String]; + if (utf8_url) { + *url = GURL(utf8_url); + // Extra paranoia check. + if (title && [title_array count]) + *title = base::SysNSStringToUTF16([title_array objectAtIndex:0]); + } + } + return YES; +} + +GURL GetFileURLFromDropData(id info) { + if ([[info draggingPasteboard] containsURLData]) { + GURL url; + PopulateURLAndTitleFromPasteBoard(&url, + NULL, + [info draggingPasteboard], + YES); + + if (url.SchemeIs("file")) + return url; + } + return GURL(); +} + +static BOOL IsSupportedFileURL(const GURL& url) { + FilePath full_path; + net::FileURLToFilePath(url, &full_path); + + std::string mime_type; + net::GetMimeTypeFromFile(full_path, &mime_type); + + // This logic mirrors |BufferedResourceHandler::ShouldDownload()|. + // TODO(asvitkine): Refactor this out to a common location instead of + // duplicating code. + if (net::IsSupportedMimeType(mime_type)) + return YES; + + // Check whether there is a plugin that supports the mime type. (e.g. PDF) + bool allow_wildcard = false; + std::vector plugins; + webkit::npapi::PluginList::Singleton()->GetPluginInfoArray( + GURL(), mime_type, allow_wildcard, NULL, &plugins, NULL); + + // If any associated plugins exist and are enabled don't allow the download. + if (!plugins.empty()) { + std::vector::const_iterator it = plugins.begin(); + for (; it != plugins.end(); ++it) { + if (webkit_glue::IsPluginEnabled(*it)) + return YES; + } + } + + return NO; +} + +BOOL IsUnsupportedDropData(id info) { + GURL url = GetFileURLFromDropData(info); + if (!url.is_empty()) { + // If dragging a file, only allow dropping supported file types (that the + // web view can display). + return !IsSupportedFileURL(url); + } + return NO; +} + +} // namespace drag_util diff --git a/cef1/libcef/web_drag_utils_win.cc b/cef1/libcef/web_drag_utils_win.cc new file mode 100644 index 000000000..2812b7ef0 --- /dev/null +++ b/cef1/libcef/web_drag_utils_win.cc @@ -0,0 +1,61 @@ +// 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 "libcef/web_drag_utils_win.h" + +#include +#include "base/logging.h" + +using WebKit::WebDragOperation; +using WebKit::WebDragOperationsMask; +using WebKit::WebDragOperationNone; +using WebKit::WebDragOperationCopy; +using WebKit::WebDragOperationLink; +using WebKit::WebDragOperationMove; +using WebKit::WebDragOperationGeneric; + +namespace web_drag_utils_win { + +WebDragOperation WinDragOpToWebDragOp(DWORD effect) { + DCHECK(effect == DROPEFFECT_NONE || effect == DROPEFFECT_COPY || + effect == DROPEFFECT_LINK || effect == DROPEFFECT_MOVE); + + return WinDragOpMaskToWebDragOpMask(effect); +} + +WebDragOperationsMask WinDragOpMaskToWebDragOpMask(DWORD effects) { + WebDragOperationsMask ops = WebDragOperationNone; + if (effects & DROPEFFECT_COPY) + ops = static_cast(ops | WebDragOperationCopy); + if (effects & DROPEFFECT_LINK) + ops = static_cast(ops | WebDragOperationLink); + if (effects & DROPEFFECT_MOVE) + ops = static_cast(ops | WebDragOperationMove | + WebDragOperationGeneric); + return ops; +} + +DWORD WebDragOpToWinDragOp(WebDragOperation op) { + DCHECK(op == WebDragOperationNone || + op == WebDragOperationCopy || + op == WebDragOperationLink || + op == WebDragOperationMove || + op == (WebDragOperationMove | WebDragOperationGeneric)); + + return WebDragOpMaskToWinDragOpMask(op); +} + +DWORD WebDragOpMaskToWinDragOpMask(WebDragOperationsMask ops) { + DWORD win_ops = DROPEFFECT_NONE; + if (ops & WebDragOperationCopy) + win_ops |= DROPEFFECT_COPY; + if (ops & WebDragOperationLink) + win_ops |= DROPEFFECT_LINK; + if (ops & (WebDragOperationMove | WebDragOperationGeneric)) + win_ops |= DROPEFFECT_MOVE; + return win_ops; +} + +} // namespace web_drag_utils_win + diff --git a/cef1/libcef/web_drag_utils_win.h b/cef1/libcef/web_drag_utils_win.h new file mode 100644 index 000000000..8fd3e307f --- /dev/null +++ b/cef1/libcef/web_drag_utils_win.h @@ -0,0 +1,22 @@ +// 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. + +#ifndef CEF_LIBCEF_WEB_DRAG_UTILS_WIN_H_ +#define CEF_LIBCEF_WEB_DRAG_UTILS_WIN_H_ +#pragma once + +#include +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" + +namespace web_drag_utils_win { + +WebKit::WebDragOperation WinDragOpToWebDragOp(DWORD effect); +WebKit::WebDragOperationsMask WinDragOpMaskToWebDragOpMask(DWORD effects); + +DWORD WebDragOpToWinDragOp(WebKit::WebDragOperation op); +DWORD WebDragOpMaskToWinDragOpMask(WebKit::WebDragOperationsMask ops); + +} // namespace web_drag_utils_win + +#endif // CEF_LIBCEF_WEB_DRAG_UTILS_WIN_H_ diff --git a/cef1/libcef/web_drop_target_gtk.cc b/cef1/libcef/web_drop_target_gtk.cc new file mode 100644 index 000000000..25c8fbf55 --- /dev/null +++ b/cef1/libcef/web_drop_target_gtk.cc @@ -0,0 +1,269 @@ +// 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/web_drop_target_gtk.h" + +#include +#include + +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/drag_data_impl.h" + +#include "base/utf_string_conversions.h" +#include "base/bind.h" +#include "googleurl/src/gurl.h" +#include "net/base/net_util.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/base/dragdrop/os_exchange_data.h" +#include "ui/base/dragdrop/os_exchange_data_provider_gtk.h" +#include "ui/base/dragdrop/drag_drop_types.h" +#include "ui/base/dragdrop/gtk_dnd_util.h" +#include "ui/base/gtk/gtk_screen_util.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/window_open_disposition.h" + +using WebKit::WebDragOperation; +using WebKit::WebDragOperationNone; +using WebKit::WebDragOperationCopy; +using WebKit::WebDragOperationLink; +using WebKit::WebDragOperationMove; +using WebKit::WebDragOperationGeneric; +using WebKit::WebDragOperationsMask; +using WebKit::WebPoint; +using WebKit::WebView; +using ui::DragDropTypes; + +namespace { + +/// GTK callbacks +gboolean drag_motion(GtkWidget* widget, GdkDragContext* context, gint x, + gint y, guint time, WebDropTarget* user_data) { + return user_data->OnDragMove(widget, context, x, y, time); +} + +void drag_leave(GtkWidget* widget, GdkDragContext* context, guint time, + WebDropTarget* user_data) { + user_data->OnDragLeave(widget, context, time); +} + +gboolean drag_drop(GtkWidget* widget, GdkDragContext* context, gint x, + gint y, guint time, WebDropTarget* user_data) { + return user_data->OnDragDrop(widget, context, x, y, time); +} + +void drag_data_received(GtkWidget* widget, GdkDragContext* context, + gint x, gint y, GtkSelectionData* data, guint info, + guint time, WebDropTarget* user_data) { + user_data->OnDragDataReceived(widget, context, x, y, data, info, time); +} + +int supported_targets[] = { + ui::TEXT_PLAIN, + ui::TEXT_URI_LIST, + ui::TEXT_HTML, + ui::NETSCAPE_URL, + ui::CHROME_NAMED_URL, + ui::TEXT_PLAIN_NO_CHARSET, +}; + +WebDragOperationsMask _mask(GdkDragContext* context) { + GdkDragAction propsed_action = context->suggested_action; + return (WebDragOperationsMask)DragDropTypes::GdkDragActionToDragOperation( + propsed_action); +} + +} // namespace + +WebDropTarget::WebDropTarget(CefBrowserImpl* browser) + : browser_(browser), + data_requests_(0), + context_(NULL), + method_factory_(this) { + GtkWidget* widget = browser->UIT_GetWebViewHost()->view_handle(); + gtk_drag_dest_set(widget, (GtkDestDefaults)0, NULL, 0, + static_cast(GDK_ACTION_COPY | GDK_ACTION_LINK | + GDK_ACTION_MOVE)); + g_signal_connect(widget, "drag-motion", G_CALLBACK(&drag_motion), this); + g_signal_connect(widget, "drag-leave", G_CALLBACK(&drag_leave), this); + g_signal_connect(widget, "drag-drop", G_CALLBACK(&drag_drop), this); + g_signal_connect(widget, "drag-data-received", + G_CALLBACK(&drag_data_received), this); +} + +WebDropTarget::~WebDropTarget() { +} + +WebKit::WebView* WebDropTarget::getView() { + return browser_->UIT_GetWebView(); +} + +BrowserWebViewDelegate* WebDropTarget::getDelegate() { + return browser_->UIT_GetWebViewDelegate(); +} + +bool WebDropTarget::OnDragMove(GtkWidget* widget, GdkDragContext* context, + gint x, gint y, guint time) { + WebView* webview = getView(); + gint widget_x, widget_y; + WebDragOperation operation; + gtk_widget_translate_coordinates(gtk_widget_get_toplevel(widget), widget, x, + y, &widget_x, &widget_y); + + // Request all the data and potentially start the DnD. + if (context_ != context) { + drop_data_.reset(new WebDropData); + data_requests_ = arraysize(supported_targets); + for (size_t i = 0; i < arraysize(supported_targets); ++i) { + gtk_drag_get_data(widget, context, + ui::GetAtomForTarget(supported_targets[i]), + time); + } + } else if (data_requests_ == 0) { + operation = webview->dragTargetDragOver(WebPoint(x, y), + WebPoint(widget_x, widget_y), + _mask(context)); + gdk_drag_status(context, + (GdkDragAction)DragDropTypes::DragOperationToGdkDragAction(operation), + time); + } + return TRUE; +} + +// Real DragLeave +void WebDropTarget::DragLeave() { + WebView* webview = getView(); + webview->dragTargetDragLeave(); +} + +// GTK Sends DragDrop (immediately) after DragLeave +// So post re-post DragLeave allowing us to behave like chromium expects. +void WebDropTarget::OnDragLeave(GtkWidget* widget, GdkDragContext* context, + guint time) { + context_ = NULL; + drop_data_.reset(); + MessageLoop::current()->PostTask(FROM_HERE, + base::Bind(&WebDropTarget::DragLeave, method_factory_.GetWeakPtr())); +} + +bool WebDropTarget::OnDragDrop(GtkWidget* widget, GdkDragContext* context, + gint x, gint y, guint time) { + method_factory_.InvalidateWeakPtrs(); + + gint widget_x, widget_y; + gtk_widget_translate_coordinates(gtk_widget_get_toplevel(widget), widget, x, + y, &widget_x, &widget_y); + browser_->set_is_dropping(true); + + if (browser_->UIT_GetWebView()) { + browser_->UIT_GetWebView()->dragTargetDrop( + WebPoint(x, y), + WebPoint(widget_x, widget_y)); + } + browser_->set_is_dropping(false); + context_ = NULL; + gtk_drag_finish(context, TRUE, FALSE, time); + + return TRUE; +} + + +void WebDropTarget::OnDragDataReceived(GtkWidget* widget, + GdkDragContext* context, gint x, gint y, + GtkSelectionData* data, guint info, + guint time) { + WebDragOperation operation; + data_requests_--; + + // If the source can't provide us with valid data for a requested target, + // data->data will be NULL. + if (data->data && data->length > 0) { + if (data->target == ui::GetAtomForTarget(ui::TEXT_PLAIN) || + data->target == ui::GetAtomForTarget(ui::TEXT_PLAIN_NO_CHARSET)) { + guchar* text = gtk_selection_data_get_text(data); + if (text) { + drop_data_->text = + NullableString16(UTF8ToUTF16((const char*)text), false); + g_free(text); + } + } else if (data->target == ui::GetAtomForTarget(ui::TEXT_URI_LIST)) { + gchar** uris = gtk_selection_data_get_uris(data); + if (uris) { + drop_data_->url = GURL(); + for (gchar** uri_iter = uris; *uri_iter; uri_iter++) { + // Most file managers populate text/uri-list with file URLs when + // dragging files. To avoid exposing file system paths to web content, + // file URLs are never set as the URL content for the drop. + // TODO(estade): Can the filenames have a non-UTF8 encoding? + GURL url(*uri_iter); + FilePath file_path; + if (url.SchemeIs("file") && + net::FileURLToFilePath(url, &file_path)) { + drop_data_->filenames.push_back( + WebDropData::FileInfo(UTF8ToUTF16(file_path.value()), + string16())); + // This is a hack. Some file managers also populate text/plain with + // a file URL when dragging files, so we clear it to avoid exposing + // it to the web content. + // drop_data_->text = NullableString16(true); + } else if (!drop_data_->url.is_valid()) { + // Also set the first non-file URL as the URL content for the drop. + drop_data_->url = url; + } + } + g_strfreev(uris); + } + } else if (data->target == ui::GetAtomForTarget(ui::TEXT_HTML)) { + drop_data_->html = NullableString16( + UTF8ToUTF16(std::string(reinterpret_cast(data->data), + data->length)), false); + // We leave the base URL empty. + } else if (data->target == ui::GetAtomForTarget(ui::NETSCAPE_URL)) { + std::string netscape_url(reinterpret_cast(data->data), + data->length); + size_t split = netscape_url.find_first_of('\n'); + if (split != std::string::npos) { + drop_data_->url = GURL(netscape_url.substr(0, split)); + if (split < netscape_url.size() - 1) + drop_data_->url_title = UTF8ToUTF16(netscape_url.substr(split + 1)); + } + } else if (data->target == ui::GetAtomForTarget(ui::CHROME_NAMED_URL)) { + ui::ExtractNamedURL(data, &drop_data_->url, &drop_data_->url_title); + } + } + + if (data_requests_ == 0) { + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDragHandler(); + if (handler.get()) { + CefRefPtr data(new CefDragDataImpl(*drop_data_.get())); + if (handler->OnDragEnter(browser_, data, + (cef_drag_operations_mask_t)_mask(context))) { + operation = WebDragOperationNone; + gdk_drag_status(context, + (GdkDragAction)DragDropTypes::DragOperationToGdkDragAction( + operation), + time); + return; + } + } + } + gint widget_x, widget_y; + gtk_widget_translate_coordinates(gtk_widget_get_toplevel(widget), widget, + x, y, &widget_x, &widget_y); + WebView* webview = getView(); + operation = webview->dragTargetDragEnter(drop_data_->ToDragData(), + WebPoint(x, y), + WebPoint(widget_x, widget_y), + _mask(context)); + gdk_drag_status(context, + (GdkDragAction)DragDropTypes::DragOperationToGdkDragAction(operation), + time); + context_ = context; + } +} diff --git a/cef1/libcef/web_drop_target_gtk.h b/cef1/libcef/web_drop_target_gtk.h new file mode 100644 index 000000000..0032551e0 --- /dev/null +++ b/cef1/libcef/web_drop_target_gtk.h @@ -0,0 +1,52 @@ +// Copyright (c) 2012 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. + +#ifndef CEF_LIBCEF_WEB_DROP_TARGET_GTK_H_ +#define CEF_LIBCEF_WEB_DROP_TARGET_GTK_H_ + +#include +#include "base/memory/ref_counted.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" + +class BrowserWebViewDelegate; +class CefBrowserImpl; +class WebDropData; + +namespace WebKit { +class WebView; +} + +class WebDropTarget : public base::RefCounted { + public: + explicit WebDropTarget(CefBrowserImpl* browser); + virtual ~WebDropTarget(); + + WebKit::WebView* getView(); + BrowserWebViewDelegate* getDelegate(); + + // Called by GTK callbacks + bool OnDragMove(GtkWidget* widget, GdkDragContext* context, gint x, gint y, + guint time); + void OnDragLeave(GtkWidget* widget, GdkDragContext* context, guint time); + bool OnDragDrop(GtkWidget* widget, GdkDragContext* context, gint x, gint y, + guint time); + void OnDragEnd(GtkWidget* widget, GdkDragContext* context, guint time); + void OnDragDataReceived(GtkWidget* widget, GdkDragContext* context, gint x, + gint y, GtkSelectionData* data, guint info, + guint time); + void DragLeave(); + + private: + CefBrowserImpl* browser_; + scoped_ptr drop_data_; + bool entered_; + int data_requests_; + GdkDragContext* context_; + base::WeakPtrFactory method_factory_; +}; + +#endif // CEF_LIBCEF_WEB_DROP_TARGET_GTK_H_ + diff --git a/cef1/libcef/web_drop_target_mac.h b/cef1/libcef/web_drop_target_mac.h new file mode 100644 index 000000000..acfe102e1 --- /dev/null +++ b/cef1/libcef/web_drop_target_mac.h @@ -0,0 +1,69 @@ +// 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. + +#ifndef CEF_LIBCEF_WEB_DROP_TARGET_MAC_H_ +#define CEF_LIBCEF_WEB_DROP_TARGET_MAC_H_ +#pragma once + +#import + +#include "base/string16.h" + +class GURL; +struct WebDropData; +@class BrowserWebView; +class WebViewHost; + +// A class that handles tracking and event processing for a drag and drop +// over the content area. Assumes something else initiates the drag, this is +// only for processing during a drag. + +@interface WebDropTarget : NSObject { + @private + // Our associated WebView. Weak reference. + BrowserWebView* view_; + + // Keep track of the WebViewHost we're dragging over. If it changes during a + // drag, we need to re-send the DragEnter message. + WebViewHost* current_wvh_; + + // True if the drag has been canceled. + bool canceled_; +} + +// |view| is the WebView representing this browser window, used to communicate +// drag&drop messages to WebCore and handle navigation on a successful drop +// (if necessary). +- (id)initWithWebView:(BrowserWebView*)view; + +// Messages to send during the tracking of a drag, ususally upon receiving +// calls from the view system. Communicates the drag messages to WebCore. +- (NSDragOperation)draggingEntered:(id)info + view:(NSView*)view; +- (void)draggingExited:(id)info; +- (NSDragOperation)draggingUpdated:(id)info + view:(NSView*)view; +- (BOOL)performDragOperation:(id)info + view:(NSView*)view; + +@end + +// Public use only for unit tests. +@interface WebDropTarget(Testing) +// Given |data|, which should not be nil, fill it in using the contents of the +// given pasteboard. +- (void)populateWebDropData:(WebDropData*)data + fromPasteboard:(NSPasteboard*)pboard; +// Given a point in window coordinates and a view in that window, return a +// flipped point in the coordinate system of |view|. +- (NSPoint)flipWindowPointToView:(const NSPoint&)windowPoint + view:(NSView*)view; +// Given a point in window coordinates and a view in that window, return a +// flipped point in screen coordinates. +- (NSPoint)flipWindowPointToScreen:(const NSPoint&)windowPoint + view:(NSView*)view; +@end + +#endif // CEF_LIBCEF_WEB_DROP_TARGET_MAC_H_ diff --git a/cef1/libcef/web_drop_target_mac.mm b/cef1/libcef/web_drop_target_mac.mm new file mode 100644 index 000000000..9aefc196a --- /dev/null +++ b/cef1/libcef/web_drop_target_mac.mm @@ -0,0 +1,260 @@ +// 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. + +#include "libcef/browser_impl.h" +#import "libcef/browser_webview_mac.h" +#include "libcef/cef_context.h" +#include "libcef/drag_data_impl.h" +#import "libcef/web_drop_target_mac.h" +#import "libcef/web_drag_utils_mac.h" + +#include "base/logging.h" +#include "base/sys_string_conversions.h" +#import "third_party/mozilla/NSPasteboard+Utils.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/window_open_disposition.h" + +using WebKit::WebDragOperation; +using WebKit::WebDragOperationsMask; +using WebKit::WebPoint; +using WebKit::WebView; + +@implementation WebDropTarget + +// |view| is the WebView representing this browser window, used to communicate +// drag&drop messages to WebCore and handle navigation on a successful drop +// (if necessary). +- (id)initWithWebView:(BrowserWebView*)view { + if ((self = [super init])) { + view_ = view; + canceled_ = false; + } + return self; +} + +// Given a point in window coordinates and a view in that window, return a +// flipped point in the coordinate system of |view|. +- (NSPoint)flipWindowPointToView:(const NSPoint&)windowPoint + view:(NSView*)view { + DCHECK(view); + NSPoint viewPoint = [view convertPoint:windowPoint fromView:nil]; + NSRect viewFrame = [view frame]; + viewPoint.y = viewFrame.size.height - viewPoint.y; + return viewPoint; +} + +// Given a point in window coordinates and a view in that window, return a +// flipped point in screen coordinates. +- (NSPoint)flipWindowPointToScreen:(const NSPoint&)windowPoint + view:(NSView*)view { + DCHECK(view); + NSPoint screenPoint = [[view window] convertBaseToScreen:windowPoint]; + NSScreen* screen = [[view window] screen]; + NSRect screenFrame = [screen frame]; + screenPoint.y = screenFrame.size.height - screenPoint.y; + return screenPoint; +} + +// Return YES if the drop site only allows drops that would navigate. If this +// is the case, we don't want to pass messages to the renderer because there's +// really no point (i.e., there's nothing that cares about the mouse position or +// entering and exiting). One example is an interstitial page (e.g., safe +// browsing warning). +- (BOOL)onlyAllowsNavigation { + return false; +} + +// Messages to send during the tracking of a drag, usually upon receiving +// calls from the view system. Communicates the drag messages to WebCore. + +- (NSDragOperation)draggingEntered:(id)info + view:(NSView*)view { + // Save off the current WebViewHost so we can tell if it changes during a + // drag. If it does, we need to send a new enter message in draggingUpdated:. + current_wvh_ = _Context->current_webviewhost(); + DCHECK(current_wvh_); + + if ([self onlyAllowsNavigation]) { + if ([[info draggingPasteboard] containsURLData]) + return NSDragOperationCopy; + return NSDragOperationNone; + } + + WebView* webview = view_.browser->UIT_GetWebView(); + + // Fill out a WebDropData from pasteboard. + WebDropData drop_data; + [self populateWebDropData:&drop_data + fromPasteboard:[info draggingPasteboard]]; + + NSDragOperation mask = [info draggingSourceOperationMask]; + + canceled_ = false; + + CefRefPtr client = view_.browser->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDragHandler(); + if (handler.get()) { + CefRefPtr data(new CefDragDataImpl(drop_data)); + if (handler->OnDragEnter(view_.browser, data, + static_cast(mask))) { + canceled_ = true; + return NSDragOperationNone; + } + } + } + + // Create the appropriate mouse locations for WebCore. The draggingLocation + // is in window coordinates. Both need to be flipped. + NSPoint windowPoint = [info draggingLocation]; + NSPoint viewPoint = [self flipWindowPointToView:windowPoint view:view]; + NSPoint screenPoint = [self flipWindowPointToScreen:windowPoint view:view]; + WebDragOperation op = + webview->dragTargetDragEnter(drop_data.ToDragData(), + WebPoint(viewPoint.x, viewPoint.y), + WebPoint(screenPoint.x, screenPoint.y), + static_cast(mask)); + return static_cast(op); +} + +- (void)draggingExited:(id)info { + DCHECK(current_wvh_); + if (current_wvh_ != _Context->current_webviewhost()) + return; + + if (canceled_) + return; + + WebView* webview = view_.browser->UIT_GetWebView(); + + // Nothing to do in the interstitial case. + + webview->dragTargetDragLeave(); +} + +- (NSDragOperation)draggingUpdated:(id)info + view:(NSView*)view { + DCHECK(current_wvh_); + if (current_wvh_ != _Context->current_webviewhost()) + [self draggingEntered:info view:view]; + + if ([self onlyAllowsNavigation]) { + if ([[info draggingPasteboard] containsURLData]) + return NSDragOperationCopy; + return NSDragOperationNone; + } + + if (canceled_) + return NSDragOperationNone; + + WebView* webview = view_.browser->UIT_GetWebView(); + + // Create the appropriate mouse locations for WebCore. The draggingLocation + // is in window coordinates. + NSPoint windowPoint = [info draggingLocation]; + NSPoint viewPoint = [self flipWindowPointToView:windowPoint view:view]; + NSPoint screenPoint = [self flipWindowPointToScreen:windowPoint view:view]; + NSDragOperation mask = [info draggingSourceOperationMask]; + WebDragOperation op = + webview->dragTargetDragOver(WebPoint(viewPoint.x, viewPoint.y), + WebPoint(screenPoint.x, screenPoint.y), + static_cast(mask)); + return static_cast(op); +} + +- (BOOL)performDragOperation:(id)info + view:(NSView*)view { + DCHECK(current_wvh_); + if (current_wvh_ != _Context->current_webviewhost()) + [self draggingEntered:info view:view]; + + // Check if we only allow navigation and navigate to a url on the pasteboard. + if ([self onlyAllowsNavigation]) { + NSPasteboard* pboard = [info draggingPasteboard]; + if ([pboard containsURLData]) { + GURL url; + drag_util::PopulateURLAndTitleFromPasteBoard(&url, NULL, pboard, YES); + view_.browser->GetMainFrame()->LoadURL(url.spec()); + return YES; + } + return NO; + } + + current_wvh_ = NULL; + + WebView* webview = view_.browser->UIT_GetWebView(); + + // Create the appropriate mouse locations for WebCore. The draggingLocation + // is in window coordinates. Both need to be flipped. + NSPoint windowPoint = [info draggingLocation]; + NSPoint viewPoint = [self flipWindowPointToView:windowPoint view:view]; + NSPoint screenPoint = [self flipWindowPointToScreen:windowPoint view:view]; + + view_.browser->set_is_dropping(true); + webview->dragTargetDrop(gfx::Point(viewPoint.x, viewPoint.y), + gfx::Point(screenPoint.x, screenPoint.y)); + view_.browser->set_is_dropping(false); + + return YES; +} + +// Given |data|, which should not be nil, fill it in using the contents of the +// given pasteboard. +- (void)populateWebDropData:(WebDropData*)data + fromPasteboard:(NSPasteboard*)pboard { + DCHECK(data); + DCHECK(pboard); + NSArray* types = [pboard types]; + + // Get URL if possible. To avoid exposing file system paths to web content, + // filenames in the drag are not converted to file URLs. + drag_util::PopulateURLAndTitleFromPasteBoard(&data->url, + &data->url_title, + pboard, + NO); + + // Get plain text. + if ([types containsObject:NSStringPboardType]) { + data->text = NullableString16( + base::SysNSStringToUTF16([pboard stringForType:NSStringPboardType]), + false); + } + + // Get HTML. If there's no HTML, try RTF. + if ([types containsObject:NSHTMLPboardType]) { + data->html = NullableString16( + base::SysNSStringToUTF16([pboard stringForType:NSHTMLPboardType]), + false); + } else if ([types containsObject:NSRTFPboardType]) { + NSString* html = [pboard htmlFromRtf]; + data->html = NullableString16(base::SysNSStringToUTF16(html), false); + } + + // Get files. + if ([types containsObject:NSFilenamesPboardType]) { + NSArray* files = [pboard propertyListForType:NSFilenamesPboardType]; + if ([files isKindOfClass:[NSArray class]] && [files count]) { + for (NSUInteger i = 0; i < [files count]; i++) { + NSString* filename = [files objectAtIndex:i]; + BOOL isDir = NO; + BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:filename + isDirectory:&isDir]; + if (exists && !isDir) { + data->filenames.push_back( + WebDropData::FileInfo(base::SysNSStringToUTF16(filename), + string16())); + } + } + } + } + + // TODO(pinkerton): Get file contents. http://crbug.com/34661 +} + +@end diff --git a/cef1/libcef/web_drop_target_win.cc b/cef1/libcef/web_drop_target_win.cc new file mode 100644 index 000000000..aa1b29599 --- /dev/null +++ b/cef1/libcef/web_drop_target_win.cc @@ -0,0 +1,184 @@ +// 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. + +#include "libcef/web_drop_target_win.h" + +#include +#include + +#include "libcef/browser_impl.h" +#include "libcef/cef_context.h" +#include "libcef/drag_data_impl.h" +#include "libcef/web_drag_utils_win.h" + +#include "googleurl/src/gurl.h" +#include "net/base/net_util.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebDragData.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebPoint.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/base/clipboard/clipboard_util_win.h" +#include "ui/base/dragdrop/os_exchange_data.h" +#include "ui/base/dragdrop/os_exchange_data_provider_win.h" +#include "webkit/glue/webdropdata.h" +#include "webkit/glue/window_open_disposition.h" + +using WebKit::WebDragOperation; +using WebKit::WebDragOperationNone; +using WebKit::WebDragOperationCopy; +using WebKit::WebDragOperationLink; +using WebKit::WebDragOperationMove; +using WebKit::WebDragOperationGeneric; +using WebKit::WebPoint; +using WebKit::WebView; + +namespace { + +// A helper method for getting the preferred drop effect. +DWORD GetPreferredDropEffect(DWORD effect) { + if (effect & DROPEFFECT_COPY) + return DROPEFFECT_COPY; + if (effect & DROPEFFECT_LINK) + return DROPEFFECT_LINK; + if (effect & DROPEFFECT_MOVE) + return DROPEFFECT_MOVE; + return DROPEFFECT_NONE; +} + +} // namespace + +WebDropTarget::WebDropTarget(CefBrowserImpl* browser) + : ui::DropTarget(browser->UIT_GetWebViewWndHandle()), + browser_(browser), + current_wvh_(NULL), + drag_cursor_(WebDragOperationNone), + canceled_(false) { +} + +WebDropTarget::~WebDropTarget() { +} + +DWORD WebDropTarget::OnDragEnter(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effects) { + current_wvh_ = _Context->current_webviewhost(); + DCHECK(current_wvh_); + + // TODO(tc): PopulateWebDropData can be slow depending on what is in the + // IDataObject. Maybe we can do this in a background thread. + WebDropData drop_data; + WebDropData::PopulateWebDropData(data_object, &drop_data); + + // Clear the fields that are currently unused when dragging into WebKit. + // Remove these lines once PopulateWebDropData() is updated not to set them. + // See crbug.com/112255. + if (!drop_data.file_contents.empty()) + drop_data.file_contents.clear(); + if (!drop_data.file_description_filename.empty()) + drop_data.file_description_filename.clear(); + + if (drop_data.url.is_empty()) + ui::OSExchangeDataProviderWin::GetPlainTextURL(data_object, &drop_data.url); + + WebKit::WebDragOperationsMask mask = + web_drag_utils_win::WinDragOpMaskToWebDragOpMask(effects); + + canceled_ = false; + + CefRefPtr client = browser_->GetClient(); + if (client.get()) { + CefRefPtr handler = client->GetDragHandler(); + if (handler.get()) { + CefRefPtr data(new CefDragDataImpl(drop_data)); + if (handler->OnDragEnter(browser_, data, + static_cast(mask))) { + canceled_ = true; + return DROPEFFECT_NONE; + } + } + } + + drag_cursor_ = WebDragOperationNone; + + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + WebDragOperation operation; + if (browser_->UIT_GetWebView()) { + operation = browser_->UIT_GetWebView()->dragTargetDragEnter( + drop_data.ToDragData(), + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y), + mask); + } else { + operation = WebDragOperationNone; + } + + return web_drag_utils_win::WebDragOpToWinDragOp(operation); +} + +DWORD WebDropTarget::OnDragOver(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effects) { + DCHECK(current_wvh_); + if (current_wvh_ != _Context->current_webviewhost()) + OnDragEnter(data_object, key_state, cursor_position, effects); + + if (canceled_) + return DROPEFFECT_NONE; + + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + WebDragOperation operation; + if (browser_->UIT_GetWebView()) { + operation = browser_->UIT_GetWebView()->dragTargetDragOver( + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y), + web_drag_utils_win::WinDragOpMaskToWebDragOpMask(effects)); + } else { + operation = WebDragOperationNone; + } + + return web_drag_utils_win::WebDragOpToWinDragOp(operation); +} + +void WebDropTarget::OnDragLeave(IDataObject* data_object) { + DCHECK(current_wvh_); + if (current_wvh_ != _Context->current_webviewhost()) + return; + + if (canceled_) + return; + + if (browser_->UIT_GetWebView()) + browser_->UIT_GetWebView()->dragTargetDragLeave(); +} + +DWORD WebDropTarget::OnDrop(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect) { + DCHECK(current_wvh_); + if (current_wvh_ != _Context->current_webviewhost()) + OnDragEnter(data_object, key_state, cursor_position, effect); + + POINT client_pt = cursor_position; + ScreenToClient(GetHWND(), &client_pt); + + browser_->set_is_dropping(true); + if (browser_->UIT_GetWebView()) { + browser_->UIT_GetWebView()->dragTargetDrop( + WebPoint(client_pt.x, client_pt.y), + WebPoint(cursor_position.x, cursor_position.y)); + } + browser_->set_is_dropping(false); + + current_wvh_ = NULL; + + // This isn't always correct, but at least it's a close approximation. + // For now, we always map a move to a copy to prevent potential data loss. + DWORD drop_effect = web_drag_utils_win::WebDragOpToWinDragOp(drag_cursor_); + return drop_effect != DROPEFFECT_MOVE ? drop_effect : DROPEFFECT_COPY; +} diff --git a/cef1/libcef/web_drop_target_win.h b/cef1/libcef/web_drop_target_win.h new file mode 100644 index 000000000..5759c9bda --- /dev/null +++ b/cef1/libcef/web_drop_target_win.h @@ -0,0 +1,69 @@ +// Copyright (c) 2011 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. + +#ifndef CEF_LIBCEF_WEB_DROP_TARGET_WIN_H_ +#define CEF_LIBCEF_WEB_DROP_TARGET_WIN_H_ +#pragma once + +#include "base/memory/scoped_ptr.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebDragOperation.h" +#include "ui/base/dragdrop/drop_target.h" + +class CefBrowserImpl; +class WebViewHost; + +// A helper object that provides drop capabilities to a WebView. The +// DropTarget handles drags that enter the region of the WebView by +// passing on the events to the renderer. +class WebDropTarget : public ui::DropTarget { + public: + // Create a new WebDropTarget associating it with the given HWND and + // WebView. + explicit WebDropTarget(CefBrowserImpl* browser); + virtual ~WebDropTarget(); + + void set_drag_cursor(WebKit::WebDragOperation op) { + drag_cursor_ = op; + } + + protected: + virtual DWORD OnDragEnter(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect); + + virtual DWORD OnDragOver(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect); + + virtual void OnDragLeave(IDataObject* data_object); + + virtual DWORD OnDrop(IDataObject* data_object, + DWORD key_state, + POINT cursor_position, + DWORD effect); + + private: + // Our associated CefBrowserImpl. + CefBrowserImpl* browser_; + + // We keep track of the web view host we're dragging over. If it changes + // during a drag, we need to re-send the DragEnter message. WARNING: + // this pointer should never be dereferenced. We only use it for comparing + // pointers. + WebViewHost* current_wvh_; + + // Used to determine what cursor we should display when dragging over web + // content area. This can be updated async during a drag operation. + WebKit::WebDragOperation drag_cursor_; + + // True if the drag has been canceled. + bool canceled_; + + DISALLOW_COPY_AND_ASSIGN(WebDropTarget); +}; + +#endif // CEF_LIBCEF_WEB_DROP_TARGET_WIN_H_ diff --git a/cef1/libcef/web_plugin_impl.cc b/cef1/libcef/web_plugin_impl.cc new file mode 100644 index 000000000..1cb0b1415 --- /dev/null +++ b/cef1/libcef/web_plugin_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_web_plugin.h" +#include "libcef/cef_context.h" +#include "libcef/cef_thread.h" + +#include "base/file_path.h" +#include "base/string_util.h" +#include "webkit/plugins/npapi/plugin_list.h" + +namespace { + +class CefWebPluginInfoImpl : public CefWebPluginInfo { + public: + explicit CefWebPluginInfoImpl(const webkit::WebPluginInfo& plugin_info) + : plugin_info_(plugin_info) { + } + + virtual CefString GetName() OVERRIDE { + return plugin_info_.name; + } + + virtual CefString GetPath() OVERRIDE { + return plugin_info_.path.value(); + } + + virtual CefString GetVersion() OVERRIDE { + return plugin_info_.version; + } + + virtual CefString GetDescription() OVERRIDE { + return plugin_info_.desc; + } + + private: + webkit::WebPluginInfo plugin_info_; + + IMPLEMENT_REFCOUNTING(CefWebPluginInfoImpl); +}; + +} // namespace + +size_t CefGetWebPluginCount() { + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return 0; + } + + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return 0; + } + + std::vector plugins; + webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins); + return plugins.size(); +} + +CefRefPtr CefGetWebPluginInfo(int index) { + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return 0; + } + + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return 0; + } + + std::vector plugins; + webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins); + + if (index < 0 || index >= static_cast(plugins.size())) + return NULL; + + return new CefWebPluginInfoImpl(plugins[index]); +} + +CefRefPtr CefGetWebPluginInfo(const CefString& name) { + if (!CONTEXT_STATE_VALID()) { + NOTREACHED() << "context not valid"; + return 0; + } + + if (!CefThread::CurrentlyOn(CefThread::UI)) { + NOTREACHED() << "called on invalid thread"; + return 0; + } + + std::vector plugins; + webkit::npapi::PluginList::Singleton()->GetPlugins(&plugins); + + std::string nameStr = name; + StringToLowerASCII(&nameStr); + + std::vector::const_iterator it = plugins.begin(); + for (; it != plugins.end(); ++it) { + if (LowerCaseEqualsASCII(it->name, nameStr.c_str())) + return new CefWebPluginInfoImpl(*it); + } + + return NULL; +} diff --git a/cef1/libcef/web_urlrequest_impl.cc b/cef1/libcef/web_urlrequest_impl.cc new file mode 100644 index 000000000..16c8a30d1 --- /dev/null +++ b/cef1/libcef/web_urlrequest_impl.cc @@ -0,0 +1,304 @@ +// 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/web_urlrequest_impl.h" +#include "libcef/browser_webkit_init.h" +#include "libcef/cef_thread.h" +#include "libcef/request_impl.h" +#include "libcef/response_impl.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "base/memory/scoped_ptr.h" +#include "googleurl/src/gurl.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLError.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLLoaderClient.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLRequest.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" +#include "webkit/glue/weburlloader_impl.h" + +using WebKit::WebURLError; +using WebKit::WebURLLoader; +using WebKit::WebURLRequest; +using WebKit::WebURLResponse; + +namespace { +class CefWebURLLoaderClientImpl; +}; + +// Manages the lifespan of WebKit objects. Methods of this class will only be +// called on the UI thread. +class CefWebURLRequestImpl::Context + : public base::RefCountedThreadSafe { + public: + explicit Context(CefRefPtr client) + : client_(client) { + } + virtual ~Context() { + } + + void initialize(CefRefPtr request); + void destroy(); + void cancel(); + + CefRefPtr client() { return client_; } + + protected: + CefRefPtr client_; + scoped_ptr url_loader_; + scoped_ptr url_client_; +}; + + +namespace { + +// Implements the WebURLLoaderClient interface. Methods of this class will only +// be called on the UI thread. +class CefWebURLLoaderClientImpl : public WebKit::WebURLLoaderClient { + public: + explicit CefWebURLLoaderClientImpl(CefWebURLRequestImpl::Context* context) + : context_(context) { + } + virtual ~CefWebURLLoaderClientImpl() { + } + + // ===================================================================== + // WebKit::WebURLLoaderClient API + // + + // Called when following a redirect. |newRequest| contains the request + // generated by the redirect. The client may modify |newRequest|. + virtual void willSendRequest(WebKit::WebURLLoader*, + WebKit::WebURLRequest& newRequest, + const WebKit::WebURLResponse& redirectResponse) { + REQUIRE_UIT(); + if (!context_) + return; + + CefRefPtr client = context_->client(); + if (client.get()) { + CefRefPtr handler = client->GetHandler(); + if (handler.get()) { + CefRefPtr cefRequest(new CefRequestImpl()); + CefRefPtr cefResponse( + new CefResponseImpl(redirectResponse)); + + cefRequest->Set(newRequest); + handler->OnRedirect(client.get(), cefRequest.get(), cefResponse); + cefRequest->Get(newRequest); + } + } + } + + // Called to report upload progress. The bytes reported correspond to + // the HTTP message body. + virtual void didSendData( + WebKit::WebURLLoader*, + unsigned long long bytesSent, // NOLINT(runtime/int) + unsigned long long totalBytesToBeSent) { // NOLINT(runtime/int) + REQUIRE_UIT(); + if (!context_) + return; + + CefRefPtr client = context_->client(); + if (client.get()) { + CefRefPtr handler = client->GetHandler(); + if (handler.get()) + handler->OnProgress(client.get(), bytesSent, totalBytesToBeSent); + } + } + + // Called when response headers are received. + virtual void didReceiveResponse(WebKit::WebURLLoader*, + const WebKit::WebURLResponse& response) { + REQUIRE_UIT(); + if (!context_) + return; + + CefRefPtr client = context_->client(); + if (client.get()) { + client->DoStateChange(WUR_STATE_HEADERS_RECEIVED); + CefRefPtr handler = client->GetHandler(); + if (handler.get()) { + CefRefPtr cefResponse(new CefResponseImpl(response)); + handler->OnHeadersReceived(client.get(), cefResponse); + } + } + } + + // Called when a chunk of response data is downloaded. This is only called + // if WebURLRequest's downloadToFile flag was set to true. + virtual void didDownloadData(WebKit::WebURLLoader*, int dataLength) { + NOTREACHED(); + } + + // Called when a chunk of response data is received. + virtual void didReceiveData(WebURLLoader*, const char* data, int dataLength, + int lengthReceived) { + REQUIRE_UIT(); + if (!context_) + return; + + CefRefPtr client = context_->client(); + if (client.get()) { + client->DoStateChange(WUR_STATE_LOADING); + CefRefPtr handler = client->GetHandler(); + if (handler.get()) { + handler->OnData(client.get(), data, dataLength); + } + } + } + + // Called when a chunk of renderer-generated metadata is received from + // the cache. + virtual void didReceiveCachedMetadata(WebKit::WebURLLoader*, const char* data, + int dataLength) { + NOTREACHED(); + } + + // Called when the load completes successfully. + virtual void didFinishLoading(WebKit::WebURLLoader*, double finishTime) { + REQUIRE_UIT(); + if (!context_) + return; + + CefRefPtr client = context_->client(); + if (client.get()) + client->DoStateChange(WUR_STATE_DONE); + + complete(); + } + + // Called when the load completes with an error. + virtual void didFail(WebKit::WebURLLoader*, + const WebKit::WebURLError& error) { + REQUIRE_UIT(); + if (!context_) + return; + + CefRefPtr client = context_->client(); + if (client.get() && client->GetState() != WUR_STATE_ABORT) { + client->DoStateChange(WUR_STATE_ERROR); + CefRefPtr handler = client->GetHandler(); + if (handler.get()) { + handler->OnError(client.get(), + static_cast(error.reason)); + } + } + + complete(); + } + + void complete() { + context_->destroy(); + context_ = NULL; + } + + protected: + scoped_refptr context_; +}; + +} // namespace + + +// CefWebURLManager + +void CefWebURLRequestImpl::Context::initialize( + CefRefPtr request) { + REQUIRE_UIT(); + + url_loader_.reset( + new webkit_glue::WebURLLoaderImpl(reinterpret_cast( + WebKit::webKitPlatformSupport()))); + url_client_.reset(new CefWebURLLoaderClientImpl(this)); + + WebURLRequest urlRequest; + static_cast(request.get())->Get(urlRequest); + url_loader_->loadAsynchronously(urlRequest, url_client_.get()); +} + +void CefWebURLRequestImpl::Context::destroy() { + REQUIRE_UIT(); + client_ = NULL; +} + +void CefWebURLRequestImpl::Context::cancel() { + REQUIRE_UIT(); + url_loader_->cancel(); + url_client_->complete(); +} + + +// CefWebURLRequest + +// static +CefRefPtr +CefWebURLRequest::CreateWebURLRequest( + CefRefPtr request, CefRefPtr client) { + CefRefPtr requester = new CefWebURLRequestImpl(client); + + // Send the request from the UI thread. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefWebURLRequestImpl::DoSend, requester.get(), request)); + + return requester.get(); +} + + +// CefWebURLRequestImpl + +CefWebURLRequestImpl::CefWebURLRequestImpl( + CefRefPtr handler) + : handler_(handler), + state_(WUR_STATE_UNSENT) { +} + +CefWebURLRequestImpl::~CefWebURLRequestImpl() { +} + +CefWebURLRequestImpl::RequestState CefWebURLRequestImpl::GetState() { + AutoLock lock_scope(this); + return state_; +} + +void CefWebURLRequestImpl::Cancel() { + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&CefWebURLRequestImpl::DoCancel, this)); +} + +void CefWebURLRequestImpl::DoSend(CefRefPtr request) { + REQUIRE_UIT(); + DCHECK(state_ == WUR_STATE_UNSENT); + + context_ = new CefWebURLRequestImpl::Context(this); + context_->initialize(request); + + DoStateChange(WUR_STATE_STARTED); +} + +void CefWebURLRequestImpl::DoCancel() { + REQUIRE_UIT(); + + if (state_ < WUR_STATE_DONE) { + DoStateChange(WUR_STATE_ABORT); + context_->cancel(); + } +} + +void CefWebURLRequestImpl::DoStateChange(RequestState newState) { + REQUIRE_UIT(); + + if (state_ == newState) + return; + + { + AutoLock lock_scope(this); + state_ = newState; + } + + if (handler_.get()) + handler_->OnStateChange(this, newState); +} diff --git a/cef1/libcef/web_urlrequest_impl.h b/cef1/libcef/web_urlrequest_impl.h new file mode 100644 index 000000000..774ffc66a --- /dev/null +++ b/cef1/libcef/web_urlrequest_impl.h @@ -0,0 +1,44 @@ +// 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_LIBCEF_WEB_URLREQUEST_IMPL_H_ +#define CEF_LIBCEF_WEB_URLREQUEST_IMPL_H_ +#pragma once + +#include "include/cef_web_urlrequest.h" +#include "base/memory/ref_counted.h" + +class CefWebURLRequestImpl : public CefWebURLRequest { + public: + class Context; + + explicit CefWebURLRequestImpl( + CefRefPtr handler); + virtual ~CefWebURLRequestImpl(); + + // Can be called on any thread. + virtual RequestState GetState() OVERRIDE; + virtual void Cancel() OVERRIDE; + + // Can only be called on the UI thread. + void DoSend(CefRefPtr request); + void DoCancel(); + void DoStateChange(RequestState newState); + + CefRefPtr GetHandler() { return handler_; } + + static bool ImplementsThreadSafeReferenceCounting() { return true; } + + protected: + CefRefPtr handler_; + + // The below parameters are only modified on the UI thread. + RequestState state_; + scoped_refptr context_; + + IMPLEMENT_REFCOUNTING(CefWebURLRequestImpl); + IMPLEMENT_LOCKING(CefWebURLRequestImpl); +}; + +#endif // CEF_LIBCEF_WEB_URLREQUEST_IMPL_H_ diff --git a/cef1/libcef/webview_host.cc b/cef1/libcef/webview_host.cc new file mode 100644 index 000000000..a448ed907 --- /dev/null +++ b/cef1/libcef/webview_host.cc @@ -0,0 +1,14 @@ +// 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/webview_host.h" + +WebViewHost::WebViewHost(BrowserWebViewDelegate* delegate) + : delegate_(delegate) { +} + +#if !defined(OS_MACOSX) +WebViewHost::~WebViewHost() { +} +#endif diff --git a/cef1/libcef/webview_host.h b/cef1/libcef/webview_host.h new file mode 100644 index 000000000..d4acf7462 --- /dev/null +++ b/cef1/libcef/webview_host.h @@ -0,0 +1,82 @@ +// 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. + +#ifndef CEF_LIBCEF_WEBVIEW_HOST_H_ +#define CEF_LIBCEF_WEBVIEW_HOST_H_ +#pragma once + +#include "libcef/webwidget_host.h" +#include "base/basictypes.h" +#include "ui/gfx/native_widget_types.h" + +#if defined(TOOLKIT_GTK) +#include "webkit/plugins/npapi/gtk_plugin_container_manager.h" +#endif + +class BrowserWebViewDelegate; + +namespace webkit_glue { +struct WebPreferences; +} + +namespace WebKit { +class WebDevToolsAgentClient; +class WebView; +} + +// This class is a simple NativeView-based host for a WebView +class WebViewHost : public WebWidgetHost { + public: + // The new instance is deleted once the associated NativeView is destroyed. + // The newly created window should be resized after it is created, using the + // MoveWindow (or equivalent) function. + static WebViewHost* Create(gfx::NativeView parent_view, + const gfx::Rect& rect, + BrowserWebViewDelegate* delegate, + PaintDelegate* paint_delegate, + WebKit::WebDevToolsAgentClient* devtools_client, + const webkit_glue::WebPreferences& prefs); + + virtual ~WebViewHost(); + + WebKit::WebView* webview() const; + +#if defined(TOOLKIT_GTK) + // Create a new plugin parent container for a given plugin XID. + void CreatePluginContainer(gfx::PluginWindowHandle id); + + // Destroy the plugin parent container when a plugin has been destroyed. + void DestroyPluginContainer(gfx::PluginWindowHandle id); + + webkit::npapi::GtkPluginContainerManager* plugin_container_manager() { + return &plugin_container_manager_; + } + + virtual void KeyEvent(GdkEventKey* event); +#elif defined(OS_MACOSX) + void SetIsActive(bool active); + virtual void MouseEvent(NSEvent* event); + virtual void KeyEvent(NSEvent* event); + virtual void SetFocus(bool enable); +#endif + + protected: + explicit WebViewHost(BrowserWebViewDelegate* delegate); + +#if defined(OS_WIN) + virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam); + virtual void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam); + virtual void KeyEvent(UINT message, WPARAM wparam, LPARAM lparam); +#endif + +#if defined(TOOLKIT_GTK) + // Helper class that creates and moves plugin containers. + webkit::npapi::GtkPluginContainerManager plugin_container_manager_; +#endif + + // The delegate pointer will always outlive the WebViewHost object. + BrowserWebViewDelegate* delegate_; +}; + +#endif // CEF_LIBCEF_WEBVIEW_HOST_H_ diff --git a/cef1/libcef/webview_host_gtk.cc b/cef1/libcef/webview_host_gtk.cc new file mode 100644 index 000000000..829619c8b --- /dev/null +++ b/cef1/libcef/webview_host_gtk.cc @@ -0,0 +1,70 @@ +// 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. + +#include + +#include "libcef/webview_host.h" +#include "libcef/browser_webview_delegate.h" + +#include "base/logging.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/gtk/WebInputEventFactory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/gfx/rect.h" +#include "ui/gfx/size.h" +#include "webkit/glue/webpreferences.h" +#include "webkit/plugins/npapi/gtk_plugin_container.h" + +using WebKit::WebDevToolsAgentClient; +using WebKit::WebKeyboardEvent; +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebView; + +// static +WebViewHost* WebViewHost::Create(GtkWidget* parent_view, + const gfx::Rect& rect, + BrowserWebViewDelegate* delegate, + PaintDelegate* paint_delegate, + WebDevToolsAgentClient* dev_tools_client, + const webkit_glue::WebPreferences& prefs) { + WebViewHost* host = new WebViewHost(delegate); + + host->view_ = WebWidgetHost::CreateWidget(parent_view, host); + host->plugin_container_manager_.set_host_widget(host->view_); + +#if defined(WEBKIT_HAS_WEB_AUTO_FILL_CLIENT) + host->webwidget_ = WebView::create(delegate, NULL); +#else + host->webwidget_ = WebView::create(delegate); +#endif + host->webview()->setDevToolsAgentClient(dev_tools_client); + host->webview()->setPermissionClient(delegate); + host->webview()->setPrerendererClient(delegate); + prefs.Apply(host->webview()); + host->webview()->initializeMainFrame(delegate); + host->webwidget_->layout(); + + return host; +} + +WebView* WebViewHost::webview() const { + return static_cast(webwidget_); +} + +void WebViewHost::CreatePluginContainer(gfx::PluginWindowHandle id) { + plugin_container_manager_.CreatePluginContainer(id); +} + +void WebViewHost::DestroyPluginContainer(gfx::PluginWindowHandle id) { + plugin_container_manager_.DestroyPluginContainer(id); +} + +void WebViewHost::KeyEvent(GdkEventKey* event) { + WebKeyboardEvent keyboard_event(WebInputEventFactory::keyboardEvent(event)); + if (delegate_->OnKeyboardEvent(keyboard_event, false)) + return; + + WebWidgetHost::KeyEvent(event); +} diff --git a/cef1/libcef/webview_host_mac.mm b/cef1/libcef/webview_host_mac.mm new file mode 100644 index 000000000..cb4e93127 --- /dev/null +++ b/cef1/libcef/webview_host_mac.mm @@ -0,0 +1,97 @@ +// Copyright (c) 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. + +#import + +#include "libcef/webview_host.h" +#include "libcef/browser_webview_delegate.h" +#include "libcef/browser_webview_mac.h" +#include "libcef/cef_context.h" + +#include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/mac/WebInputEventFactory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "ui/gfx/rect.h" +#include "ui/gfx/size.h" +#include "webkit/glue/webpreferences.h" + +using WebKit::WebDevToolsAgentClient; +using WebKit::WebKeyboardEvent; +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebSize; +using WebKit::WebView; + +// static +WebViewHost* WebViewHost::Create(NSView* parent_view, + const gfx::Rect& rect, + BrowserWebViewDelegate* delegate, + PaintDelegate* paint_delegate, + WebDevToolsAgentClient* dev_tools_client, + const webkit_glue::WebPreferences& prefs) { + WebViewHost* host = new WebViewHost(delegate); + + NSRect content_rect = {{rect.x(), rect.y()}, {rect.width(), rect.height()}}; + if (!paint_delegate) { + host->view_ = [[BrowserWebView alloc] initWithFrame:content_rect]; + [host->view_ setAutoresizingMask:(NSViewWidthSizable | + NSViewHeightSizable)]; + [parent_view addSubview:host->view_]; + [host->view_ release]; + } else { + host->paint_delegate_ = paint_delegate; + } + +#if defined(WEBKIT_HAS_WEB_AUTO_FILL_CLIENT) + host->webwidget_ = WebView::create(delegate, NULL); +#else + host->webwidget_ = WebView::create(delegate); +#endif + host->webview()->setDevToolsAgentClient(dev_tools_client); + host->webview()->setPermissionClient(delegate); + host->webview()->setPrerendererClient(delegate); + prefs.Apply(host->webview()); + host->webview()->initializeMainFrame(delegate); + host->webwidget_->resize(WebSize(content_rect.size.width, + content_rect.size.height)); + + return host; +} + +WebViewHost::~WebViewHost() { + BrowserWebView* webView = static_cast(view_); + webView.browser = NULL; +} + +WebView* WebViewHost::webview() const { + return static_cast(webwidget_); +} + +void WebViewHost::SetIsActive(bool active) { + webview()->setIsActive(active); +} + +void WebViewHost::MouseEvent(NSEvent* event) { + _Context->set_current_webviewhost(this); + WebWidgetHost::MouseEvent(event); +} + +void WebViewHost::KeyEvent(NSEvent *event) { + WebKeyboardEvent keyboard_event(WebInputEventFactory::keyboardEvent(event)); + if (delegate_->OnKeyboardEvent(keyboard_event, false)) + return; + + WebWidgetHost::KeyEvent(event); +} + +void WebViewHost::SetFocus(bool enable) { + if (enable) { + // Set the current WebViewHost in case a drag action is started before mouse + // events are detected for the window. + _Context->set_current_webviewhost(this); + } + WebWidgetHost::SetFocus(enable); +} diff --git a/cef1/libcef/webview_host_win.cc b/cef1/libcef/webview_host_win.cc new file mode 100644 index 000000000..a10629cb2 --- /dev/null +++ b/cef1/libcef/webview_host_win.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. + +#include "libcef/webview_host.h" +#include "libcef/browser_webview_delegate.h" +#include "libcef/cef_context.h" + +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/win/WebInputEventFactory.h" +#include "ui/base/win/hwnd_util.h" +#include "ui/gfx/rect.h" +#include "ui/gfx/size.h" +#include "webkit/glue/webpreferences.h" + +using WebKit::WebDevToolsAgentClient; +using WebKit::WebKeyboardEvent; +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebView; + +static const wchar_t kWindowClassName[] = L"WebViewHost"; + +/*static*/ +WebViewHost* WebViewHost::Create(HWND parent_view, + const gfx::Rect&, + BrowserWebViewDelegate* delegate, + PaintDelegate* paint_delegate, + WebDevToolsAgentClient* dev_tools_client, + const webkit_glue::WebPreferences& prefs) { + WebViewHost* host = new WebViewHost(delegate); + + if (!paint_delegate) { + static bool registered_class = false; + if (!registered_class) { + WNDCLASSEX wcex = {0}; + wcex.cbSize = sizeof(wcex); + wcex.style = CS_DBLCLKS; + wcex.lpfnWndProc = WebWidgetHost::WndProc; + wcex.hInstance = GetModuleHandle(NULL); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.lpszClassName = kWindowClassName; + RegisterClassEx(&wcex); + registered_class = true; + } + + host->view_ = CreateWindow(kWindowClassName, NULL, + WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 0, 0, + 0, 0, parent_view, NULL, + GetModuleHandle(NULL), NULL); + ui::SetWindowUserData(host->view_, host); + } else { + host->paint_delegate_ = paint_delegate; + } + +#if defined(WEBKIT_HAS_WEB_AUTO_FILL_CLIENT) + host->webwidget_ = WebView::create(delegate, NULL); +#else + host->webwidget_ = WebView::create(delegate); +#endif + host->webview()->setDevToolsAgentClient(dev_tools_client); + host->webview()->setPermissionClient(delegate); + host->webview()->setPrerendererClient(delegate); + prefs.Apply(host->webview()); + host->webview()->initializeMainFrame(delegate); + + return host; +} + +WebView* WebViewHost::webview() const { + return static_cast(webwidget_); +} + +bool WebViewHost::WndProc(UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_SETFOCUS: + // Set the current WebViewHost in case a drag action is started before mouse + // events are detected for the window. + _Context->set_current_webviewhost(this); + break; + } + return false; +} + +void WebViewHost::MouseEvent(UINT message, WPARAM wparam, LPARAM lparam) { + _Context->set_current_webviewhost(this); + WebWidgetHost::MouseEvent(message, wparam, lparam); +} + +void WebViewHost::KeyEvent(UINT message, WPARAM wparam, LPARAM lparam) { + // Give the client a chance to handle keyboard events before they're passed + // to WebKit. + const WebKeyboardEvent& event = WebInputEventFactory::keyboardEvent( + view_, message, wparam, lparam); + if (delegate_->OnKeyboardEvent(event, false)) + return; + + WebWidgetHost::KeyEvent(message, wparam, lparam); +} diff --git a/cef1/libcef/webwidget_host.cc b/cef1/libcef/webwidget_host.cc new file mode 100644 index 000000000..c1ae0be65 --- /dev/null +++ b/cef1/libcef/webwidget_host.cc @@ -0,0 +1,123 @@ +// 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/webwidget_host.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "base/message_loop.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebWidget.h" + +using webkit::npapi::WebPluginGeometry; +using WebKit::WebSize; + + +void WebWidgetHost::ScheduleComposite() { + if (has_invalidate_task_) + return; + + has_invalidate_task_ = true; + + // Try to paint at 60fps. + static int64 kDesiredRate = 16; + + base::TimeDelta delta = base::TimeTicks::Now() - paint_last_call_; + int64 actualRate = delta.InMilliseconds(); + if (actualRate >= kDesiredRate) { + // Can't keep up so run as fast as possible. + MessageLoop::current()->PostTask(FROM_HERE, + base::Bind(&WebWidgetHost::Invalidate, weak_factory_.GetWeakPtr())); + } else { + // Maintain the desired rate. + MessageLoop::current()->PostDelayedTask(FROM_HERE, + base::Bind(&WebWidgetHost::Invalidate, weak_factory_.GetWeakPtr()), + kDesiredRate - actualRate); + } +} + +void WebWidgetHost::ScheduleAnimation() { + ScheduleComposite(); +} + +void WebWidgetHost::UpdatePaintRect(const gfx::Rect& rect) { +#if defined(OS_WIN) || defined(OS_MACOSX) + paint_rgn_.op(rect.x(), rect.y(), rect.right(), rect.bottom(), + SkRegion::kUnion_Op); +#else + // TODO(cef): Update all ports to use regions instead of rectangles. + paint_rect_ = paint_rect_.Union(rect); +#endif +} + +void WebWidgetHost::UpdateRedrawRect(const gfx::Rect& rect) { + if (!view_) + redraw_rect_ = redraw_rect_.Union(rect); +} + +void WebWidgetHost::SetSize(int width, int height) { + webwidget_->resize(WebSize(width, height)); + DidInvalidateRect(gfx::Rect(0, 0, width, height)); + EnsureTooltip(); +} + +void WebWidgetHost::GetSize(int& width, int& height) { + const WebSize& size = webwidget_->size(); + width = size.width; + height = size.height; +} + +void WebWidgetHost::AddWindowedPlugin(gfx::PluginWindowHandle handle) { + WebPluginGeometry geometry; + plugin_map_.insert(std::make_pair(handle, geometry)); +} + +void WebWidgetHost::RemoveWindowedPlugin(gfx::PluginWindowHandle handle) { + PluginMap::iterator it = plugin_map_.find(handle); + DCHECK(it != plugin_map_.end()); + plugin_map_.erase(it); +} + +void WebWidgetHost::MoveWindowedPlugin(const WebPluginGeometry& move) { + PluginMap::iterator it = plugin_map_.find(move.window); + DCHECK(it != plugin_map_.end()); + + it->second.window = move.window; + if (move.rects_valid) { + it->second.window_rect = move.window_rect; + it->second.clip_rect = move.clip_rect; + it->second.cutout_rects = move.cutout_rects; + it->second.rects_valid = true; + } + it->second.visible = move.visible; +} + +gfx::PluginWindowHandle WebWidgetHost::GetWindowedPluginAt(int x, int y) { + if (!plugin_map_.empty()) { + PluginMap::const_iterator it = plugin_map_.begin(); + for (; it != plugin_map_.end(); ++it) { + if (it->second.visible && it->second.window_rect.Contains(x, y)) + return it->second.window; + } + } + + return gfx::kNullPluginWindow; +} + +void WebWidgetHost::DoPaint() { + if (MessageLoop::current()->IsIdle()) { + has_update_task_ = false; + // Paint to the delegate. +#if defined(OS_MACOSX) + SkRegion region; + Paint(region); +#else + Paint(); +#endif + } else { + // Try again later. + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&WebWidgetHost::DoPaint, weak_factory_.GetWeakPtr())); + } +} diff --git a/cef1/libcef/webwidget_host.h b/cef1/libcef/webwidget_host.h new file mode 100644 index 000000000..b5dfec428 --- /dev/null +++ b/cef1/libcef/webwidget_host.h @@ -0,0 +1,307 @@ +// 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. + +#ifndef CEF_LIBCEF_WEBWIDGET_HOST_H_ +#define CEF_LIBCEF_WEBWIDGET_HOST_H_ +#pragma once + +#include +#include + +#include "include/internal/cef_string.h" +#include "include/internal/cef_types.h" +#include "include/internal/cef_types_wrappers.h" + +#include "base/basictypes.h" +#include "base/memory/scoped_ptr.h" +#include "base/memory/weak_ptr.h" +#include "base/time.h" +#include "skia/ext/platform_canvas.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebTextInputType.h" +#include "third_party/skia/include/core/SkRegion.h" +#include "ui/gfx/native_widget_types.h" +#include "ui/gfx/rect.h" +#include "webkit/plugins/npapi/webplugin.h" + +#if defined(OS_WIN) +#include "ui/base/win/ime_input.h" +#endif + +#if defined(TOOLKIT_GTK) +#include // NOLINT(build/include_order) +#endif + +namespace gfx { +class Rect; +class Size; +} + +namespace WebKit { +class WebWidget; +class WebWidgetClient; +class WebKeyboardEvent; +struct WebScreenInfo; +} + +#if defined(OS_MACOSX) +#ifdef __OBJC__ +@class NSEvent; +#else +class NSEvent; +#endif +#endif + +// This class is a simple NativeView-based host for a WebWidget +class WebWidgetHost { + public: + class PaintDelegate { + public: + virtual ~PaintDelegate() {} + virtual void Paint(bool popup, const std::vector& dirtyRects, + const void* buffer) =0; + }; + + // The new instance is deleted once the associated NativeView is destroyed. + // The newly created window should be resized after it is created, using the + // MoveWindow (or equivalent) function. + static WebWidgetHost* Create(gfx::NativeView parent_view, + WebKit::WebWidgetClient* client, + PaintDelegate* paint_delegate); + + virtual ~WebWidgetHost(); + + gfx::NativeView view_handle() const { return view_; } + WebKit::WebWidget* webwidget() const { return webwidget_; } + + void DidInvalidateRect(const gfx::Rect& rect); + void DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect); + + // Called for accelerated content like WebGL. + void ScheduleComposite(); + + // Called for requestAnimationFrame animations. + void ScheduleAnimation(); + + // Invalidate the complete client area. This is called at a reasonable frame + // rate by the Schedule*() methods. + void Invalidate(); + +#if defined(OS_WIN) + void SetCursor(HCURSOR cursor); +#endif + + // Update the region that will be painted to the canvas by WebKit the next + // time that Paint() is called. + void UpdatePaintRect(const gfx::Rect& rect); + + // Update the region that will be drawn to the device the next time Paint() + // is called. This is only used when window rendering is disabled. + void UpdateRedrawRect(const gfx::Rect& rect); + +#if defined(OS_MACOSX) + void Paint(SkRegion& update_rgn); +#else + void Paint(); +#endif + void InvalidateRect(const gfx::Rect& rect); + + bool GetImage(int width, int height, void* buffer); + + void SetSize(int width, int height); + void GetSize(int& width, int& height); + + skia::PlatformCanvas* canvas() const { return canvas_.get(); } + + WebKit::WebScreenInfo GetScreenInfo(); + + WebKit::WebKeyboardEvent GetLastKeyEvent() const { return last_key_event_; } + + void PaintRect(const gfx::Rect& rect); + + void SetTooltipText(const CefString& tooltip_text); + + void SendKeyEvent(cef_key_type_t type, const cef_key_info_t& keyInfo, + int modifiers); + void SendMouseClickEvent(int x, int y, cef_mouse_button_type_t type, + bool mouseUp, int clickCount); + void SendMouseMoveEvent(int x, int y, bool mouseLeave); + void SendMouseWheelEvent(int x, int y, int deltaX, int deltaY); + void SendFocusEvent(bool setFocus); + void SendCaptureLostEvent(); + + // Manage windowed plugins when window rendering is disabled. + bool HasWindowedPlugins() { return !plugin_map_.empty(); } + void AddWindowedPlugin(gfx::PluginWindowHandle handle); + void RemoveWindowedPlugin(gfx::PluginWindowHandle handle); + void MoveWindowedPlugin(const webkit::npapi::WebPluginGeometry& geometry); + gfx::PluginWindowHandle GetWindowedPluginAt(int x, int y); + + // If window rendering is disabled paint messages are generated after all + // other pending messages have been processed. + void DoPaint(); + + void set_popup(bool popup) { popup_ = popup; } + bool popup() { return popup_; } + + PaintDelegate* paint_delegate() { return paint_delegate_; } + + protected: + WebWidgetHost(); + +#if defined(OS_WIN) + // Per-class wndproc. Returns true if the event should be swallowed. + virtual bool WndProc(UINT message, WPARAM wparam, LPARAM lparam); + + void Resize(LPARAM lparam); + virtual void MouseEvent(UINT message, WPARAM wparam, LPARAM lparam); + void WheelEvent(WPARAM wparam, LPARAM lparam); + virtual void KeyEvent(UINT message, WPARAM wparam, LPARAM lparam); + void CaptureLostEvent(); + void SetFocus(bool enable); + void OnNotify(WPARAM wparam, NMHDR* header); + + static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); + LRESULT OnImeSetContext(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + LRESULT OnImeStartComposition(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + LRESULT OnImeComposition(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + LRESULT OnImeEndComposition(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + void OnInputLangChange(DWORD character_set, HKL input_language_id); + void ImeUpdateTextInputState(WebKit::WebTextInputType type, + const gfx::Rect& caret_rect); + void UpdateInputMethod(); +#elif defined(OS_MACOSX) + // These need to be called from a non-subclass, so they need to be public. + public: + void Resize(const gfx::Rect& rect); + virtual void MouseEvent(NSEvent* event); + void WheelEvent(NSEvent* event); + virtual void KeyEvent(NSEvent* event); + virtual void SetFocus(bool enable); + + protected: +#elif defined(TOOLKIT_GTK) + + public: + // --------------------------------------------------------------------------- + // This is needed on Linux because the GtkWidget creation is the same between + // both web view hosts and web widget hosts. The Windows code manages this by + // reusing the WndProc function (static, above). However, GTK doesn't use a + // single big callback function like that so we have a static function that + // sets up a GtkWidget correctly. + // parent: a GtkBox to pack the new widget at the end of + // host: a pointer to a WebWidgetHost (or subclass thereof) + // --------------------------------------------------------------------------- + static gfx::NativeView CreateWidget(gfx::NativeView parent_view, + WebWidgetHost* host); + void Resize(const gfx::Size& size); + virtual void KeyEvent(GdkEventKey* event); +#endif + +#if defined(OS_WIN) + void TrackMouseLeave(bool enable); +#endif + + void set_painting(bool value) { + painting_ = value; + } + + void EnsureTooltip(); + void ResetTooltip(); + + gfx::NativeView view_; + + // The paint delegate is used instead of the view when window rendering is + // disabled. + PaintDelegate* paint_delegate_; + + WebKit::WebWidget* webwidget_; + scoped_ptr canvas_; + int canvas_w_; + int canvas_h_; + + // True if this widget is a popup widget. + bool popup_; + + // Specifies the portion of the webwidget that needs painting. + // TODO(cef): Update the Linux port to use regions instead of rectangles. +#if defined(OS_WIN) || defined(OS_MACOSX) + SkRegion paint_rgn_; +#else + gfx::Rect paint_rect_; +#endif + + // True if an update task is pending when window rendering is disabled. + bool has_update_task_; + + // True if an invalidate task is pending due to the Schedule*() methods. + bool has_invalidate_task_; + +#if defined(OS_WIN) + // True if an update input method task is pending due to DidInvalidateRect(). + bool has_update_input_method_task_; +#endif + + // When the Paint() method last completed. + base::TimeTicks paint_last_call_; + + // Redraw rectangle requested by an explicit call to CefBrowser::Invalidate(). + gfx::Rect redraw_rect_; + + // The map of windowed plugins that need to be drawn when window rendering is + // disabled. + typedef std::map + PluginMap; + PluginMap plugin_map_; + +#if defined(OS_WIN) + bool track_mouse_leave_; + std::wstring tooltip_text_; + gfx::NativeView tooltip_view_; + bool tooltip_showing_; + + // Wrapper class for IME input. + ui::ImeInput ime_input_; + + // Represents whether or not this browser process is receiving status + // messages about the focused edit control from a renderer process. + bool ime_notification_; + + // Represents whether or not the IME of a browser process is active. + bool input_method_is_active_; + + // Stores the current text input type received by ImeUpdateTextInputState() + // method. + WebKit::WebTextInputType text_input_type_; + + // Stores the current caret bounds of input focus. + WebKit::WebRect caret_bounds_; +#endif + +#if defined(OS_MACOSX) + int mouse_modifiers_; + WebKit::WebMouseEvent::Button mouse_button_down_; +#endif + +#if defined(TOOLKIT_GTK) + // Since GtkWindow resize is asynchronous, we have to stash the dimensions, + // so that the backing store doesn't have to wait for sizing to take place. + gfx::Size logical_size_; +#endif + + WebKit::WebKeyboardEvent last_key_event_; + + bool painting_; + bool layouting_; + + private: + base::WeakPtrFactory weak_factory_; +}; + +#endif // CEF_LIBCEF_WEBWIDGET_HOST_H_ diff --git a/cef1/libcef/webwidget_host_gtk.cc b/cef1/libcef/webwidget_host_gtk.cc new file mode 100644 index 000000000..38b1658b9 --- /dev/null +++ b/cef1/libcef/webwidget_host_gtk.cc @@ -0,0 +1,499 @@ +// 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. + +#include "libcef/webwidget_host.h" + +#include +#include +#include + +#include "base/basictypes.h" +#include "base/logging.h" +#include "skia/ext/bitmap_platform_device.h" +#include "skia/ext/platform_canvas.h" +#include "skia/ext/platform_device.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/gtk/WebInputEventFactory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/x11/WebScreenInfoFactory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenu.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" + +using WebKit::WebInputEventFactory; +using WebKit::WebKeyboardEvent; +using WebKit::WebMouseEvent; +using WebKit::WebMouseWheelEvent; +using WebKit::WebPopupMenu; +using WebKit::WebScreenInfo; +using WebKit::WebScreenInfoFactory; +using WebKit::WebSize; +using WebKit::WebWidgetClient; + +namespace { + +// Used to store a backpointer to WebWidgetHost from our GtkWidget. +const char kWebWidgetHostKey[] = "webwidgethost"; + +// In response to an invalidation, we call into WebKit to do layout. On +// Windows, WM_PAINT is a virtual message so any extra invalidates that come up +// while it's doing layout are implicitly swallowed as soon as we actually do +// drawing via BeginPaint. +// +// Though GTK does know how to collapse multiple paint requests, it won't erase +// paint requests from the future when we start drawing. To avoid an infinite +// cycle of repaints, we track whether we're currently handling a redraw, and +// during that if we get told by WebKit that a region has become invalid, we +// still add that region to the local dirty rect but *don't* enqueue yet +// another "do a paint" message. +bool g_handling_expose = false; + +// ----------------------------------------------------------------------------- +// Callback functions to proxy to host... + +// The web contents are completely drawn and handled by WebKit, except that +// windowed plugins are GtkSockets on top of it. We need to place the +// GtkSockets inside a GtkContainer. We use a GtkFixed container, and the +// GtkSocket objects override a little bit to manage their size (see the code +// in webplugin_delegate_impl_gtk.cc). We listen on a the events we're +// interested in and forward them on to the WebWidgetHost. This class is a +// collection of static methods, implementing the widget related code. +class WebWidgetHostGtkWidget { + public: + // This will create a new widget used for hosting the web contents. We use + // our GtkDrawingAreaContainer here, for the reasons mentioned above. + static GtkWidget* CreateNewWidget(GtkWidget* parent_view, + WebWidgetHost* host) { + GtkWidget* widget = gtk_fixed_new(); + gtk_fixed_set_has_window(GTK_FIXED(widget), true); + + gtk_box_pack_start(GTK_BOX(parent_view), widget, TRUE, TRUE, 0); + + gtk_widget_add_events(widget, GDK_EXPOSURE_MASK | + GDK_POINTER_MOTION_MASK | + GDK_BUTTON_PRESS_MASK | + GDK_BUTTON_RELEASE_MASK | + GDK_KEY_PRESS_MASK | + GDK_KEY_RELEASE_MASK); + gtk_widget_set_can_focus(widget, TRUE); + g_signal_connect(widget, "size-request", + G_CALLBACK(&HandleSizeRequest), host); + g_signal_connect(widget, "size-allocate", + G_CALLBACK(&HandleSizeAllocate), host); + g_signal_connect(widget, "configure-event", + G_CALLBACK(&HandleConfigure), host); + g_signal_connect(widget, "expose-event", + G_CALLBACK(&HandleExpose), host); + g_signal_connect(widget, "key-press-event", + G_CALLBACK(&HandleKeyPress), host); + g_signal_connect(widget, "key-release-event", + G_CALLBACK(&HandleKeyRelease), host); + g_signal_connect(widget, "focus", + G_CALLBACK(&HandleFocus), host); + g_signal_connect(widget, "focus-in-event", + G_CALLBACK(&HandleFocusIn), host); + g_signal_connect(widget, "focus-out-event", + G_CALLBACK(&HandleFocusOut), host); + g_signal_connect(widget, "button-press-event", + G_CALLBACK(&HandleButtonPress), host); + g_signal_connect(widget, "button-release-event", + G_CALLBACK(&HandleButtonRelease), host); + g_signal_connect(widget, "motion-notify-event", + G_CALLBACK(&HandleMotionNotify), host); + g_signal_connect(widget, "scroll-event", + G_CALLBACK(&HandleScroll), host); + + g_object_set_data(G_OBJECT(widget), kWebWidgetHostKey, host); + return widget; + } + + private: + // Our size was requested. We let the GtkFixed do its normal calculation, + // after which this callback is called. The GtkFixed will come up with a + // requisition based on its children, which include plugin windows. Since + // we don't want to prevent resizing smaller than a plugin window, we need to + // control the size ourself. + static void HandleSizeRequest(GtkWidget* widget, + GtkRequisition* req, + WebWidgetHost* host) { + // This is arbitrary, but the WebKit scrollbars try to shrink themselves + // if the browser window is too small. Give them some space. + static const int kMinWidthHeight = 64; + + req->width = kMinWidthHeight; + req->height = kMinWidthHeight; + } + + // Our size has changed. + static void HandleSizeAllocate(GtkWidget* widget, + GtkAllocation* allocation, + WebWidgetHost* host) { + host->Resize(WebSize(allocation->width, allocation->height)); + } + + // Size, position, or stacking of the GdkWindow changed. + static gboolean HandleConfigure(GtkWidget* widget, + GdkEventConfigure* config, + WebWidgetHost* host) { + host->Resize(WebSize(config->width, config->height)); + return FALSE; + } + + // A portion of the GdkWindow needs to be redraw. + static gboolean HandleExpose(GtkWidget* widget, + GdkEventExpose* expose, + WebWidgetHost* host) { + // See comments above about what g_handling_expose is for. + g_handling_expose = true; + gfx::Rect rect(expose->area); + host->UpdatePaintRect(rect); + host->Paint(); + g_handling_expose = false; + return FALSE; + } + + // Keyboard key pressed. + static gboolean HandleKeyPress(GtkWidget* widget, + GdkEventKey* event, + WebWidgetHost* host) { + host->KeyEvent(event); + return FALSE; + } + + // Keyboard key released. + static gboolean HandleKeyRelease(GtkWidget* widget, + GdkEventKey* event, + WebWidgetHost* host) { + return HandleKeyPress(widget, event, host); + } + + // This signal is called when arrow keys or tab is pressed. If we return + // true, we prevent focus from being moved to another widget. If we want to + // allow focus to be moved outside of web contents, we need to implement + // WebViewDelegate::TakeFocus in the test webview delegate. + static gboolean HandleFocus(GtkWidget* widget, + GdkEventFocus* focus, + WebWidgetHost* host) { + return TRUE; + } + + // Keyboard focus entered. + static gboolean HandleFocusIn(GtkWidget* widget, + GdkEventFocus* focus, + WebWidgetHost* host) { + host->webwidget()->setFocus(true); + return TRUE; + } + + // Keyboard focus left. + static gboolean HandleFocusOut(GtkWidget* widget, + GdkEventFocus* focus, + WebWidgetHost* host) { + host->webwidget()->setFocus(false); + return TRUE; + } + + // Mouse button down. + static gboolean HandleButtonPress(GtkWidget* widget, + GdkEventButton* event, + WebWidgetHost* host) { + if (!(event->button == 1 || event->button == 2 || event->button == 3)) + return FALSE; // We do not forward any other buttons to the renderer. + if (event->type == GDK_2BUTTON_PRESS || event->type == GDK_3BUTTON_PRESS) + return FALSE; + + gtk_widget_grab_focus(widget); + + host->webwidget()->handleInputEvent( + WebInputEventFactory::mouseEvent(event)); + return FALSE; + } + + // Mouse button up. + static gboolean HandleButtonRelease(GtkWidget* widget, + GdkEventButton* event, + WebWidgetHost* host) { + return HandleButtonPress(widget, event, host); + } + + // Mouse pointer movements. + static gboolean HandleMotionNotify(GtkWidget* widget, + GdkEventMotion* event, + WebWidgetHost* host) { + host->webwidget()->handleInputEvent( + WebInputEventFactory::mouseEvent(event)); + return FALSE; + } + + // Mouse scroll wheel. + static gboolean HandleScroll(GtkWidget* widget, + GdkEventScroll* event, + WebWidgetHost* host) { + host->webwidget()->handleInputEvent( + WebInputEventFactory::mouseWheelEvent(event)); + return FALSE; + } + + DISALLOW_IMPLICIT_CONSTRUCTORS(WebWidgetHostGtkWidget); +}; + +// Return an Xlib Display pointer for the given widget. +Display* GtkWidgetGetDisplay(GtkWidget* widget) { + GdkDisplay* gdk_display = gtk_widget_get_display(widget); + return gdk_x11_display_get_xdisplay(gdk_display); +} + +// Return the screen number for the given widget. +int GtkWidgetGetScreenNum(GtkWidget* widget) { + GdkDisplay* gdk_display = gtk_widget_get_display(widget); + GdkScreen* gdk_screen = gdk_display_get_default_screen(gdk_display); + return gdk_x11_screen_get_screen_number(gdk_screen); +} + +} // namespace + +// This is provided so that the webview can reuse the custom GTK window code. +// static +gfx::NativeView WebWidgetHost::CreateWidget( + gfx::NativeView parent_view, WebWidgetHost* host) { + return WebWidgetHostGtkWidget::CreateNewWidget(parent_view, host); +} + +// static +WebWidgetHost* WebWidgetHost::Create(GtkWidget* parent_view, + WebWidgetClient* client, + PaintDelegate* paint_delegate) { + WebWidgetHost* host = new WebWidgetHost(); + host->view_ = CreateWidget(parent_view, host); + host->webwidget_ = WebPopupMenu::create(client); + // We manage our own double buffering because we need to be able to update + // the expose area in an ExposeEvent within the lifetime of the event handler. + gtk_widget_set_double_buffered(GTK_WIDGET(host->view_), false); + + return host; +} + +void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) { + DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting"; + + UpdatePaintRect(damaged_rect); + + if (!g_handling_expose) { + gtk_widget_queue_draw_area(GTK_WIDGET(view_), damaged_rect.x(), + damaged_rect.y(), damaged_rect.width(), damaged_rect.height()); + } +} + +void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { + // This is used for optimizing painting when the renderer is scrolled. We're + // currently not doing any optimizations so just invalidate the region. + DidInvalidateRect(clip_rect); +} + +void WebWidgetHost::Invalidate() { + int width = logical_size_.width(); + int height = logical_size_.height(); + GdkRectangle grect = { + 0, + 0, + width, + height + }; + GdkWindow* window = view_->window; + gdk_window_invalidate_rect(window, &grect, 0); +} + +WebWidgetHost::WebWidgetHost() + : view_(NULL), + paint_delegate_(NULL), + webwidget_(NULL), + canvas_w_(0), + canvas_h_(0), + popup_(false), + has_update_task_(false), + has_invalidate_task_(false), + ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) { + set_painting(false); +} + +WebWidgetHost::~WebWidgetHost() { + // We may be deleted before the view_. Clear out the signals so that we don't + // attempt to invoke something on a deleted object. + g_object_set_data(G_OBJECT(view_), kWebWidgetHostKey, NULL); + g_signal_handlers_disconnect_matched(view_, + G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, this); + // TODO(port): Figure out why we can't do this without crashing. + // webwidget_->close(); +} + +void WebWidgetHost::Resize(const gfx::Size &newsize) { + logical_size_ = newsize; + SetSize(newsize.width(), newsize.height()); +} + +void WebWidgetHost::Paint() { + int width = logical_size_.width(); + int height = logical_size_.height(); + gfx::Rect client_rect(width, height); + + // Number of pixels that the canvas is allowed to differ from the client area. + const int kCanvasGrowSize = 128; + + if (!canvas_.get() || + canvas_w_ < client_rect.width() || + canvas_h_ < client_rect.height() || + canvas_w_ > client_rect.width() + kCanvasGrowSize * 2 || + canvas_h_ > client_rect.height() + kCanvasGrowSize * 2) { + paint_rect_ = client_rect; + + // Resize the canvas to be within a reasonable size of the client area. + canvas_w_ = client_rect.width() + kCanvasGrowSize; + canvas_h_ = client_rect.height() + kCanvasGrowSize; + canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true)); + if (!canvas_.get()) { + // memory allocation failed, we can't paint. + LOG(ERROR) << "Failed to allocate memory for " << width << "x" << height; + return; + } + } + + webwidget_->animate(0.0); + + // This may result in more invalidation + webwidget_->layout(); + + // Paint the canvas if necessary. Allow painting to generate extra rects the + // first time we call it. This is necessary because some WebCore rendering + // objects update their layout only when painted. + // Store the total area painted in total_paint. Then tell the gdk window + // to update that area after we're done painting it. + gfx::Rect total_paint; + for (int i = 0; i < 2; ++i) { + paint_rect_ = client_rect.Intersect(paint_rect_); + if (!paint_rect_.IsEmpty()) { + gfx::Rect rect(paint_rect_); + paint_rect_ = gfx::Rect(); + + DLOG_IF(WARNING, i == 1) << "painting caused additional invalidations"; + PaintRect(rect); + total_paint = total_paint.Union(rect); + } + } + // DCHECK(paint_rect_.IsEmpty()); + + // Invalidate the paint region on the widget's underlying gdk window. Note + // that gdk_window_invalidate_* will generate extra expose events, which + // we wish to avoid. So instead we use calls to begin_paint/end_paint. + GdkRectangle grect = { + total_paint.x(), + total_paint.y(), + total_paint.width(), + total_paint.height(), + }; + GdkWindow* window = view_->window; + gdk_window_begin_paint_rect(window, &grect); + + // BitBlit to the gdk window. + skia::ScopedPlatformPaint scoped_platform_paint(canvas_.get()); + cairo_t* source_surface = scoped_platform_paint.GetPlatformSurface(); + cairo_t* cairo_drawable = gdk_cairo_create(window); + cairo_set_source_surface(cairo_drawable, cairo_get_target(source_surface), + 0, 0); + cairo_paint(cairo_drawable); + cairo_destroy(cairo_drawable); + + gdk_window_end_paint(window); + + // Used with scheduled invalidation to maintain a consistent frame rate. + paint_last_call_ = base::TimeTicks::Now(); + if (has_invalidate_task_) + has_invalidate_task_ = false; +} + +void WebWidgetHost::SetTooltipText(const CefString& tooltip_text) { + // TODO(port): Implement this method as part of tooltip support. +} + +void WebWidgetHost::InvalidateRect(const gfx::Rect& rect) { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +bool WebWidgetHost::GetImage(int width, int height, void* rgba_buffer) { + if (!canvas_.get()) + return false; + + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); + return false; +} + +WebScreenInfo WebWidgetHost::GetScreenInfo() { + Display* display = GtkWidgetGetDisplay(view_); + int screen_num = GtkWidgetGetScreenNum(view_); + return WebScreenInfoFactory::screenInfo(display, screen_num); +} + +void WebWidgetHost::PaintRect(const gfx::Rect& rect) { + set_painting(true); + webwidget_->paint(canvas_.get(), rect); + set_painting(false); +} + +void WebWidgetHost::SendKeyEvent(cef_key_type_t type, + const cef_key_info_t& keyInfo, + int modifiers) { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +void WebWidgetHost::SendMouseClickEvent(int x, int y, + cef_mouse_button_type_t type, + bool mouseUp, int clickCount) { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave) { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +void WebWidgetHost::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +void WebWidgetHost::SendFocusEvent(bool setFocus) { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +void WebWidgetHost::SendCaptureLostEvent() { + // TODO(port): Implement this method as part of off-screen rendering support. + NOTIMPLEMENTED(); +} + +void WebWidgetHost::EnsureTooltip() { + // TODO(port): Implement this method as part of tooltip support. +} + +void WebWidgetHost::ResetTooltip() { + // TODO(port): Implement this method as part of tooltip support. +} + +void WebWidgetHost::KeyEvent(GdkEventKey* event) { + WebKeyboardEvent keyboard_event(WebInputEventFactory::keyboardEvent(event)); + last_key_event_ = keyboard_event; + webwidget()->handleInputEvent(keyboard_event); + + // In the browser we do a ton of work with IMEs. This is some minimal + // code to make basic text work in test_shell, but doesn't cover IME. + // This is a copy of the logic in ProcessUnfilteredKeyPressEvent in + // render_widget_host_view_gtk.cc . + if (event->type == GDK_KEY_PRESS && keyboard_event.text[0]) { + keyboard_event.type = WebKit::WebInputEvent::Char; + last_key_event_ = keyboard_event; + webwidget()->handleInputEvent(keyboard_event); + } +} diff --git a/cef1/libcef/webwidget_host_mac.mm b/cef1/libcef/webwidget_host_mac.mm new file mode 100644 index 000000000..4de7cf7dd --- /dev/null +++ b/cef1/libcef/webwidget_host_mac.mm @@ -0,0 +1,682 @@ +// Copyright (c) 2008-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. + +#import + +#include "base/compiler_specific.h" +#include "third_party/WebKit/Source/WebCore/config.h" +MSVC_PUSH_WARNING_LEVEL(0); +#include "KeyEventCocoa.h" // NOLINT(build/include) +MSVC_POP_WARNING(); + +#undef LOG +#import "libcef/webwidget_host.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#import "base/logging.h" +#import "skia/ext/platform_canvas.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebInputEventFactory.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/mac/WebScreenInfoFactory.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenu.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#import "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#import "third_party/skia/include/core/SkRegion.h" +#import "ui/gfx/rect.h" +#import "ui/gfx/size.h" +#import "webkit/glue/webkit_glue.h" + +using webkit::npapi::WebPluginGeometry; +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebKeyboardEvent; +using WebKit::WebMouseEvent; +using WebKit::WebMouseWheelEvent; +using WebKit::WebPopupMenu; +using WebKit::WebScreenInfo; +using WebKit::WebScreenInfoFactory; +using WebKit::WebSize; +using WebKit::WebWidgetClient; + +namespace { + +inline SkIRect convertToSkiaRect(const gfx::Rect& r) { + return SkIRect::MakeLTRB(r.x(), r.y(), r.right(), r.bottom()); +} + +inline gfx::Rect convertFromSkiaRect(const SkIRect& r) { + return gfx::Rect(r.x(), r.y(), r.width(), r.height()); +} + +} // namespace + +/*static*/ +WebWidgetHost* WebWidgetHost::Create(NSView* parent_view, + WebWidgetClient* client, + PaintDelegate* paint_delegate) { + WebWidgetHost* host = new WebWidgetHost(); + + if (!paint_delegate) { + const NSRect bounds = [parent_view bounds]; + host->view_ = [[NSView alloc] initWithFrame:bounds]; + [parent_view addSubview:host->view_]; + + host->webwidget_ = WebPopupMenu::create(client); + host->webwidget_->resize(WebSize(NSWidth(bounds), NSHeight(bounds))); + } else { + host->paint_delegate_ = paint_delegate; + host->view_ = nil; + host->webwidget_ = WebPopupMenu::create(client); + } + + return host; +} + +WebWidgetHost::WebWidgetHost() + : view_(NULL), + paint_delegate_(NULL), + webwidget_(NULL), + canvas_w_(0), + canvas_h_(0), + popup_(false), + has_update_task_(false), + has_invalidate_task_(false), + mouse_modifiers_(0), + painting_(false), + layouting_(false), + ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) { + set_painting(false); +} + +WebWidgetHost::~WebWidgetHost() { +} + +void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) { + int width, height; + GetSize(width, height); + const gfx::Rect client_rect(width, height); + + const gfx::Rect damaged_rect_in_client = client_rect.Intersect(damaged_rect); + + if (!damaged_rect_in_client.IsEmpty()) { + UpdatePaintRect(damaged_rect_in_client); + + if (view_) { + NSRect cocoa_rect = NSRectFromCGRect(damaged_rect_in_client.ToCGRect()); + cocoa_rect.origin.y = client_rect.height() - NSMaxY(cocoa_rect); + [view_ setNeedsDisplayInRect:cocoa_rect]; + } else { + // Don't post a paint task if this invalidation occurred during layout or + // if a paint task is already pending. Paint() will be called by + // DoPaint(). + if (!layouting_ && !has_update_task_) { + has_update_task_ = true; + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&WebWidgetHost::DoPaint, weak_factory_.GetWeakPtr())); + } + } + } +} + +void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { + DCHECK(dx || dy); + + int width, height; + GetSize(width, height); + const gfx::Rect client_rect(width, height); + gfx::Rect rect = clip_rect.Intersect(client_rect); + + const int x = rect.x(); + const int y = rect.y(); + const int r = rect.right(); + const int b = rect.bottom(); + const int w = rect.width(); + const int h = rect.height(); + const int Dx = ABS(dx); + const int Dy = ABS(dy); + + // If we're in a state right now where we cannot draw into the view then just + // mark the scrolling rect as dirty and it will be completely redrawn instead. + // The Paint() method can end up calling this method indirectly if the view + // needs to be laid out; calling scrollRect:by: in this situation leads to + // unwanted behavior. Finally, scrolling the rectangle by more than the size + // of the view means we can just invalidate the entire scroll rect. + if (!view_ || [view_ canDraw] || painting_ || layouting_ || Dx >= w || + Dy >= h) { + DidInvalidateRect(clip_rect); + return; + } + + // The scrolling rect must not scroll outside the clip rect because that will + // clobber the scrollbars. As a result we shorten the rectangle a bit from the + // leading side of the scroll (could be either horizontally or vertically). + rect = gfx::Rect(dx>=0? x: x + Dx, dy>=0? y: y + Dy, w - Dx, h - Dy); + + // Convert the scroll rectangle to the view's coordinate system and perform + // the scroll directly without invalidating the view. In theory this could + // cause some kind of performance issue since we're not coalescing redraw + // events. In practice, however, we get much smoother scrolling of big views + // since just copying the pixels within the window is much faster than + // redrawing them. + NSRect cocoa_rect = NSRectFromCGRect(rect.ToCGRect()); + cocoa_rect.origin.y = client_rect.height() - NSMaxY(cocoa_rect); + [view_ scrollRect:cocoa_rect by:NSMakeSize(dx, -dy)]; + + // Repaint the rectangle that was revealed when scrolling the given rectangle. + // The invalidated area will be painted before the view contents are flushed + // to the screen buffer. + rect = gfx::Rect(dx>=0? x: r - Dx, dy>=0? y: b - Dy, + dx>0? Dx: w, dy>0? Dy: h); + DidInvalidateRect(rect); + + // If any part of the scrolled rect was marked as dirty make sure to redraw + // it in the new scrolled-to location. Otherwise we can end up with artifacts + // for overlapping elements. If there are multiple dirty regions in the scroll + // rect the rectangle union of those regions will be redrawn. + SkRegion moved_paint_rgn(paint_rgn_); + moved_paint_rgn.translate(dx, dy); + moved_paint_rgn.op(convertToSkiaRect(client_rect), SkRegion::kIntersect_Op); + DidInvalidateRect(convertFromSkiaRect(moved_paint_rgn.getBounds())); +} + +void WebWidgetHost::Paint(SkRegion& update_rgn) { + int width, height; + GetSize(width, height); + gfx::Rect client_rect(width, height); + + SkRegion damaged_rgn; + if (!view_ && !redraw_rect_.IsEmpty()) { + // At a minimum we need to send the delegate the rectangle that was + // requested by calling CefBrowser::InvalidateRect(). + damaged_rgn.setRect(convertToSkiaRect(redraw_rect_)); + redraw_rect_ = gfx::Rect(); + } + + if (view_) { + // Union the rectangle that WebKit think needs repainting with the rectangle + // of the view that must be painted now. In most situations this will not + // affect the painted rectangle. In some situations we could end up re- + // painting areas that are already in the canvas and only dirty in the view + // itself. However, if we don't do this we can get artifacts when scrolling + // because contents of the canvas are no longer correct after scrolling only + // in the view. + paint_rgn_.op(update_rgn, SkRegion::kUnion_Op); + + // When we are not using accelerated compositing the canvas area is allowed + // to differ in size from the client by a certain number of pixels (128 in + // this case). When accelerated compositing is in effect the size must match + // exactly. + const int extra_w = (webwidget_->isAcceleratedCompositingActive()? 0: 128); + const int extra_h = (webwidget_->isAcceleratedCompositingActive()? 0: 128); + const int min_w = client_rect.width(); + const int min_h = client_rect.height(); + const int max_w = client_rect.width() + extra_w * 2; + const int max_h = client_rect.height() + extra_h * 2; + + const bool too_small = (canvas_w_ < min_w || canvas_h_ < min_h); + const bool too_large = (canvas_w_ > max_w || canvas_h_ > max_h); + + if (!canvas_.get() || too_small || too_large) { + canvas_w_ = client_rect.width() + extra_w; + canvas_h_ = client_rect.height() + extra_h; + canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true)); + paint_rgn_.setRect(convertToSkiaRect(client_rect)); + } + } else if (!canvas_.get() || canvas_w_ != client_rect.width() || + canvas_h_ != client_rect.height()) { + paint_rgn_.setRect(convertToSkiaRect(client_rect)); + + // The canvas must be the exact size of the client area. + canvas_w_ = client_rect.width(); + canvas_h_ = client_rect.height(); + canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true)); + } + + webwidget_->animate(0.0); + + // Layout any views that have not been laid out yet. The layout may result in + // more invalidation. Keep track of the fact that we are laying out views, + // because this will sometimes cause ScrollRect to be called and we don't want + // to try to scrollRect:by: then. + layouting_ = true; + webwidget_->layout(); + layouting_ = false; + + // Draw into the graphics context of the canvas instead of the view's context. + // The view's context is pushed onto the context stack to be restored below. + CGContextRef bitmap = skia::GetBitmapContext(skia::GetTopDevice(*canvas_)); + NSGraphicsContext* paint_context = + [NSGraphicsContext graphicsContextWithGraphicsPort:bitmap flipped:YES]; + [NSGraphicsContext saveGraphicsState]; + [NSGraphicsContext setCurrentContext:paint_context]; + + // Paint the canvas if necessary. The painting operation can cause additional + // regions to be invalidated because some elements are laid out the first time + // they are painted. + while (!paint_rgn_.isEmpty()) { + SkRegion draw_rgn; + draw_rgn.swap(paint_rgn_); + + SkRegion::Cliperator iterator(draw_rgn, convertToSkiaRect(client_rect)); + for (; !iterator.done(); iterator.next()) { + const SkIRect& r = iterator.rect(); + PaintRect(convertFromSkiaRect(r)); + + if (!view_) + damaged_rgn.op(r, SkRegion::kUnion_Op); + } + + if (view_) { + // If any more rectangles were made dirty during the paint operation, make + // sure they are copied to the window buffer, by including the paint + // region. If nothing needs additional painting, this is a no-op. + update_rgn.op(paint_rgn_, SkRegion::kUnion_Op); + } + } + + if (!view_ && plugin_map_.size() > 0) { + // Flash seems to stop calling NPN_InvalidateRect, which means we stop + // painting. If we've got a plugin make sure we paint its rect each time. + + PluginMap::const_iterator it = plugin_map_.begin(); + for (; it != plugin_map_.end(); ++it) { + if (it->second.visible && + client_rect.Intersects(it->second.window_rect)) { + const WebPluginGeometry* geom = &it->second; + damaged_rgn.op(convertToSkiaRect(geom->window_rect), + SkRegion::kUnion_Op); + } + } + } + + if (view_) { + // Set the context back to our view and copy the bitmap that we just painted + // into to the view. Only the regions that were updated are copied. + [NSGraphicsContext restoreGraphicsState]; + NSGraphicsContext* view_context = [NSGraphicsContext currentContext]; + CGContextRef context = + static_cast([view_context graphicsPort]); + + SkRegion::Cliperator iterator(update_rgn, convertToSkiaRect(client_rect)); + for (; !iterator.done(); iterator.next()) { + const SkIRect& r = iterator.rect(); + CGRect copy_rect = { { r.x(), r.y() }, { r.width(), r.height() } }; + const float x = r.x(); + const float y = client_rect.height() - r.bottom(); + skia::DrawToNativeContext(canvas_.get(), context, x, y, ©_rect); + } + } else { + // Paint to the delegate. + DCHECK(paint_delegate_); + const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false); + DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config); + const void* pixels = bitmap.getPixels(); + + std::vector damaged_rects; + SkRegion::Cliperator iterator(damaged_rgn, convertToSkiaRect(client_rect)); + for (; !iterator.done(); iterator.next()) { + const SkIRect& r = iterator.rect(); + damaged_rects.push_back( + CefRect(r.left(), r.top(), r.width(), r.height())); + } + + paint_delegate_->Paint(popup_, damaged_rects, pixels); + } + + // Used with scheduled invalidation to maintain a consistent frame rate. + paint_last_call_ = base::TimeTicks::Now(); + if (has_invalidate_task_) + has_invalidate_task_ = false; +} + +void WebWidgetHost::Invalidate() { + if (view_) { + [view_ setNeedsDisplay:YES]; + } else if (webwidget_) { + WebSize size = webwidget_->size(); + InvalidateRect(gfx::Rect(0, 0, size.width, size.height)); + } +} + +void WebWidgetHost::SetTooltipText(const CefString& tooltip_text) { + // TODO(port): Implement this method as part of tooltip support. +} + +void WebWidgetHost::InvalidateRect(const gfx::Rect& rect) { + if (rect.IsEmpty()) + return; + + if (!view_) { + // Don't post a paint task if this invalidation occurred during layout or if + // a paint task is already pending. Paint() will be called by DoPaint(). + if (!layouting_ && !has_update_task_) { + has_update_task_ = true; + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&WebWidgetHost::DoPaint, weak_factory_.GetWeakPtr())); + } + } else { + NOTIMPLEMENTED(); + } +} + +bool WebWidgetHost::GetImage(int width, int height, void* rgba_buffer) { + if (!canvas_.get()) + return false; + + const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false); + DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config); + + if (width == canvas_->getDevice()->width() && + height == canvas_->getDevice()->height()) { + // The specified width and height values are the same as the canvas size. + // Return the existing canvas contents. + const void* pixels = bitmap.getPixels(); + memcpy(rgba_buffer, pixels, width * height * 4); + return true; + } + + // Create a new canvas of the requested size. + scoped_ptr new_canvas( + new skia::PlatformCanvas(width, height, true)); + + new_canvas->writePixels(bitmap, 0, 0); + const SkBitmap& new_bitmap = new_canvas->getDevice()->accessBitmap(false); + DCHECK(new_bitmap.config() == SkBitmap::kARGB_8888_Config); + + // Return the new canvas contents. + const void* pixels = new_bitmap.getPixels(); + memcpy(rgba_buffer, pixels, width * height * 4); + return true; +} + +WebScreenInfo WebWidgetHost::GetScreenInfo() { + return WebScreenInfoFactory::screenInfo(view_); +} + +void WebWidgetHost::Resize(const gfx::Rect& rect) { + SetSize(rect.width(), rect.height()); +} + +void WebWidgetHost::MouseEvent(NSEvent *event) { + const WebMouseEvent& web_event = WebInputEventFactory::mouseEvent( + event, view_); + webwidget_->handleInputEvent(web_event); +} + +void WebWidgetHost::WheelEvent(NSEvent *event) { + webwidget_->handleInputEvent( + WebInputEventFactory::mouseWheelEvent(event, view_)); +} + +void WebWidgetHost::KeyEvent(NSEvent *event) { + WebKeyboardEvent keyboard_event(WebInputEventFactory::keyboardEvent(event)); + last_key_event_ = keyboard_event; + webwidget_->handleInputEvent(keyboard_event); + + if ([event type] != NSKeyDown) + return; + + if ([event modifierFlags] & (NSNumericPadKeyMask | NSFunctionKeyMask)) { + // Don't send a Char event for non-char keys like arrows, function keys and + // clear. + switch ([event keyCode]) { + case 81: // = + case 75: // / + case 67: // * + case 78: // - + case 69: // + + case 76: // Enter + case 65: // . + case 82: // 0 + case 83: // 1 + case 84: // 2 + case 85: // 3 + case 86: // 4 + case 87: // 5 + case 88: // 6 + case 89: // 7 + case 91: // 8 + case 92: // 9 + break; + default: + return; + } + } + + // Send a Char event here to emulate the keyboard events. + // TODO(hbono): Bug 20852 implement the NSTextInput + // protocol and remove this code. + keyboard_event.type = WebInputEvent::Char; + last_key_event_ = keyboard_event; + webwidget_->handleInputEvent(keyboard_event); +} + +void WebWidgetHost::SetFocus(bool enable) { + webwidget_->setFocus(enable); +} + +void WebWidgetHost::PaintRect(const gfx::Rect& rect) { +#ifndef NDEBUG + DCHECK(!painting_); +#endif + DCHECK(canvas_.get()); + + if (rect.IsEmpty()) + return; + + if (!popup() && ((WebKit::WebView*)webwidget_)->isTransparent()) { + // When using transparency mode clear the rectangle before painting. + SkPaint clearpaint; + clearpaint.setARGB(0, 0, 0, 0); + clearpaint.setXfermodeMode(SkXfermode::kClear_Mode); + + SkRect skrc; + skrc.set(rect.x(), rect.y(), rect.right(), rect.bottom()); + canvas_->drawRect(skrc, clearpaint); + } + + set_painting(true); + webwidget_->paint(webkit_glue::ToWebCanvas(canvas_.get()), rect); + set_painting(false); +} + +void WebWidgetHost::SendKeyEvent(cef_key_type_t type, + const cef_key_info_t& keyInfo, + int modifiers) { + WebKeyboardEvent event; + + switch (type) { + case KT_KEYUP: + default: + event.type = WebInputEvent::KeyUp; + break; + case KT_KEYDOWN: + event.type = WebInputEvent::RawKeyDown; + break; + case KT_CHAR: + event.type = WebInputEvent::Char; + break; + } + event.timeStampSeconds = TickCount(); + + if (modifiers & KEY_SHIFT) + event.modifiers |= WebInputEvent::ShiftKey; + if (modifiers & KEY_ALT) + event.modifiers |= WebInputEvent::AltKey; + if (modifiers & KEY_CTRL) + event.modifiers |= WebInputEvent::ControlKey; + if (modifiers & KEY_META) + event.modifiers |= WebInputEvent::MetaKey; + if (modifiers & KEY_KEYPAD) + event.modifiers |= WebInputEvent::IsKeyPad; + + // There are several kinds of characters for which we produce key code from + // char code: + // 1. Roman letters. Windows keyboard layouts affect both virtual key codes + // and character codes for these, so e.g. 'A' gets the same keyCode on + // QWERTY, AZERTY or Dvorak layouts. + // 2. Keys for which there is no known Mac virtual key codes, like + // PrintScreen. + // 3. Certain punctuation keys. On Windows, these are also remapped depending + // on current keyboard layout, but see comment in + // windowsKeyCodeForCharCode(). + + if (type == KT_KEYUP || type == KT_KEYDOWN) { + if (keyInfo.character != 0) { + // Cmd switches Roman letters for Dvorak-QWERTY layout, so try modified + // characters first. + event.windowsKeyCode = + WebCore::windowsKeyCodeForCharCode(keyInfo.character); + } + if (event.windowsKeyCode == 0 && keyInfo.characterNoModifiers != 0) { + // Ctrl+A on an AZERTY keyboard would get VK_Q keyCode if we relied on + // keyInfo.keyCode below. + event.windowsKeyCode = + WebCore::windowsKeyCodeForCharCode(keyInfo.characterNoModifiers); + } + } + + if (event.windowsKeyCode == 0) { + // Map Mac virtual key code directly to Windows one for any keys not handled + // above. E.g. the key next to Caps Lock has the same Event.keyCode on U.S. + // keyboard ('A') and on Russian keyboard (CYRILLIC LETTER EF). + event.windowsKeyCode = WebCore::windowsKeyCodeForKeyCode(keyInfo.keyCode); + } + + event.nativeKeyCode = keyInfo.keyCode; + + int textChar = keyInfo.character; + int unmodifiedChar = keyInfo.characterNoModifiers; + + // Always use 13 for Enter/Return -- we don't want to use AppKit's + // different character for Enter. + if (event.windowsKeyCode == '\r') { + textChar = '\r'; + unmodifiedChar = '\r'; + } + + // The adjustments below are only needed in backward compatibility mode, + // but we cannot tell what mode we are in from here. + + // Turn 0x7F into 8, because backspace needs to always be 8. + if (textChar == '\x7F') + textChar = '\x8'; + if (unmodifiedChar == '\x7F') + unmodifiedChar = '\x8'; + // Always use 9 for tab -- we don't want to use AppKit's different character + // for shift-tab. + if (event.windowsKeyCode == 9) { + textChar = '\x9'; + unmodifiedChar = '\x9'; + } + + event.text[0] = textChar; + event.unmodifiedText[0] = unmodifiedChar; + + event.setKeyIdentifierFromWindowsKeyCode(); + + event.isSystemKey = !!(modifiers & KEY_META); + + last_key_event_ = event; + + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::SendMouseClickEvent(int x, int y, + cef_mouse_button_type_t type, + bool mouseUp, int clickCount) { + WebMouseEvent event; + + switch(type) { + case MBT_LEFT: + event.button = WebMouseEvent::ButtonLeft; + event.modifiers |= WebInputEvent::LeftButtonDown; + break; + case MBT_MIDDLE: + event.button = WebMouseEvent::ButtonMiddle; + event.modifiers |= WebInputEvent::MiddleButtonDown; + break; + case MBT_RIGHT: + event.button = WebMouseEvent::ButtonRight; + event.modifiers |= WebInputEvent::RightButtonDown; + break; + } + + if (mouseUp) + event.type = WebInputEvent::MouseUp; + else + event.type = WebInputEvent::MouseDown; + + event.clickCount = clickCount; + event.timeStampSeconds = TickCount(); + event.x = x; + event.y = y; + event.windowX = event.x; + event.windowY = event.y; + + if (mouseUp) { + mouse_button_down_ = WebMouseEvent::ButtonNone; + mouse_modifiers_ &= ~event.modifiers; + } else { + mouse_modifiers_ |= event.modifiers; + mouse_button_down_ = event.button; + } + event.modifiers = mouse_modifiers_; + + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave) { + WebMouseEvent event; + + event.type = WebInputEvent::MouseMove; + event.timeStampSeconds = TickCount(); + event.button = mouse_button_down_; + event.x = x; + event.y = y; + event.windowX = event.x; + event.windowY = event.y; + event.modifiers = mouse_modifiers_; + + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) { + WebMouseWheelEvent event; + + // Conversion between wheel delta amounts and number of pixels to scroll. + static const double scrollbarPixelsPerCocoaTick = 40.0; + + event.type = WebInputEvent::MouseWheel; + event.timeStampSeconds = TickCount(); + event.button = WebMouseEvent::ButtonNone; + event.deltaX = static_cast(deltaX); + event.deltaY = static_cast(deltaY); + event.wheelTicksX = static_cast(deltaX/scrollbarPixelsPerCocoaTick); + event.wheelTicksY = static_cast(deltaY/scrollbarPixelsPerCocoaTick); + event.hasPreciseScrollingDeltas = true; + event.x = x; + event.y = y; + event.windowX = event.x; + event.windowY = event.y; + + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::SendFocusEvent(bool setFocus) { + SetFocus(setFocus); +} + +void WebWidgetHost::SendCaptureLostEvent() { +} + +void WebWidgetHost::EnsureTooltip() { + // TODO(port): Implement this method as part of tooltip support. +} + +void WebWidgetHost::ResetTooltip() { + // TODO(port): Implement this method as part of tooltip support. +} diff --git a/cef1/libcef/webwidget_host_win.cc b/cef1/libcef/webwidget_host_win.cc new file mode 100644 index 000000000..15810f6e2 --- /dev/null +++ b/cef1/libcef/webwidget_host_win.cc @@ -0,0 +1,1132 @@ +// Copyright (c) 2008-2009 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. + +#include +#include + +#include "libcef/webwidget_host.h" +#include "libcef/browser_impl.h" +#include "libcef/cef_thread.h" + +#include "base/bind.h" +#include "base/logging.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebCompositionUnderline.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebPopupMenu.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebRect.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebSize.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebVector.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/win/WebInputEventFactory.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/win/WebScreenInfoFactory.h" +#include "third_party/skia/include/core/SkRegion.h" +#include "ui/base/ime/composition_text.h" +#include "ui/base/range/range.h" +#include "ui/base/win/hwnd_util.h" +#include "ui/gfx/gdi_util.h" +#include "ui/gfx/rect.h" + +#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp)) +#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp)) + +using webkit::npapi::WebPluginGeometry; +using WebKit::WebInputEvent; +using WebKit::WebInputEventFactory; +using WebKit::WebKeyboardEvent; +using WebKit::WebMouseEvent; +using WebKit::WebMouseWheelEvent; +using WebKit::WebPopupMenu; +using WebKit::WebScreenInfo; +using WebKit::WebScreenInfoFactory; +using WebKit::WebSize; +using WebKit::WebWidget; +using WebKit::WebWidgetClient; + +static const wchar_t kWindowClassName[] = L"WebWidgetHost"; + +namespace { + +struct MessageInfo { + UINT message; + WPARAM wParam; + LPARAM lParam; +}; + +BOOL CALLBACK SendMessageFunc(HWND hwnd, LPARAM lParam) { + MessageInfo* info = reinterpret_cast(lParam); + SendMessage(hwnd, info->message, info->wParam, info->lParam); + return TRUE; +} + +// Plugins are hosted in a Chromium-created parent window so it's necessary to +// send messages directly to the child window. +void SendMessageToPlugin(HWND hwnd, UINT message, WPARAM wParam, + LPARAM lParam) { + MessageInfo info = {message, wParam, lParam}; + EnumChildWindows(hwnd, SendMessageFunc, reinterpret_cast(&info)); +} + +inline SkIRect convertToSkiaRect(const gfx::Rect& r) { + return SkIRect::MakeLTRB(r.x(), r.y(), r.right(), r.bottom()); +} + +} // namespace + +/*static*/ +WebWidgetHost* WebWidgetHost::Create(HWND parent_view, + WebWidgetClient* client, + PaintDelegate* paint_delegate) { + WebWidgetHost* host = new WebWidgetHost(); + + if (!paint_delegate) { + // Create a window for the host. + static bool registered_class = false; + if (!registered_class) { + WNDCLASSEX wcex = {0}; + wcex.cbSize = sizeof(wcex); + wcex.style = CS_DBLCLKS; + wcex.lpfnWndProc = WebWidgetHost::WndProc; + wcex.hInstance = GetModuleHandle(NULL); + wcex.hCursor = LoadCursor(NULL, IDC_ARROW); + wcex.lpszClassName = kWindowClassName; + RegisterClassEx(&wcex); + registered_class = true; + } + + host->view_ = CreateWindowEx(WS_EX_TOOLWINDOW, + kWindowClassName, kWindowClassName, WS_POPUP, + 0, 0, 0, 0, + parent_view, NULL, GetModuleHandle(NULL), + NULL); + + ui::SetWindowUserData(host->view_, host); + } else { + host->paint_delegate_ = paint_delegate; + } + + host->webwidget_ = WebPopupMenu::create(client); + + return host; +} + +/*static*/ +static WebWidgetHost* FromWindow(HWND view) { + return reinterpret_cast(ui::GetWindowUserData(view)); +} + +/*static*/ +LRESULT CALLBACK WebWidgetHost::WndProc(HWND hwnd, UINT message, WPARAM wparam, + LPARAM lparam) { + WebWidgetHost* host = FromWindow(hwnd); + if (host && !host->WndProc(message, wparam, lparam)) { + switch (message) { + case WM_PAINT: { + // Paint to the window. + host->Paint(); + return 0; + } + + case WM_ERASEBKGND: + // Do nothing here to avoid flashing, the background will be erased + // during painting. + return 0; + + case WM_SIZE: + host->Resize(lparam); + return 0; + + case WM_MOUSEMOVE: + case WM_MOUSELEAVE: + case WM_LBUTTONDOWN: + case WM_MBUTTONDOWN: + case WM_RBUTTONDOWN: + case WM_LBUTTONUP: + case WM_MBUTTONUP: + case WM_RBUTTONUP: + case WM_LBUTTONDBLCLK: + case WM_MBUTTONDBLCLK: + case WM_RBUTTONDBLCLK: + host->MouseEvent(message, wparam, lparam); + // Finish the ongoing composition whenever a mouse click happens. + // It matches IE's behavior. + if (message == WM_LBUTTONDOWN || message == WM_MBUTTONDOWN || + message == WM_RBUTTONDOWN) { + host->ime_input_.CleanupComposition(host->view_); + } + break; + + case WM_MOUSEWHEEL: + { + // Only send mouse wheel events if the cursor is over the window. + POINT mousePt = { GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam) }; + RECT wndRect; + GetWindowRect(hwnd, &wndRect); + if (PtInRect(&wndRect, mousePt)) + host->WheelEvent(wparam, lparam); + } + break; + + case WM_MOUSEACTIVATE: + if (host->popup()) { + // Do not activate popup widgets on mouse click. + return MA_NOACTIVATE; + } + break; + + case WM_CAPTURECHANGED: + case WM_CANCELMODE: + host->CaptureLostEvent(); + break; + + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + case WM_CHAR: + case WM_SYSCHAR: + host->KeyEvent(message, wparam, lparam); + break; + + // Necessary for text input of characters from east-asian languages. Do + // not pass to DefWindowProc or characters will be displayed twice. + case WM_IME_CHAR: + host->KeyEvent(message, wparam, lparam); + return 0; + + case WM_CREATE: + // Call the WM_INPUTLANGCHANGE message handler to initialize + // the input locale of a browser process. + host->OnInputLangChange(0, 0); + break; + + case WM_INPUTLANGCHANGE: + host->OnInputLangChange(0, 0); + break; + + case WM_IME_SETCONTEXT: + { + BOOL handled; + LRESULT ime_retval = host->OnImeSetContext(message, wparam, + lparam, handled); + if (handled) + return ime_retval; + } + break; + + case WM_IME_STARTCOMPOSITION: + { + BOOL handled; + LRESULT ime_retval = host->OnImeStartComposition(message, wparam, + lparam, handled); + if (handled) + return ime_retval; + } + break; + + case WM_IME_COMPOSITION: + { + BOOL handled; + LRESULT ime_retval = host->OnImeComposition(message, wparam, + lparam, handled); + if (handled) + return ime_retval; + } + break; + + case WM_IME_ENDCOMPOSITION: + { + BOOL handled; + LRESULT ime_retval = host->OnImeEndComposition(message, wparam, + lparam, handled); + if (handled) + return ime_retval; + } + break; + + case WM_SETFOCUS: + host->SetFocus(true); + break; + + case WM_KILLFOCUS: + host->SetFocus(false); + break; + + case WM_NOTIFY: + host->OnNotify(0, reinterpret_cast(lparam)); + break; + + case WM_GETDLGCODE: + return DLGC_WANTALLKEYS; + } + } + + return DefWindowProc(hwnd, message, wparam, lparam); +} + +void WebWidgetHost::DidInvalidateRect(const gfx::Rect& damaged_rect) { + DLOG_IF(WARNING, painting_) << "unexpected invalidation while painting"; + + // If this invalidate overlaps with a pending scroll then we have to downgrade + // to invalidating the scroll rect. + UpdatePaintRect(damaged_rect); + InvalidateRect(damaged_rect); + + if (!popup_ && view_ && webwidget_ && input_method_is_active_ && + !has_update_input_method_task_) { + has_update_input_method_task_ = true; + + // Call UpdateInputMethod() approximately every 100ms. + CefThread::PostDelayedTask(CefThread::UI, FROM_HERE, + base::Bind(&WebWidgetHost::UpdateInputMethod, + weak_factory_.GetWeakPtr()), + 100); + } +} + +void WebWidgetHost::DidScrollRect(int dx, int dy, const gfx::Rect& clip_rect) { + DCHECK(dx || dy); + + // Invalidate and re-paint the entire scroll rect if: + // 1. Window rendering is disabled, or + // 2. We're in a state where we cannot draw into the view right now, or + // 3. The rect is being scrolled by more than the size of the view, or + // 4. The scroll rect intersects the current paint region. + if (!view_ || !canvas_.get() || layouting_ || painting_ || + abs(dx) >= clip_rect.width() || abs(dy) >= clip_rect.height() || + paint_rgn_.intersects(convertToSkiaRect(clip_rect))) { + DidInvalidateRect(clip_rect); + return; + } + + // Scroll the canvas bitmap. + { + skia::ScopedPlatformPaint scoped_platform_paint(canvas_.get()); + HDC hdc = scoped_platform_paint.GetPlatformSurface(); + RECT clip_rect_win32 = clip_rect.ToRECT(), uncovered_rect = {0, 0, 0, 0}; + ScrollDC(hdc, dx, dy, NULL, &clip_rect_win32, NULL, &uncovered_rect); + + UpdatePaintRect(gfx::Rect(uncovered_rect)); + } + + // Invalidate the scroll rect. It will be drawn from the canvas bitmap on the + // next WM_PAINT call. + InvalidateRect(clip_rect); +} + +void WebWidgetHost::Invalidate() { + if (!webwidget_) + return; + WebSize size = webwidget_->size(); + InvalidateRect(gfx::Rect(0, 0, size.width, size.height)); +} + +void WebWidgetHost::SetCursor(HCURSOR cursor) { + DCHECK(view_); + SetClassLong(view_, GCL_HCURSOR, + static_cast(reinterpret_cast(cursor))); + ::SetCursor(cursor); +} + +WebWidgetHost::WebWidgetHost() + : view_(NULL), + paint_delegate_(NULL), + webwidget_(NULL), + canvas_w_(0), + canvas_h_(0), + popup_(false), + track_mouse_leave_(false), + has_update_task_(false), + has_invalidate_task_(false), + has_update_input_method_task_(false), + tooltip_view_(NULL), + tooltip_showing_(false), + ime_notification_(false), + input_method_is_active_(false), + layouting_(false), + text_input_type_(WebKit::WebTextInputTypeNone), + ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) { + set_painting(false); +} + +WebWidgetHost::~WebWidgetHost() { + TrackMouseLeave(false); + ResetTooltip(); + + if (view_) { + ui::SetWindowUserData(view_, 0); + view_ = NULL; + } +} + +bool WebWidgetHost::WndProc(UINT message, WPARAM wparam, LPARAM lparam) { + switch (message) { + case WM_ACTIVATE: + if (wparam == WA_INACTIVE) { + PostMessage(view_, WM_CLOSE, 0, 0); + return true; + } + break; + } + + return false; +} + +void WebWidgetHost::Paint() { + int width, height; + GetSize(width, height); + gfx::Rect client_rect(width, height); + + // Damaged rectangle used for drawing when window rendering is disabled. + SkRegion damaged_rgn; + if (!view_ && !redraw_rect_.IsEmpty()) { + // At a minimum we need to send the delegate the rectangle that was + // requested by calling CefBrowser::InvalidateRect(). + damaged_rgn.setRect(convertToSkiaRect(redraw_rect_)); + redraw_rect_ = gfx::Rect(); + } + + if (view_ && !webwidget_->isAcceleratedCompositingActive()) { + // Number of pixels that the canvas is allowed to differ from the client + // area. + const int kCanvasGrowSize = 128; + + if (!canvas_.get() || + canvas_w_ < client_rect.width() || + canvas_h_ < client_rect.height() || + canvas_w_ > client_rect.width() + kCanvasGrowSize * 2 || + canvas_h_ > client_rect.height() + kCanvasGrowSize * 2) { + paint_rgn_.setRect(convertToSkiaRect(client_rect)); + + // Resize the canvas to be within a reasonable size of the client area. + canvas_w_ = client_rect.width() + kCanvasGrowSize; + canvas_h_ = client_rect.height() + kCanvasGrowSize; + canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true)); + } + } else if (!canvas_.get() || canvas_w_ != client_rect.width() || + canvas_h_ != client_rect.height()) { + paint_rgn_.setRect(convertToSkiaRect(client_rect)); + + // The canvas must be the exact size of the client area. + canvas_w_ = client_rect.width(); + canvas_h_ = client_rect.height(); + canvas_.reset(new skia::PlatformCanvas(canvas_w_, canvas_h_, true)); + } + + webwidget_->animate(0.0); + + // This may result in more invalidation. + layouting_ = true; + webwidget_->layout(); + layouting_ = false; + + // Paint the canvas if necessary. Allow painting to generate extra rects the + // first time we call it. This is necessary because some WebCore rendering + // objects update their layout only when painted. + for (int i = 0; i < 2; ++i) { + SkRegion draw_rgn; + draw_rgn.swap(paint_rgn_); + + // Draw each dirty rect in the region. + SkRegion::Cliperator iterator(draw_rgn, convertToSkiaRect(client_rect)); + for (; !iterator.done(); iterator.next()) { + const SkIRect& r = iterator.rect(); + gfx::Rect paint_rect = + gfx::Rect(r.left(), r.top(), r.width(), r.height()); + PaintRect(paint_rect); + + if (!view_) + damaged_rgn.op(convertToSkiaRect(paint_rect), SkRegion::kUnion_Op); + } + + if (paint_rgn_.isEmpty()) + break; + } + + DCHECK(paint_rgn_.isEmpty()); + + if (!view_ && plugin_map_.size() > 0) { + typedef std::list PluginList; + PluginList visible_plugins; + + // Identify the visible plugins. + PluginMap::const_iterator it = plugin_map_.begin(); + for (; it != plugin_map_.end(); ++it) { + if (it->second.visible && client_rect.Intersects(it->second.window_rect)) + visible_plugins.push_back(&it->second); + } + + if (!visible_plugins.empty()) { + skia::ScopedPlatformPaint scoped_platform_paint(canvas_.get()); + HDC drawDC = scoped_platform_paint.GetPlatformSurface(); + HRGN oldRGN, newRGN; + POINT oldViewport; + + // Paint the plugin windows. + PluginList::const_iterator it = visible_plugins.begin(); + for (; it != visible_plugins.end(); ++it) { + const WebPluginGeometry* geom = *(it); + + oldRGN = CreateRectRgn(0, 0, 1, 1); + GetClipRgn(drawDC, oldRGN); + + // Only paint inside the clip region. + newRGN = CreateRectRgn(geom->clip_rect.x(), + geom->clip_rect.y(), + geom->clip_rect.right(), + geom->clip_rect.bottom()); + gfx::SubtractRectanglesFromRegion(newRGN, geom->cutout_rects); + OffsetRgn(newRGN, geom->window_rect.x(), geom->window_rect.y()); + SelectClipRgn(drawDC, newRGN); + + // Change the viewport origin to the plugin window origin. + SetViewportOrgEx(drawDC, geom->window_rect.x(), geom->window_rect.y(), + &oldViewport); + + SendMessageToPlugin(geom->window, WM_PRINT, + reinterpret_cast(drawDC), + PRF_OWNED | PRF_ERASEBKGND | PRF_CLIENT | PRF_NONCLIENT); + + SetViewportOrgEx(drawDC, oldViewport.x, oldViewport.y, NULL); + SelectClipRgn(drawDC, oldRGN); + + if (!view_) { + damaged_rgn.op(convertToSkiaRect(geom->window_rect), + SkRegion::kUnion_Op); + } + + DeleteObject(oldRGN); + DeleteObject(newRGN); + } + } + } + + if (view_) { + // Paint to the window. + PAINTSTRUCT ps; + BeginPaint(view_, &ps); + skia::DrawToNativeContext(canvas_.get(), ps.hdc, ps.rcPaint.left, + ps.rcPaint.top, &ps.rcPaint); + EndPaint(view_, &ps); + + // Draw children + UpdateWindow(view_); + } else { + // Paint to the delegate. + DCHECK(paint_delegate_); + const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false); + DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config); + const void* pixels = bitmap.getPixels(); + + std::vector damaged_rects; + SkRegion::Cliperator iterator(damaged_rgn, convertToSkiaRect(client_rect)); + for (; !iterator.done(); iterator.next()) { + const SkIRect& r = iterator.rect(); + damaged_rects.push_back( + CefRect(r.left(), r.top(), r.width(), r.height())); + } + + paint_delegate_->Paint(popup_, damaged_rects, pixels); + } + + // Used with scheduled invalidation to maintain a consistent frame rate. + paint_last_call_ = base::TimeTicks::Now(); + if (has_invalidate_task_) + has_invalidate_task_ = false; +} + +void WebWidgetHost::InvalidateRect(const gfx::Rect& rect) { + if (rect.IsEmpty()) + return; + + if (view_) { + // Let the window handle painting. + RECT r = rect.ToRECT(); + ::InvalidateRect(view_, &r, FALSE); + } else { + // Don't post a paint task if this invalidation occurred during layout or if + // a paint task is already pending. Paint() will be called by DoPaint(). + if (!layouting_ && !has_update_task_) { + has_update_task_ = true; + CefThread::PostTask(CefThread::UI, FROM_HERE, + base::Bind(&WebWidgetHost::DoPaint, weak_factory_.GetWeakPtr())); + } + } +} + +bool WebWidgetHost::GetImage(int width, int height, void* buffer) { + const SkBitmap& bitmap = canvas_->getDevice()->accessBitmap(false); + DCHECK(bitmap.config() == SkBitmap::kARGB_8888_Config); + + if (width == canvas_->getDevice()->width() && + height == canvas_->getDevice()->height()) { + // The specified width and height values are the same as the canvas size. + // Return the existing canvas contents. + const void* pixels = bitmap.getPixels(); + memcpy(buffer, pixels, width * height * 4); + return true; + } + + // Create a new canvas of the requested size. + scoped_ptr new_canvas( + new skia::PlatformCanvas(width, height, true)); + + new_canvas->writePixels(bitmap, 0, 0); + const SkBitmap& new_bitmap = new_canvas->getDevice()->accessBitmap(false); + DCHECK(new_bitmap.config() == SkBitmap::kARGB_8888_Config); + + // Return the new canvas contents. + const void* pixels = new_bitmap.getPixels(); + memcpy(buffer, pixels, width * height * 4); + return true; +} + +WebScreenInfo WebWidgetHost::GetScreenInfo() { + return WebScreenInfoFactory::screenInfo(view_); +} + +void WebWidgetHost::Resize(LPARAM lparam) { + SetSize(LOWORD(lparam), HIWORD(lparam)); +} + +void WebWidgetHost::MouseEvent(UINT message, WPARAM wparam, LPARAM lparam) { + const WebMouseEvent& event = WebInputEventFactory::mouseEvent( + view_, message, wparam, lparam); + switch (event.type) { + case WebInputEvent::MouseMove: + TrackMouseLeave(true); + break; + case WebInputEvent::MouseLeave: + TrackMouseLeave(false); + break; + case WebInputEvent::MouseDown: + if (!popup()) { + SetCapture(view_); + + if (::GetFocus() != view_) { + // Set focus to this window. + HWND parent_hwnd = ::GetParent(view_); + if (parent_hwnd) { + CefRefPtr browser = + static_cast( + ui::GetWindowUserData(parent_hwnd)); + if (browser.get()) { + // This mimics a temporary workaround in RenderWidgetHostViewWin + // for bug 765011 to get focus when the mouse is clicked. This + // happens after the mouse down event is sent to the renderer + // because normally Windows does a WM_SETFOCUS after + // WM_LBUTTONDOWN. + browser->SetFocus(true); + } + } + } + } + break; + case WebInputEvent::MouseUp: + if (!popup()) { + if (GetCapture() == view_) + ReleaseCapture(); + } + break; + } + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::WheelEvent(WPARAM wparam, LPARAM lparam) { + const WebMouseWheelEvent& event = WebInputEventFactory::mouseWheelEvent( + view_, WM_MOUSEWHEEL, wparam, lparam); + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::KeyEvent(UINT message, WPARAM wparam, LPARAM lparam) { + const WebKeyboardEvent& event = WebInputEventFactory::keyboardEvent( + view_, message, wparam, lparam); + last_key_event_ = event; + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::CaptureLostEvent() { + webwidget_->mouseCaptureLost(); +} + +void WebWidgetHost::SetFocus(bool enable) { + webwidget_->setFocus(enable); +} + +void WebWidgetHost::OnNotify(WPARAM wparam, NMHDR* header) { + if (tooltip_view_ == NULL) + return; + + switch (header->code) { + case TTN_GETDISPINFO: + { + NMTTDISPINFOW* tooltip_info = reinterpret_cast(header); + tooltip_info->szText[0] = L'\0'; + tooltip_info->lpszText = const_cast(tooltip_text_.c_str()); + ::SendMessage(tooltip_view_, TTM_SETMAXTIPWIDTH, 0, 1024); + } + break; + + case TTN_POP: + tooltip_showing_ = false; + break; + + case TTN_SHOW: + tooltip_showing_ = true; + break; + } +} + +void WebWidgetHost::SetTooltipText(const CefString& tooltip_text) { + if (!view_) + return; + + std::wstring new_tooltip_text(tooltip_text); + if (new_tooltip_text != tooltip_text_) { + tooltip_text_ = new_tooltip_text; + + // Need to check if the tooltip is already showing so that we don't + // immediately show the tooltip with no delay when we move the mouse from + // a region with no tooltip to a region with a tooltip. + if (::IsWindow(tooltip_view_) && tooltip_showing_) { + ::SendMessage(tooltip_view_, TTM_POP, 0, 0); + ::SendMessage(tooltip_view_, TTM_POPUP, 0, 0); + } + } else { + // Make sure the tooltip gets closed after TTN_POP gets sent. For some + // reason this doesn't happen automatically, so moving the mouse around + // within the same link/image/etc doesn't cause the tooltip to re-appear. + if (!tooltip_showing_) { + if (::IsWindow(tooltip_view_)) + ::SendMessage(tooltip_view_, TTM_POP, 0, 0); + } + } +} + +void WebWidgetHost::EnsureTooltip() { + if (!view_) + return; + + UINT message = TTM_NEWTOOLRECT; + + TOOLINFO ti; + ti.cbSize = sizeof(ti); + ti.hwnd = view_; + ti.uId = 0; + if (!::IsWindow(tooltip_view_)) { + message = TTM_ADDTOOL; + tooltip_view_ = CreateWindowEx( + WS_EX_TRANSPARENT, + TOOLTIPS_CLASS, L"tooltip_view_", TTS_NOPREFIX, 0, 0, 0, 0, + view_, NULL, + NULL, NULL); + ti.uFlags = TTF_SUBCLASS; + ti.lpszText = LPSTR_TEXTCALLBACK; + } + + GetClientRect(view_, &ti.rect); + SendMessage(tooltip_view_, message, NULL, reinterpret_cast(&ti)); +} + +void WebWidgetHost::ResetTooltip() { + if (!view_) + return; + + if (::IsWindow(tooltip_view_)) + ::DestroyWindow(tooltip_view_); + tooltip_view_ = NULL; +} + +void WebWidgetHost::TrackMouseLeave(bool track) { + if (!view_) + return; + + if (track == track_mouse_leave_) + return; + track_mouse_leave_ = track; + + DCHECK(view_); + + TRACKMOUSEEVENT tme; + tme.cbSize = sizeof(TRACKMOUSEEVENT); + tme.dwFlags = TME_LEAVE; + if (!track_mouse_leave_) + tme.dwFlags |= TME_CANCEL; + tme.hwndTrack = view_; + + TrackMouseEvent(&tme); +} + +void WebWidgetHost::PaintRect(const gfx::Rect& rect) { +#ifndef NDEBUG + DCHECK(!painting_); +#endif + DCHECK(canvas_.get()); + + if (!popup() && ((WebKit::WebView*)webwidget_)->isTransparent()) { + // When using transparency mode clear the rectangle before painting. + SkPaint clearpaint; + clearpaint.setARGB(0, 0, 0, 0); + clearpaint.setXfermodeMode(SkXfermode::kClear_Mode); + + SkRect skrc; + skrc.set(rect.x(), rect.y(), rect.right(), rect.bottom()); + canvas_->drawRect(skrc, clearpaint); + } + + set_painting(true); + webwidget_->paint(canvas_.get(), rect); + set_painting(false); +} + +void WebWidgetHost::SendKeyEvent(cef_key_type_t type, + const cef_key_info_t& keyInfo, + int modifiers) { + UINT message = 0; + WPARAM wparam = keyInfo.key; + LPARAM lparam = modifiers; + + if (type == KT_KEYUP) { + if (keyInfo.sysChar) + message = WM_SYSKEYUP; + else if (keyInfo.imeChar) + message = WM_IME_KEYUP; + else + message = WM_KEYUP; + } else if (type == KT_KEYDOWN) { + if (keyInfo.sysChar) + message = WM_SYSKEYDOWN; + else if (keyInfo.imeChar) + message = WM_IME_KEYDOWN; + else + message = WM_KEYDOWN; + } else if (type == KT_CHAR) { + if (keyInfo.sysChar) + message = WM_SYSCHAR; + else if (keyInfo.imeChar) + message = WM_IME_CHAR; + else + message = WM_CHAR; + } + + if (message == 0) { + NOTREACHED(); + return; + } + + const WebKeyboardEvent& event = WebInputEventFactory::keyboardEvent( + NULL, message, wparam, lparam); + last_key_event_ = event; + + webwidget_->handleInputEvent(event); +} + +void WebWidgetHost::SendMouseClickEvent(int x, int y, + cef_mouse_button_type_t type, + bool mouseUp, int clickCount) { + DCHECK(clickCount >=1 && clickCount <= 2); + + UINT message = 0; + WPARAM wparam = 0; + LPARAM lparam = MAKELPARAM(x, y); + + if (type == MBT_LEFT) { + if (mouseUp) + message = (clickCount == 1?WM_LBUTTONUP:WM_LBUTTONDBLCLK); + else + message = WM_LBUTTONDOWN; + } else if (type == MBT_MIDDLE) { + if (mouseUp) + message = (clickCount == 1?WM_MBUTTONUP:WM_MBUTTONDBLCLK); + else + message = WM_MBUTTONDOWN; + } else if (type == MBT_RIGHT) { + if (mouseUp) + message = (clickCount == 1?WM_RBUTTONUP:WM_RBUTTONDBLCLK); + else + message = WM_RBUTTONDOWN; + } + + if (message == 0) { + NOTREACHED(); + return; + } + + if (GetKeyState(VK_CONTROL) & 0x8000) + wparam |= MK_CONTROL; + if (GetKeyState(VK_SHIFT) & 0x8000) + wparam |= MK_SHIFT; + if (GetKeyState(VK_LBUTTON) & 0x8000) + wparam |= MK_LBUTTON; + if (GetKeyState(VK_MBUTTON) & 0x8000) + wparam |= MK_MBUTTON; + if (GetKeyState(VK_RBUTTON) & 0x8000) + wparam |= MK_RBUTTON; + + gfx::PluginWindowHandle plugin = GetWindowedPluginAt(x, y); + if (plugin) { + SendMessageToPlugin(plugin, message, wparam, lparam); + } else { + const WebMouseEvent& event = WebInputEventFactory::mouseEvent(NULL, message, + wparam, lparam); + webwidget_->handleInputEvent(event); + } +} + +void WebWidgetHost::SendMouseMoveEvent(int x, int y, bool mouseLeave) { + UINT message; + WPARAM wparam = 0; + LPARAM lparam = 0; + + if (mouseLeave) { + message = WM_MOUSELEAVE; + } else { + message = WM_MOUSEMOVE; + lparam = MAKELPARAM(x, y); + } + + if (GetKeyState(VK_CONTROL) & 0x8000) + wparam |= MK_CONTROL; + if (GetKeyState(VK_SHIFT) & 0x8000) + wparam |= MK_SHIFT; + if (GetKeyState(VK_LBUTTON) & 0x8000) + wparam |= MK_LBUTTON; + if (GetKeyState(VK_MBUTTON) & 0x8000) + wparam |= MK_MBUTTON; + if (GetKeyState(VK_RBUTTON) & 0x8000) + wparam |= MK_RBUTTON; + + gfx::PluginWindowHandle plugin = GetWindowedPluginAt(x, y); + if (plugin) { + SendMessageToPlugin(plugin, message, wparam, lparam); + } else { + const WebMouseEvent& event = WebInputEventFactory::mouseEvent(NULL, message, + wparam, lparam); + webwidget_->handleInputEvent(event); + } +} + +void WebWidgetHost::SendMouseWheelEvent(int x, int y, int deltaX, int deltaY) { + WPARAM wparam = MAKEWPARAM(0, deltaY); + LPARAM lparam = MAKELPARAM(x, y); + + if (GetKeyState(VK_CONTROL) & 0x8000) + wparam |= MK_CONTROL; + if (GetKeyState(VK_SHIFT) & 0x8000) + wparam |= MK_SHIFT; + if (GetKeyState(VK_LBUTTON) & 0x8000) + wparam |= MK_LBUTTON; + if (GetKeyState(VK_MBUTTON) & 0x8000) + wparam |= MK_MBUTTON; + if (GetKeyState(VK_RBUTTON) & 0x8000) + wparam |= MK_RBUTTON; + + gfx::PluginWindowHandle plugin = GetWindowedPluginAt(x, y); + if (plugin) { + SendMessageToPlugin(plugin, WM_MOUSEWHEEL, wparam, lparam); + } else { + const WebMouseWheelEvent& event = WebInputEventFactory::mouseWheelEvent( + NULL, WM_MOUSEWHEEL, wparam, lparam); + webwidget_->handleInputEvent(event); + } +} + +void WebWidgetHost::SendFocusEvent(bool setFocus) { + SetFocus(setFocus); +} + +void WebWidgetHost::SendCaptureLostEvent() { + CaptureLostEvent(); +} + +LRESULT WebWidgetHost::OnImeSetContext(UINT message, WPARAM wparam, + LPARAM lparam, BOOL& handled) { + if (!webwidget_) + return 0; + + // We need status messages about the focused input control from a + // renderer process when: + // * the current input context has IMEs, and; + // * an application is activated. + // This seems to tell we should also check if the current input context has + // IMEs before sending a request, however, this WM_IME_SETCONTEXT is + // fortunately sent to an application only while the input context has IMEs. + // Therefore, we just start/stop status messages according to the activation + // status of this application without checks. + bool activated = (wparam == TRUE); + if (webwidget_) { + input_method_is_active_ = activated; + ime_notification_ = activated; + } + + if (ime_notification_) + ime_input_.CreateImeWindow(view_); + + ime_input_.CleanupComposition(view_); + ime_input_.SetImeWindowStyle(view_, message, wparam, lparam, &handled); + return 0; +} + +LRESULT WebWidgetHost::OnImeStartComposition(UINT message, WPARAM wparam, + LPARAM lparam, BOOL& handled) { + if (!webwidget_) + return 0; + + // Reset the composition status and create IME windows. + ime_input_.CreateImeWindow(view_); + ime_input_.ResetComposition(view_); + // We have to prevent WTL from calling ::DefWindowProc() because the function + // calls ::ImmSetCompositionWindow() and ::ImmSetCandidateWindow() to + // over-write the position of IME windows. + handled = TRUE; + return 0; +} + +LRESULT WebWidgetHost::OnImeComposition(UINT message, WPARAM wparam, + LPARAM lparam, BOOL& handled) { + if (!webwidget_) + return 0; + + // At first, update the position of the IME window. + ime_input_.UpdateImeWindow(view_); + + // ui::CompositionUnderline should be identical to + // WebKit::WebCompositionUnderline, so that we can do reinterpret_cast safely. + COMPILE_ASSERT(sizeof(ui::CompositionUnderline) == + sizeof(WebKit::WebCompositionUnderline), + ui_CompositionUnderline__WebKit_WebCompositionUnderline_diff); + + // Retrieve the result string and its attributes of the ongoing composition + // and send it to a renderer process. + ui::CompositionText composition; + if (ime_input_.GetResult(view_, lparam, &composition.text)) { + webwidget_->setComposition(composition.text, + std::vector(), + 0, 0); + webwidget_->confirmComposition(); + ime_input_.ResetComposition(view_); + // Fall though and try reading the composition string. + // Japanese IMEs send a message containing both GCS_RESULTSTR and + // GCS_COMPSTR, which means an ongoing composition has been finished + // by the start of another composition. + } + // Retrieve the composition string and its attributes of the ongoing + // composition and send it to a renderer process. + if (ime_input_.GetComposition(view_, lparam, &composition)) { + // TODO(suzhe): due to a bug of webkit, we can't use selection range with + // composition string. See: https://bugs.webkit.org/show_bug.cgi?id=37788 + composition.selection = ui::Range(composition.selection.end()); + + // TODO(suzhe): convert both renderer_host and renderer to use + // ui::CompositionText. + const std::vector& underlines = + reinterpret_cast&>( + composition.underlines); + webwidget_->setComposition( + composition.text, underlines, + composition.selection.start(), composition.selection.end()); + } + // We have to prevent WTL from calling ::DefWindowProc() because we do not + // want for the IMM (Input Method Manager) to send WM_IME_CHAR messages. + handled = TRUE; + return 0; +} + +LRESULT WebWidgetHost::OnImeEndComposition(UINT message, WPARAM wparam, + LPARAM lparam, BOOL& handled) { + if (!webwidget_) + return 0; + + if (ime_input_.is_composing()) { + // A composition has been ended while there is an ongoing composition, + // i.e. the ongoing composition has been canceled. + // We need to reset the composition status both of the ImeInput object and + // of the renderer process. + ime_input_.CancelIME(view_); + ime_input_.ResetComposition(view_); + } + ime_input_.DestroyImeWindow(view_); + // Let WTL call ::DefWindowProc() and release its resources. + handled = FALSE; + return 0; +} + +void WebWidgetHost::OnInputLangChange(DWORD character_set, + HKL input_language_id) { + // Send the given Locale ID to the ImeInput object and retrieves whether + // or not the current input context has IMEs. + // If the current input context has IMEs, a browser process has to send a + // request to a renderer process that it needs status messages about + // the focused edit control from the renderer process. + // On the other hand, if the current input context does not have IMEs, the + // browser process also has to send a request to the renderer process that + // it does not need the status messages any longer. + // To minimize the number of this notification request, we should check if + // the browser process is actually retrieving the status messages (this + // state is stored in ime_notification_) and send a request only if the + // browser process has to update this status, its details are listed below: + // * If a browser process is not retrieving the status messages, + // (i.e. ime_notification_ == false), + // send this request only if the input context does have IMEs, + // (i.e. ime_status == true); + // When it successfully sends the request, toggle its notification status, + // (i.e.ime_notification_ = !ime_notification_ = true). + // * If a browser process is retrieving the status messages + // (i.e. ime_notification_ == true), + // send this request only if the input context does not have IMEs, + // (i.e. ime_status == false). + // When it successfully sends the request, toggle its notification status, + // (i.e.ime_notification_ = !ime_notification_ = false). + // To analyze the above actions, we can optimize them into the ones + // listed below: + // 1 Sending a request only if ime_status_ != ime_notification_, and; + // 2 Copying ime_status to ime_notification_ if it sends the request + // successfully (because Action 1 shows ime_status = !ime_notification_.) + bool ime_status = ime_input_.SetInputLanguage(); + if (ime_status != ime_notification_ && webwidget_) { + input_method_is_active_ = ime_status; + ime_notification_ = ime_status; + } +} + +void WebWidgetHost::ImeUpdateTextInputState(WebKit::WebTextInputType type, + const gfx::Rect& caret_rect) { + if (text_input_type_ != type) { + text_input_type_ = type; + if (type == WebKit::WebTextInputTypeText) + ime_input_.EnableIME(view_); + else + ime_input_.DisableIME(view_); + } + + // Only update caret position if the input method is enabled. + if (type == WebKit::WebTextInputTypeText) + ime_input_.UpdateCaretRect(view_, caret_rect); +} + +void WebWidgetHost::UpdateInputMethod() { + REQUIRE_UIT(); + + has_update_input_method_task_ = false; + + if (!input_method_is_active_ || !webwidget_) + return; + + WebKit::WebTextInputType new_type = webwidget_->textInputType(); + WebKit::WebRect new_caret_bounds; + + WebKit::WebRect startRect, endRect; + if (webwidget_->selectionBounds(startRect, endRect)) + new_caret_bounds = endRect; + + // Only sends text input type and caret bounds to the browser process if they + // are changed. + if (text_input_type_ != new_type || caret_bounds_ != new_caret_bounds) { + text_input_type_ = new_type; + caret_bounds_ = new_caret_bounds; + ImeUpdateTextInputState(new_type, new_caret_bounds); + } +} diff --git a/cef1/libcef/xml_reader_impl.cc b/cef1/libcef/xml_reader_impl.cc new file mode 100644 index 000000000..27a4106f7 --- /dev/null +++ b/cef1/libcef/xml_reader_impl.cc @@ -0,0 +1,446 @@ +// 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/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/cef1/libcef/xml_reader_impl.h b/cef1/libcef/xml_reader_impl.h new file mode 100644 index 000000000..714be0a33 --- /dev/null +++ b/cef1/libcef/xml_reader_impl.h @@ -0,0 +1,73 @@ +// 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_LIBCEF_XML_READER_IMPL_H_ +#define CEF_LIBCEF_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(); + + // Initialize the reader context. + bool Initialize(CefRefPtr stream, + EncodingType encodingType, const CefString& URI); + + 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; + + // 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_XML_READER_IMPL_H_ diff --git a/cef1/libcef/zip_reader_impl.cc b/cef1/libcef/zip_reader_impl.cc new file mode 100644 index 000000000..8ab50342a --- /dev/null +++ b/cef1/libcef/zip_reader_impl.cc @@ -0,0 +1,280 @@ +// 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/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/cef1/libcef/zip_reader_impl.h b/cef1/libcef/zip_reader_impl.h new file mode 100644 index 000000000..fa8d194ad --- /dev/null +++ b/cef1/libcef/zip_reader_impl.h @@ -0,0 +1,55 @@ +// 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_LIBCEF_ZIP_READER_IMPL_H_ +#define CEF_LIBCEF_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(); + + // Initialize the reader context. + bool Initialize(CefRefPtr stream); + + virtual bool MoveToFirstFile(); + virtual bool MoveToNextFile(); + virtual bool MoveToFile(const CefString& fileName, bool caseSensitive); + virtual bool Close(); + virtual CefString GetFileName(); + virtual int64 GetFileSize(); + virtual time_t GetFileLastModified(); + virtual bool OpenFile(const CefString& password); + virtual bool CloseFile(); + virtual int ReadFile(void* buffer, size_t bufferSize); + virtual int64 Tell(); + virtual bool Eof(); + + 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_ZIP_READER_IMPL_H_ diff --git a/cef1/libcef_dll/cef_logging.h b/cef1/libcef_dll/cef_logging.h new file mode 100644 index 000000000..5d28a004e --- /dev/null +++ b/cef1/libcef_dll/cef_logging.h @@ -0,0 +1,22 @@ +// 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_CEF_LOGGING_H_ +#define CEF_LIBCEF_DLL_CEF_LOGGING_H_ +#pragma once + +#ifdef BUILDING_CEF_SHARED +#include "base/logging.h" +#else +#include // NOLINT(build/include_order) +#define DCHECK(condition) assert(condition) +#define DCHECK_EQ(val1, val2) DCHECK(val1 == val2) +#define DCHECK_NE(val1, val2) DCHECK(val1 != val2) +#define DCHECK_LE(val1, val2) DCHECK(val1 <= val2) +#define DCHECK_LT(val1, val2) DCHECK(val1 < val2) +#define DCHECK_GE(val1, val2) DCHECK(val1 >= val2) +#define DCHECK_GT(val1, val2) DCHECK(val1 > val2) +#endif + +#endif // CEF_LIBCEF_DLL_CEF_LOGGING_H_ diff --git a/cef1/libcef_dll/cpptoc/app_cpptoc.cc b/cef1/libcef_dll/cpptoc/app_cpptoc.cc new file mode 100644 index 000000000..4b1045a42 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/app_cpptoc.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/proxy_handler_cpptoc.h" +#include "libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_proxy_handler_t* CEF_CALLBACK app_get_proxy_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)->GetProxyHandler( + ); + + // Return type: refptr_same + return CefProxyHandlerCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefAppCppToC::CefAppCppToC(CefApp* cls) + : CefCppToC(cls) { + struct_.struct_.get_resource_bundle_handler = app_get_resource_bundle_handler; + struct_.struct_.get_proxy_handler = app_get_proxy_handler; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/app_cpptoc.h b/cef1/libcef_dll/cpptoc/app_cpptoc.h new file mode 100644 index 000000000..0809df8b4 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/app_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefAppCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_APP_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/base_cpptoc.h b/cef1/libcef_dll/cpptoc/base_cpptoc.h new file mode 100644 index 000000000..1184d718a --- /dev/null +++ b/cef1/libcef_dll/cpptoc/base_cpptoc.h @@ -0,0 +1,146 @@ +// 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/cef_base.h" +#include "include/capi/cef_base_capi.h" +#include "libcef_dll/cef_logging.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_.get_refct = struct_get_refct; + } + 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. + int AddRef() { + UnderlyingAddRef(); + return refct_.AddRef(); + } + int Release() { + UnderlyingRelease(); + int retval = refct_.Release(); + if (retval == 0) + delete this; + return retval; + } + int GetRefCt() { return refct_.GetRefCt(); } + + // Increment/decrement reference counts on only the underlying class. + int UnderlyingAddRef() { return class_->AddRef(); } + int UnderlyingRelease() { return class_->Release(); } + int UnderlyingGetRefCt() { return class_->GetRefCt(); } + + private: + static int CEF_CALLBACK struct_add_ref(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return 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_get_refct(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return impl->class_->GetRefCt(); + } + + protected: + CefRefCount refct_; + Struct struct_; + CefBase* class_; +}; + +#endif // CEF_LIBCEF_DLL_CPPTOC_BASE_CPPTOC_H_ diff --git a/cef1/libcef_dll/cpptoc/browser_cpptoc.cc b/cef1/libcef_dll/cpptoc/browser_cpptoc.cc new file mode 100644 index 000000000..3830709af --- /dev/null +++ b/cef1/libcef_dll/cpptoc/browser_cpptoc.cc @@ -0,0 +1,757 @@ +// 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/client_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT int cef_browser_create(cef_window_info_t* windowInfo, + struct _cef_client_t* client, const cef_string_t* url, + const struct _cef_browser_settings_t* settings) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: windowInfo; type: struct_byref + DCHECK(windowInfo); + if (!windowInfo) + return 0; + // Verify param: client; type: refptr_diff + DCHECK(client); + if (!client) + return 0; + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return 0; + // Unverified params: url + + // Translate param: windowInfo; type: struct_byref + CefWindowInfo windowInfoObj; + if (windowInfo) + windowInfoObj.AttachTo(*windowInfo); + // Translate param: settings; type: struct_byref_const + CefBrowserSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + + // Execute + bool _retval = CefBrowser::CreateBrowser( + windowInfoObj, + CefClientCToCpp::Wrap(client), + CefString(url), + settingsObj); + + // Restore param: windowInfo; type: struct_byref + if (windowInfo) + windowInfoObj.DetachTo(*windowInfo); + + // Return type: bool + return _retval; +} + +CEF_EXPORT cef_browser_t* cef_browser_create_sync(cef_window_info_t* windowInfo, + struct _cef_client_t* client, const cef_string_t* url, + const struct _cef_browser_settings_t* settings) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: windowInfo; type: struct_byref + DCHECK(windowInfo); + if (!windowInfo) + return NULL; + // Verify param: client; type: refptr_diff + DCHECK(client); + if (!client) + return NULL; + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return NULL; + // Unverified params: url + + // Translate param: windowInfo; type: struct_byref + CefWindowInfo windowInfoObj; + if (windowInfo) + windowInfoObj.AttachTo(*windowInfo); + // Translate param: settings; type: struct_byref_const + CefBrowserSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + + // Execute + CefRefPtr _retval = CefBrowser::CreateBrowserSync( + windowInfoObj, + CefClientCToCpp::Wrap(client), + CefString(url), + settingsObj); + + // Restore param: windowInfo; type: struct_byref + if (windowInfo) + windowInfoObj.DetachTo(*windowInfo); + + // Return type: refptr_same + return CefBrowserCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK browser_parent_window_will_close( + struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->ParentWindowWillClose(); +} + +void CEF_CALLBACK browser_close_browser(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->CloseBrowser(); +} + +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(); +} + +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(); +} + +void CEF_CALLBACK browser_set_focus(struct _cef_browser_t* self, int enable) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SetFocus( + enable?true:false); +} + +cef_window_handle_t CEF_CALLBACK browser_get_window_handle( + struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + cef_window_handle_t _retval = CefBrowserCppToC::Get(self)->GetWindowHandle(); + + // Return type: simple + return _retval; +} + +cef_window_handle_t CEF_CALLBACK browser_get_opener_window_handle( + struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + cef_window_handle_t _retval = CefBrowserCppToC::Get( + self)->GetOpenerWindowHandle(); + + // Return type: simple + 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_client_t* CEF_CALLBACK browser_get_client( + 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)->GetClient(); + + // Return type: refptr_diff + return CefClientCToCpp::Unwrap(_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(struct _cef_browser_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 + CefRefPtr _retval = CefBrowserCppToC::Get(self)->GetFrame( + CefString(name)); + + // Return type: refptr_same + return CefFrameCppToC::Wrap(_retval); +} + +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); +} + +void CEF_CALLBACK browser_find(struct _cef_browser_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 + CefBrowserCppToC::Get(self)->Find( + identifier, + CefString(searchText), + forward?true:false, + matchCase?true:false, + findNext?true:false); +} + +void CEF_CALLBACK browser_stop_finding(struct _cef_browser_t* self, + int clearSelection) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->StopFinding( + clearSelection?true:false); +} + +double CEF_CALLBACK browser_get_zoom_level(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + double _retval = CefBrowserCppToC::Get(self)->GetZoomLevel(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK browser_set_zoom_level(struct _cef_browser_t* self, + double zoomLevel) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SetZoomLevel( + zoomLevel); +} + +void CEF_CALLBACK browser_clear_history(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->ClearHistory(); +} + +void CEF_CALLBACK browser_show_dev_tools(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->ShowDevTools(); +} + +void CEF_CALLBACK browser_close_dev_tools(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->CloseDevTools(); +} + +int CEF_CALLBACK browser_is_window_rendering_disabled( + 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)->IsWindowRenderingDisabled(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK browser_get_size(struct _cef_browser_t* self, + enum cef_paint_element_type_t type, int* width, int* height) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: width; type: simple_byref + DCHECK(width); + if (!width) + return 0; + // Verify param: height; type: simple_byref + DCHECK(height); + if (!height) + return 0; + + // Translate param: width; type: simple_byref + int widthVal = width?*width:0; + // Translate param: height; type: simple_byref + int heightVal = height?*height:0; + + // Execute + bool _retval = CefBrowserCppToC::Get(self)->GetSize( + type, + widthVal, + heightVal); + + // Restore param: width; type: simple_byref + if (width) + *width = widthVal; + // Restore param: height; type: simple_byref + if (height) + *height = heightVal; + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_set_size(struct _cef_browser_t* self, + enum cef_paint_element_type_t type, int width, int height) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SetSize( + type, + width, + height); +} + +int CEF_CALLBACK browser_is_popup_visible(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)->IsPopupVisible(); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_hide_popup(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->HidePopup(); +} + +void CEF_CALLBACK browser_invalidate(struct _cef_browser_t* self, + const cef_rect_t* dirtyRect) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: dirtyRect; type: simple_byref_const + DCHECK(dirtyRect); + if (!dirtyRect) + return; + + // Translate param: dirtyRect; type: simple_byref_const + CefRect dirtyRectVal = dirtyRect?*dirtyRect:CefRect(); + + // Execute + CefBrowserCppToC::Get(self)->Invalidate( + dirtyRectVal); +} + +int CEF_CALLBACK browser_get_image(struct _cef_browser_t* self, + enum cef_paint_element_type_t type, int width, int height, void* buffer) { + // 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 + bool _retval = CefBrowserCppToC::Get(self)->GetImage( + type, + width, + height, + buffer); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK browser_send_key_event(struct _cef_browser_t* self, + enum cef_key_type_t type, const struct _cef_key_info_t* keyInfo, + int modifiers) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: keyInfo; type: struct_byref_const + DCHECK(keyInfo); + if (!keyInfo) + return; + + // Translate param: keyInfo; type: struct_byref_const + CefKeyInfo keyInfoObj; + if (keyInfo) + keyInfoObj.Set(*keyInfo, false); + + // Execute + CefBrowserCppToC::Get(self)->SendKeyEvent( + type, + keyInfoObj, + modifiers); +} + +void CEF_CALLBACK browser_send_mouse_click_event(struct _cef_browser_t* self, + int x, int y, enum cef_mouse_button_type_t type, int mouseUp, + int clickCount) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SendMouseClickEvent( + x, + y, + type, + mouseUp?true:false, + clickCount); +} + +void CEF_CALLBACK browser_send_mouse_move_event(struct _cef_browser_t* self, + int x, int y, int mouseLeave) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SendMouseMoveEvent( + x, + y, + mouseLeave?true:false); +} + +void CEF_CALLBACK browser_send_mouse_wheel_event(struct _cef_browser_t* self, + int x, int y, int deltaX, int deltaY) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SendMouseWheelEvent( + x, + y, + deltaX, + deltaY); +} + +void CEF_CALLBACK browser_send_focus_event(struct _cef_browser_t* self, + int setFocus) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SendFocusEvent( + setFocus?true:false); +} + +void CEF_CALLBACK browser_send_capture_lost_event(struct _cef_browser_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefBrowserCppToC::Get(self)->SendCaptureLostEvent(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefBrowserCppToC::CefBrowserCppToC(CefBrowser* cls) + : CefCppToC(cls) { + struct_.struct_.parent_window_will_close = browser_parent_window_will_close; + struct_.struct_.close_browser = browser_close_browser; + 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_.reload = browser_reload; + struct_.struct_.reload_ignore_cache = browser_reload_ignore_cache; + struct_.struct_.stop_load = browser_stop_load; + struct_.struct_.set_focus = browser_set_focus; + struct_.struct_.get_window_handle = browser_get_window_handle; + struct_.struct_.get_opener_window_handle = browser_get_opener_window_handle; + struct_.struct_.is_popup = browser_is_popup; + struct_.struct_.has_document = browser_has_document; + struct_.struct_.get_client = browser_get_client; + struct_.struct_.get_main_frame = browser_get_main_frame; + struct_.struct_.get_focused_frame = browser_get_focused_frame; + struct_.struct_.get_frame = browser_get_frame; + struct_.struct_.get_frame_names = browser_get_frame_names; + struct_.struct_.find = browser_find; + struct_.struct_.stop_finding = browser_stop_finding; + struct_.struct_.get_zoom_level = browser_get_zoom_level; + struct_.struct_.set_zoom_level = browser_set_zoom_level; + struct_.struct_.clear_history = browser_clear_history; + struct_.struct_.show_dev_tools = browser_show_dev_tools; + struct_.struct_.close_dev_tools = browser_close_dev_tools; + struct_.struct_.is_window_rendering_disabled = + browser_is_window_rendering_disabled; + struct_.struct_.get_size = browser_get_size; + struct_.struct_.set_size = browser_set_size; + struct_.struct_.is_popup_visible = browser_is_popup_visible; + struct_.struct_.hide_popup = browser_hide_popup; + struct_.struct_.invalidate = browser_invalidate; + struct_.struct_.get_image = browser_get_image; + struct_.struct_.send_key_event = browser_send_key_event; + struct_.struct_.send_mouse_click_event = browser_send_mouse_click_event; + struct_.struct_.send_mouse_move_event = browser_send_mouse_move_event; + struct_.struct_.send_mouse_wheel_event = browser_send_mouse_wheel_event; + struct_.struct_.send_focus_event = browser_send_focus_event; + struct_.struct_.send_capture_lost_event = browser_send_capture_lost_event; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/browser_cpptoc.h b/cef1/libcef_dll/cpptoc/browser_cpptoc.h new file mode 100644 index 000000000..eb8994163 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/browser_cpptoc.h @@ -0,0 +1,38 @@ +// 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_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); + virtual ~CefBrowserCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_BROWSER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/client_cpptoc.cc b/cef1/libcef_dll/cpptoc/client_cpptoc.cc new file mode 100644 index 000000000..6ce7df474 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/client_cpptoc.cc @@ -0,0 +1,281 @@ +// 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/client_cpptoc.h" +#include "libcef_dll/cpptoc/display_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/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/menu_handler_cpptoc.h" +#include "libcef_dll/cpptoc/permission_handler_cpptoc.h" +#include "libcef_dll/cpptoc/print_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_handler_cpptoc.h" +#include "libcef_dll/cpptoc/request_handler_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_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); +} + +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_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_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_menu_handler_t* CEF_CALLBACK client_get_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)->GetMenuHandler(); + + // Return type: refptr_same + return CefMenuHandlerCppToC::Wrap(_retval); +} + +struct _cef_permission_handler_t* CEF_CALLBACK client_get_permission_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)->GetPermissionHandler(); + + // Return type: refptr_same + return CefPermissionHandlerCppToC::Wrap(_retval); +} + +struct _cef_print_handler_t* CEF_CALLBACK client_get_print_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)->GetPrintHandler(); + + // Return type: refptr_same + return CefPrintHandlerCppToC::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_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_v8context_handler_t* CEF_CALLBACK client_get_v8context_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)->GetV8ContextHandler(); + + // Return type: refptr_same + return CefV8ContextHandlerCppToC::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_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); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefClientCppToC::CefClientCppToC(CefClient* cls) + : CefCppToC(cls) { + struct_.struct_.get_life_span_handler = client_get_life_span_handler; + struct_.struct_.get_load_handler = client_get_load_handler; + struct_.struct_.get_request_handler = client_get_request_handler; + struct_.struct_.get_display_handler = client_get_display_handler; + struct_.struct_.get_focus_handler = client_get_focus_handler; + struct_.struct_.get_keyboard_handler = client_get_keyboard_handler; + struct_.struct_.get_menu_handler = client_get_menu_handler; + struct_.struct_.get_permission_handler = client_get_permission_handler; + struct_.struct_.get_print_handler = client_get_print_handler; + struct_.struct_.get_find_handler = client_get_find_handler; + struct_.struct_.get_jsdialog_handler = client_get_jsdialog_handler; + struct_.struct_.get_v8context_handler = client_get_v8context_handler; + struct_.struct_.get_render_handler = client_get_render_handler; + struct_.struct_.get_drag_handler = client_get_drag_handler; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/client_cpptoc.h b/cef1/libcef_dll/cpptoc/client_cpptoc.h new file mode 100644 index 000000000..1db8e5b12 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/client_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefClientCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_CLIENT_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/command_line_cpptoc.cc b/cef1/libcef_dll/cpptoc/command_line_cpptoc.cc new file mode 100644 index 000000000..fbdf9c943 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/command_line_cpptoc.cc @@ -0,0 +1,316 @@ +// 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/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); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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)); +} + +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)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefCommandLineCppToC::CefCommandLineCppToC(CefCommandLine* cls) + : CefCppToC(cls) { + struct_.struct_.init_from_argv = command_line_init_from_argv; + struct_.struct_.init_from_string = command_line_init_from_string; + 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/command_line_cpptoc.h b/cef1/libcef_dll/cpptoc/command_line_cpptoc.h new file mode 100644 index 000000000..1d98acd79 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/command_line_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefCommandLineCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COMMAND_LINE_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/content_filter_cpptoc.cc b/cef1/libcef_dll/cpptoc/content_filter_cpptoc.cc new file mode 100644 index 000000000..1284f3ad3 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/content_filter_cpptoc.cc @@ -0,0 +1,108 @@ +// 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/content_filter_cpptoc.h" +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK content_filter_process_data( + struct _cef_content_filter_t* self, const void* data, int data_size, + struct _cef_stream_reader_t** substitute_data) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return; + // Verify param: substitute_data; type: refptr_diff_byref + DCHECK(substitute_data); + if (!substitute_data) + return; + + // Translate param: substitute_data; type: refptr_diff_byref + CefRefPtr substitute_dataPtr; + if (substitute_data && *substitute_data) + substitute_dataPtr = CefStreamReaderCToCpp::Wrap(*substitute_data); + CefStreamReader* substitute_dataOrig = substitute_dataPtr.get(); + + // Execute + CefContentFilterCppToC::Get(self)->ProcessData( + data, + data_size, + substitute_dataPtr); + + // Restore param: substitute_data; type: refptr_diff_byref + if (substitute_data) { + if (substitute_dataPtr.get()) { + if (substitute_dataPtr.get() != substitute_dataOrig) { + *substitute_data = CefStreamReaderCToCpp::Unwrap(substitute_dataPtr); + } + } else { + *substitute_data = NULL; + } + } +} + +void CEF_CALLBACK content_filter_drain(struct _cef_content_filter_t* self, + struct _cef_stream_reader_t** remainder) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: remainder; type: refptr_diff_byref + DCHECK(remainder); + if (!remainder) + return; + + // Translate param: remainder; type: refptr_diff_byref + CefRefPtr remainderPtr; + if (remainder && *remainder) + remainderPtr = CefStreamReaderCToCpp::Wrap(*remainder); + CefStreamReader* remainderOrig = remainderPtr.get(); + + // Execute + CefContentFilterCppToC::Get(self)->Drain( + remainderPtr); + + // Restore param: remainder; type: refptr_diff_byref + if (remainder) { + if (remainderPtr.get()) { + if (remainderPtr.get() != remainderOrig) { + *remainder = CefStreamReaderCToCpp::Unwrap(remainderPtr); + } + } else { + *remainder = NULL; + } + } +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefContentFilterCppToC::CefContentFilterCppToC(CefContentFilter* cls) + : CefCppToC( + cls) { + struct_.struct_.process_data = content_filter_process_data; + struct_.struct_.drain = content_filter_drain; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/content_filter_cpptoc.h b/cef1/libcef_dll/cpptoc/content_filter_cpptoc.h new file mode 100644 index 000000000..a1af009ca --- /dev/null +++ b/cef1/libcef_dll/cpptoc/content_filter_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_CONTENT_FILTER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_CONTENT_FILTER_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_content_filter.h" +#include "include/capi/cef_content_filter_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 CefContentFilterCppToC + : public CefCppToC { + public: + explicit CefContentFilterCppToC(CefContentFilter* cls); + virtual ~CefContentFilterCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_CONTENT_FILTER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/cookie_manager_cpptoc.cc b/cef1/libcef_dll/cpptoc/cookie_manager_cpptoc.cc new file mode 100644 index 000000000..5af5020de --- /dev/null +++ b/cef1/libcef_dll/cpptoc/cookie_manager_cpptoc.cc @@ -0,0 +1,200 @@ +// 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/cookie_manager_cpptoc.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) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: path + + // Execute + CefRefPtr _retval = CefCookieManager::CreateManager( + CefString(path)); + + // 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) { + // 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)); + + // 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/cookie_manager_cpptoc.h b/cef1/libcef_dll/cpptoc/cookie_manager_cpptoc.h new file mode 100644 index 000000000..cacc919f4 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/cookie_manager_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefCookieManagerCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COOKIE_MANAGER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/cookie_visitor_cpptoc.cc b/cef1/libcef_dll/cpptoc/cookie_visitor_cpptoc.cc new file mode 100644 index 000000000..fa61fe6c1 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/cookie_visitor_cpptoc.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/cookie_visitor_cpptoc.h b/cef1/libcef_dll/cpptoc/cookie_visitor_cpptoc.h new file mode 100644 index 000000000..6473a2309 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/cookie_visitor_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefCookieVisitorCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_COOKIE_VISITOR_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/cpptoc.h b/cef1/libcef_dll/cpptoc/cpptoc.h new file mode 100644 index 000000000..3449264f9 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/cpptoc.h @@ -0,0 +1,160 @@ +// 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/cef_base.h" +#include "include/capi/cef_base_capi.h" +#include "libcef_dll/cef_logging.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); + // 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.get_refct = struct_get_refct; + +#ifndef NDEBUG + CefAtomicIncrement(&DebugObjCt); +#endif + } + virtual ~CefCppToC() { +#ifndef NDEBUG + CefAtomicDecrement(&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. + int AddRef() { + UnderlyingAddRef(); + return refct_.AddRef(); + } + int Release() { + UnderlyingRelease(); + int retval = refct_.Release(); + if (retval == 0) + delete this; + return retval; + } + int GetRefCt() { return refct_.GetRefCt(); } + + // Increment/decrement reference counts on only the underlying class. + int UnderlyingAddRef() { return class_->AddRef(); } + int UnderlyingRelease() { return class_->Release(); } + int UnderlyingGetRefCt() { return class_->GetRefCt(); } + +#ifndef NDEBUG + // Simple tracking of allocated objects. + static long DebugObjCt; // NOLINT(runtime/int) +#endif + + private: + static int CEF_CALLBACK struct_add_ref(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return 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_get_refct(struct _cef_base_t* base) { + DCHECK(base); + if (!base) + return 0; + + Struct* impl = reinterpret_cast(base); + return impl->class_->GetRefCt(); + } + + protected: + CefRefCount refct_; + Struct struct_; + BaseName* class_; +}; + +#endif // CEF_LIBCEF_DLL_CPPTOC_CPPTOC_H_ diff --git a/cef1/libcef_dll/cpptoc/display_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/display_handler_cpptoc.cc new file mode 100644 index 000000000..5b6f6ef51 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/display_handler_cpptoc.cc @@ -0,0 +1,204 @@ +// 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/display_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 display_handler_on_nav_state_change( + struct _cef_display_handler_t* self, cef_browser_t* browser, 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 + CefDisplayHandlerCppToC::Get(self)->OnNavStateChange( + CefBrowserCToCpp::Wrap(browser), + canGoBack?true:false, + canGoForward?true:false); +} + +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_contents_size_change( + struct _cef_display_handler_t* self, cef_browser_t* browser, + struct _cef_frame_t* frame, 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: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return; + + // Execute + CefDisplayHandlerCppToC::Get(self)->OnContentsSizeChange( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + width, + height); +} + +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)); +} + +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, enum cef_handler_statustype_t type) { + // 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), + type); +} + +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_nav_state_change = display_handler_on_nav_state_change; + struct_.struct_.on_address_change = display_handler_on_address_change; + struct_.struct_.on_contents_size_change = + display_handler_on_contents_size_change; + struct_.struct_.on_title_change = display_handler_on_title_change; + 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/display_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/display_handler_cpptoc.h new file mode 100644 index 000000000..0622ced14 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/display_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefDisplayHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DISPLAY_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/domdocument_cpptoc.cc b/cef1/libcef_dll/cpptoc/domdocument_cpptoc.cc new file mode 100644 index 000000000..403f8d812 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domdocument_cpptoc.cc @@ -0,0 +1,303 @@ +// 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/domdocument_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +enum 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; +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_selection_start_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)->GetSelectionStartNode(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_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; +} + +struct _cef_domnode_t* CEF_CALLBACK domdocument_get_selection_end_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)->GetSelectionEndNode(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_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_node = + domdocument_get_selection_start_node; + struct_.struct_.get_selection_start_offset = + domdocument_get_selection_start_offset; + struct_.struct_.get_selection_end_node = domdocument_get_selection_end_node; + 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/domdocument_cpptoc.h b/cef1/libcef_dll/cpptoc/domdocument_cpptoc.h new file mode 100644 index 000000000..a35fcdd7a --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domdocument_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefDOMDocumentCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMDOCUMENT_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/domevent_cpptoc.cc b/cef1/libcef_dll/cpptoc/domevent_cpptoc.cc new file mode 100644 index 000000000..051898cab --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domevent_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/domevent_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +cef_string_userfree_t CEF_CALLBACK domevent_get_type( + struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefString _retval = CefDOMEventCppToC::Get(self)->GetType(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +enum cef_dom_event_category_t CEF_CALLBACK domevent_get_category( + struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return DOM_EVENT_CATEGORY_UNKNOWN; + + // Execute + cef_dom_event_category_t _retval = CefDOMEventCppToC::Get(self)->GetCategory( + ); + + // Return type: simple + return _retval; +} + +enum cef_dom_event_phase_t CEF_CALLBACK domevent_get_phase( + struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return DOM_EVENT_PHASE_UNKNOWN; + + // Execute + cef_dom_event_phase_t _retval = CefDOMEventCppToC::Get(self)->GetPhase(); + + // Return type: simple + return _retval; +} + +int CEF_CALLBACK domevent_can_bubble(struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMEventCppToC::Get(self)->CanBubble(); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK domevent_can_cancel(struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + + // Execute + bool _retval = CefDOMEventCppToC::Get(self)->CanCancel(); + + // Return type: bool + return _retval; +} + +cef_domdocument_t* CEF_CALLBACK domevent_get_document( + struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMEventCppToC::Get(self)->GetDocument( + ); + + // Return type: refptr_same + return CefDOMDocumentCppToC::Wrap(_retval); +} + +cef_domnode_t* CEF_CALLBACK domevent_get_target(struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMEventCppToC::Get(self)->GetTarget(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + +cef_domnode_t* CEF_CALLBACK domevent_get_current_target( + struct _cef_domevent_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return NULL; + + // Execute + CefRefPtr _retval = CefDOMEventCppToC::Get( + self)->GetCurrentTarget(); + + // Return type: refptr_same + return CefDOMNodeCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDOMEventCppToC::CefDOMEventCppToC(CefDOMEvent* cls) + : CefCppToC(cls) { + struct_.struct_.get_type = domevent_get_type; + struct_.struct_.get_category = domevent_get_category; + struct_.struct_.get_phase = domevent_get_phase; + struct_.struct_.can_bubble = domevent_can_bubble; + struct_.struct_.can_cancel = domevent_can_cancel; + struct_.struct_.get_document = domevent_get_document; + struct_.struct_.get_target = domevent_get_target; + struct_.struct_.get_current_target = domevent_get_current_target; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/domevent_cpptoc.h b/cef1/libcef_dll/cpptoc/domevent_cpptoc.h new file mode 100644 index 000000000..aec1540ec --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domevent_cpptoc.h @@ -0,0 +1,36 @@ +// 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_DOMEVENT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOMEVENT_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 CefDOMEventCppToC + : public CefCppToC { + public: + explicit CefDOMEventCppToC(CefDOMEvent* cls); + virtual ~CefDOMEventCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMEVENT_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/domevent_listener_cpptoc.cc b/cef1/libcef_dll/cpptoc/domevent_listener_cpptoc.cc new file mode 100644 index 000000000..59e22c653 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domevent_listener_cpptoc.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/domevent_listener_cpptoc.h" +#include "libcef_dll/ctocpp/domevent_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK domevent_listener_handle_event( + struct _cef_domevent_listener_t* self, cef_domevent_t* event) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: event; type: refptr_diff + DCHECK(event); + if (!event) + return; + + // Execute + CefDOMEventListenerCppToC::Get(self)->HandleEvent( + CefDOMEventCToCpp::Wrap(event)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDOMEventListenerCppToC::CefDOMEventListenerCppToC(CefDOMEventListener* cls) + : CefCppToC(cls) { + struct_.struct_.handle_event = domevent_listener_handle_event; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/domevent_listener_cpptoc.h b/cef1/libcef_dll/cpptoc/domevent_listener_cpptoc.h new file mode 100644 index 000000000..562882f3e --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domevent_listener_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_DOMEVENT_LISTENER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_DOMEVENT_LISTENER_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 CefDOMEventListenerCppToC + : public CefCppToC { + public: + explicit CefDOMEventListenerCppToC(CefDOMEventListener* cls); + virtual ~CefDOMEventListenerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMEVENT_LISTENER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/domnode_cpptoc.cc b/cef1/libcef_dll/cpptoc/domnode_cpptoc.cc new file mode 100644 index 000000000..209ae7a82 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domnode_cpptoc.cc @@ -0,0 +1,479 @@ +// 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/domdocument_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" +#include "libcef_dll/ctocpp/domevent_listener_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +enum 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_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); +} + +void CEF_CALLBACK domnode_add_event_listener(struct _cef_domnode_t* self, + const cef_string_t* eventType, struct _cef_domevent_listener_t* listener, + int useCapture) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: eventType; type: string_byref_const + DCHECK(eventType); + if (!eventType) + return; + // Verify param: listener; type: refptr_diff + DCHECK(listener); + if (!listener) + return; + + // Execute + CefDOMNodeCppToC::Get(self)->AddEventListener( + CefString(eventType), + CefDOMEventListenerCToCpp::Wrap(listener), + useCapture?true:false); +} + +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_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_.add_event_listener = domnode_add_event_listener; + 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/domnode_cpptoc.h b/cef1/libcef_dll/cpptoc/domnode_cpptoc.h new file mode 100644 index 000000000..1da9af779 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domnode_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefDOMNodeCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMNODE_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/domvisitor_cpptoc.cc b/cef1/libcef_dll/cpptoc/domvisitor_cpptoc.cc new file mode 100644 index 000000000..aefbe1c92 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domvisitor_cpptoc.cc @@ -0,0 +1,48 @@ +// 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/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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/domvisitor_cpptoc.h b/cef1/libcef_dll/cpptoc/domvisitor_cpptoc.h new file mode 100644 index 000000000..0f09b0b60 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/domvisitor_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefDOMVisitorCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOMVISITOR_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/download_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/download_handler_cpptoc.cc new file mode 100644 index 000000000..a868039ec --- /dev/null +++ b/cef1/libcef_dll/cpptoc/download_handler_cpptoc.cc @@ -0,0 +1,65 @@ +// 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/download_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK download_handler_received_data( + struct _cef_download_handler_t* self, void* data, int data_size) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return 0; + + // Execute + bool _retval = CefDownloadHandlerCppToC::Get(self)->ReceivedData( + data, + data_size); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK download_handler_complete( + struct _cef_download_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefDownloadHandlerCppToC::Get(self)->Complete(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDownloadHandlerCppToC::CefDownloadHandlerCppToC(CefDownloadHandler* cls) + : CefCppToC(cls) { + struct_.struct_.received_data = download_handler_received_data; + struct_.struct_.complete = download_handler_complete; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/download_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/download_handler_cpptoc.h new file mode 100644 index 000000000..f659d613d --- /dev/null +++ b/cef1/libcef_dll/cpptoc/download_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefDownloadHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DOWNLOAD_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/drag_data_cpptoc.cc b/cef1/libcef_dll/cpptoc/drag_data_cpptoc.cc new file mode 100644 index 000000000..5a9599931 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/drag_data_cpptoc.cc @@ -0,0 +1,216 @@ +// 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/drag_data_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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(); +} + +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; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefDragDataCppToC::CefDragDataCppToC(CefDragData* cls) + : CefCppToC(cls) { + 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_names = drag_data_get_file_names; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/drag_data_cpptoc.h b/cef1/libcef_dll/cpptoc/drag_data_cpptoc.h new file mode 100644 index 000000000..9e880a41e --- /dev/null +++ b/cef1/libcef_dll/cpptoc/drag_data_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefDragDataCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DRAG_DATA_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/drag_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/drag_handler_cpptoc.cc new file mode 100644 index 000000000..927caeeb5 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/drag_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_start(struct _cef_drag_handler_t* self, + cef_browser_t* browser, cef_drag_data_t* dragData, + enum 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)->OnDragStart( + CefBrowserCToCpp::Wrap(browser), + CefDragDataCToCpp::Wrap(dragData), + mask); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK drag_handler_on_drag_enter(struct _cef_drag_handler_t* self, + cef_browser_t* browser, cef_drag_data_t* dragData, + enum 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_start = drag_handler_on_drag_start; + struct_.struct_.on_drag_enter = drag_handler_on_drag_enter; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/drag_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/drag_handler_cpptoc.h new file mode 100644 index 000000000..94138f843 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/drag_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefDragHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_DRAG_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/find_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/find_handler_cpptoc.cc new file mode 100644 index 000000000..e96273377 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/find_handler_cpptoc.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/find_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/find_handler_cpptoc.h new file mode 100644 index 000000000..9bb2c68b0 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/find_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefFindHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FIND_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/focus_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/focus_handler_cpptoc.cc new file mode 100644 index 000000000..bffe00bb5 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/focus_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" +#include "libcef_dll/ctocpp/frame_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, enum cef_handler_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_focused_node_changed( + struct _cef_focus_handler_t* self, cef_browser_t* browser, + struct _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 + CefFocusHandlerCppToC::Get(self)->OnFocusedNodeChanged( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefDOMNodeCToCpp::Wrap(node)); +} + + +// 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_focused_node_changed = + focus_handler_on_focused_node_changed; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/focus_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/focus_handler_cpptoc.h new file mode 100644 index 000000000..b88e246ec --- /dev/null +++ b/cef1/libcef_dll/cpptoc/focus_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefFocusHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FOCUS_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/frame_cpptoc.cc b/cef1/libcef_dll/cpptoc/frame_cpptoc.cc new file mode 100644 index 000000000..aef2f2e24 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/frame_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/stream_reader_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/ctocpp/domvisitor_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_print(struct _cef_frame_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefFrameCppToC::Get(self)->Print(); +} + +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(); +} + +cef_string_userfree_t CEF_CALLBACK frame_get_source(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)->GetSource(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +cef_string_userfree_t CEF_CALLBACK frame_get_text(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)->GetText(); + + // Return type: string + return _retval.DetachToUserFree(); +} + +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_load_stream(struct _cef_frame_t* self, + struct _cef_stream_reader_t* stream, const cef_string_t* url) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: stream; type: refptr_same + DCHECK(stream); + if (!stream) + return; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return; + + // Execute + CefFrameCppToC::Get(self)->LoadStream( + CefStreamReaderCppToC::Unwrap(stream), + CefString(url)); +} + +void CEF_CALLBACK frame_execute_java_script(struct _cef_frame_t* self, + const cef_string_t* jsCode, const cef_string_t* scriptUrl, + int startLine) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: jsCode; type: string_byref_const + DCHECK(jsCode); + if (!jsCode) + return; + // Unverified params: scriptUrl + + // Execute + CefFrameCppToC::Get(self)->ExecuteJavaScript( + CefString(jsCode), + CefString(scriptUrl), + startLine); +} + +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); +} + +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)); +} + +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); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefFrameCppToC::CefFrameCppToC(CefFrame* cls) + : CefCppToC(cls) { + 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_.print = frame_print; + 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_.load_stream = frame_load_stream; + 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_.visit_dom = frame_visit_dom; + struct_.struct_.get_v8context = frame_get_v8context; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = + 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/frame_cpptoc.h b/cef1/libcef_dll/cpptoc/frame_cpptoc.h new file mode 100644 index 000000000..0392777de --- /dev/null +++ b/cef1/libcef_dll/cpptoc/frame_cpptoc.h @@ -0,0 +1,40 @@ +// 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_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); + virtual ~CefFrameCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_FRAME_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc new file mode 100644 index 000000000..0de68df23 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/jsdialog_handler_cpptoc.cc @@ -0,0 +1,152 @@ +// 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/jsdialog_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 jsdialog_handler_on_jsalert( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_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: frame; type: refptr_diff + DCHECK(frame); + if (!frame) + return 0; + // Unverified params: message + + // Execute + bool _retval = CefJSDialogHandlerCppToC::Get(self)->OnJSAlert( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(message)); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK jsdialog_handler_on_jsconfirm( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_t* message, int* retval) { + // 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: retval; type: bool_byref + DCHECK(retval); + if (!retval) + return 0; + // Unverified params: message + + // Translate param: retval; type: bool_byref + bool retvalBool = (retval && *retval)?true:false; + + // Execute + bool _retval = CefJSDialogHandlerCppToC::Get(self)->OnJSConfirm( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(message), + retvalBool); + + // Restore param: retval; type: bool_byref + if (retval) + *retval = retvalBool?true:false; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK jsdialog_handler_on_jsprompt( + struct _cef_jsdialog_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_string_t* message, + const cef_string_t* defaultValue, int* retval, cef_string_t* result) { + // 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: retval; type: bool_byref + DCHECK(retval); + if (!retval) + return 0; + // Verify param: result; type: string_byref + DCHECK(result); + if (!result) + return 0; + // Unverified params: message, defaultValue + + // Translate param: retval; type: bool_byref + bool retvalBool = (retval && *retval)?true:false; + // Translate param: result; type: string_byref + CefString resultStr(result); + + // Execute + bool _retval = CefJSDialogHandlerCppToC::Get(self)->OnJSPrompt( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefString(message), + CefString(defaultValue), + retvalBool, + resultStr); + + // Restore param: retval; type: bool_byref + if (retval) + *retval = retvalBool?true:false; + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefJSDialogHandlerCppToC::CefJSDialogHandlerCppToC(CefJSDialogHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_jsalert = jsdialog_handler_on_jsalert; + struct_.struct_.on_jsconfirm = jsdialog_handler_on_jsconfirm; + struct_.struct_.on_jsprompt = jsdialog_handler_on_jsprompt; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/jsdialog_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/jsdialog_handler_cpptoc.h new file mode 100644 index 000000000..af58e7049 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/jsdialog_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefJSDialogHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_JSDIALOG_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/keyboard_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/keyboard_handler_cpptoc.cc new file mode 100644 index 000000000..dbced2bed --- /dev/null +++ b/cef1/libcef_dll/cpptoc/keyboard_handler_cpptoc.cc @@ -0,0 +1,59 @@ +// 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/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_key_event( + struct _cef_keyboard_handler_t* self, cef_browser_t* browser, + enum cef_handler_keyevent_type_t type, int code, int modifiers, + int isSystemKey, int isAfterJavaScript) { + // 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 = CefKeyboardHandlerCppToC::Get(self)->OnKeyEvent( + CefBrowserCToCpp::Wrap(browser), + type, + code, + modifiers, + isSystemKey?true:false, + isAfterJavaScript?true:false); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefKeyboardHandlerCppToC::CefKeyboardHandlerCppToC(CefKeyboardHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_key_event = keyboard_handler_on_key_event; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/keyboard_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/keyboard_handler_cpptoc.h new file mode 100644 index 000000000..4685a74ea --- /dev/null +++ b/cef1/libcef_dll/cpptoc/keyboard_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefKeyboardHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_KEYBOARD_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/life_span_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/life_span_handler_cpptoc.cc new file mode 100644 index 000000000..85b1e2708 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/life_span_handler_cpptoc.cc @@ -0,0 +1,191 @@ +// 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/client_cpptoc.h" +#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_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* parentBrowser, + const struct _cef_popup_features_t* popupFeatures, + cef_window_info_t* windowInfo, const cef_string_t* url, + cef_client_t** client, struct _cef_browser_settings_t* settings) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return 0; + // Verify param: parentBrowser; type: refptr_diff + DCHECK(parentBrowser); + if (!parentBrowser) + 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; + // Unverified params: url + + // 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); + + // Execute + bool _retval = CefLifeSpanHandlerCppToC::Get(self)->OnBeforePopup( + CefBrowserCToCpp::Wrap(parentBrowser), + popupFeaturesObj, + windowInfoObj, + CefString(url), + clientPtr, + settingsObj); + + // 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); + + // 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/life_span_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/life_span_handler_cpptoc.h new file mode 100644 index 000000000..247d131bc --- /dev/null +++ b/cef1/libcef_dll/cpptoc/life_span_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefLifeSpanHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_LIFE_SPAN_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/load_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/load_handler_cpptoc.cc new file mode 100644 index 000000000..14c31cfa3 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/load_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_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); +} + +int CEF_CALLBACK load_handler_on_load_error(struct _cef_load_handler_t* self, + cef_browser_t* browser, cef_frame_t* frame, + enum cef_handler_errorcode_t errorCode, const cef_string_t* failedUrl, + cef_string_t* errorText) { + // 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: failedUrl; type: string_byref_const + DCHECK(failedUrl); + if (!failedUrl) + return 0; + // Verify param: errorText; type: string_byref + DCHECK(errorText); + if (!errorText) + return 0; + + // Translate param: errorText; type: string_byref + CefString errorTextStr(errorText); + + // Execute + bool _retval = CefLoadHandlerCppToC::Get(self)->OnLoadError( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + errorCode, + CefString(failedUrl), + errorTextStr); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefLoadHandlerCppToC::CefLoadHandlerCppToC(CefLoadHandler* cls) + : CefCppToC(cls) { + 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/load_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/load_handler_cpptoc.h new file mode 100644 index 000000000..f5af7e734 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/load_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefLoadHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_LOAD_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/menu_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/menu_handler_cpptoc.cc new file mode 100644 index 000000000..d1c000f90 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/menu_handler_cpptoc.cc @@ -0,0 +1,110 @@ +// 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/menu_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK menu_handler_on_before_menu(struct _cef_menu_handler_t* self, + cef_browser_t* browser, const struct _cef_menu_info_t* menuInfo) { + // 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: menuInfo; type: struct_byref_const + DCHECK(menuInfo); + if (!menuInfo) + return 0; + + // Translate param: menuInfo; type: struct_byref_const + CefMenuInfo menuInfoObj; + if (menuInfo) + menuInfoObj.Set(*menuInfo, false); + + // Execute + bool _retval = CefMenuHandlerCppToC::Get(self)->OnBeforeMenu( + CefBrowserCToCpp::Wrap(browser), + menuInfoObj); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK menu_handler_get_menu_label(struct _cef_menu_handler_t* self, + cef_browser_t* browser, enum cef_menu_id_t menuId, cef_string_t* label) { + // 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: label; type: string_byref + DCHECK(label); + if (!label) + return; + + // Translate param: label; type: string_byref + CefString labelStr(label); + + // Execute + CefMenuHandlerCppToC::Get(self)->GetMenuLabel( + CefBrowserCToCpp::Wrap(browser), + menuId, + labelStr); +} + +int CEF_CALLBACK menu_handler_on_menu_action(struct _cef_menu_handler_t* self, + cef_browser_t* browser, enum cef_menu_id_t menuId) { + // 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 = CefMenuHandlerCppToC::Get(self)->OnMenuAction( + CefBrowserCToCpp::Wrap(browser), + menuId); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefMenuHandlerCppToC::CefMenuHandlerCppToC(CefMenuHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_before_menu = menu_handler_on_before_menu; + struct_.struct_.get_menu_label = menu_handler_get_menu_label; + struct_.struct_.on_menu_action = menu_handler_on_menu_action; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/menu_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/menu_handler_cpptoc.h new file mode 100644 index 000000000..20086f438 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/menu_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_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_menu_handler.h" +#include "include/capi/cef_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 CefMenuHandlerCppToC + : public CefCppToC { + public: + explicit CefMenuHandlerCppToC(CefMenuHandler* cls); + virtual ~CefMenuHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_MENU_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/permission_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/permission_handler_cpptoc.cc new file mode 100644 index 000000000..5558de8eb --- /dev/null +++ b/cef1/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/cef1/libcef_dll/cpptoc/permission_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/permission_handler_cpptoc.h new file mode 100644 index 000000000..a7e2f44af --- /dev/null +++ b/cef1/libcef_dll/cpptoc/permission_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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 "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/cef1/libcef_dll/cpptoc/post_data_cpptoc.cc b/cef1/libcef_dll/cpptoc/post_data_cpptoc.cc new file mode 100644 index 000000000..add00ea77 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/post_data_cpptoc.cc @@ -0,0 +1,148 @@ +// 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/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::CreatePostData(); + + // Return type: refptr_same + return CefPostDataCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_.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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/post_data_cpptoc.h b/cef1/libcef_dll/cpptoc/post_data_cpptoc.h new file mode 100644 index 000000000..a97ebbecc --- /dev/null +++ b/cef1/libcef_dll/cpptoc/post_data_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefPostDataCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_POST_DATA_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/post_data_element_cpptoc.cc b/cef1/libcef_dll/cpptoc/post_data_element_cpptoc.cc new file mode 100644 index 000000000..cddf7c4a9 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/post_data_element_cpptoc.cc @@ -0,0 +1,165 @@ +// 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/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::CreatePostDataElement(); + + // Return type: refptr_same + return CefPostDataElementCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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); +} + +enum 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_.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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/post_data_element_cpptoc.h b/cef1/libcef_dll/cpptoc/post_data_element_cpptoc.h new file mode 100644 index 000000000..72d14e436 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/post_data_element_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefPostDataElementCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_POST_DATA_ELEMENT_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/print_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/print_handler_cpptoc.cc new file mode 100644 index 000000000..d72e151ff --- /dev/null +++ b/cef1/libcef_dll/cpptoc/print_handler_cpptoc.cc @@ -0,0 +1,164 @@ +// 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/print_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 print_handler_get_print_options( + struct _cef_print_handler_t* self, cef_browser_t* browser, + struct _cef_print_options_t* printOptions) { + // 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: printOptions; type: struct_byref + DCHECK(printOptions); + if (!printOptions) + return 0; + + // Translate param: printOptions; type: struct_byref + CefPrintOptions printOptionsObj; + if (printOptions) + printOptionsObj.AttachTo(*printOptions); + + // Execute + bool _retval = CefPrintHandlerCppToC::Get(self)->GetPrintOptions( + CefBrowserCToCpp::Wrap(browser), + printOptionsObj); + + // Restore param: printOptions; type: struct_byref + if (printOptions) + printOptionsObj.DetachTo(*printOptions); + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK print_handler_get_print_header_footer( + struct _cef_print_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, const cef_print_info_t* printInfo, + const cef_string_t* url, const cef_string_t* title, int currentPage, + int maxPages, cef_string_t* topLeft, cef_string_t* topCenter, + cef_string_t* topRight, cef_string_t* bottomLeft, + cef_string_t* bottomCenter, cef_string_t* bottomRight) { + // 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: printInfo; type: struct_byref_const + DCHECK(printInfo); + if (!printInfo) + return 0; + // Verify param: url; type: string_byref_const + DCHECK(url); + if (!url) + return 0; + // Verify param: title; type: string_byref_const + DCHECK(title); + if (!title) + return 0; + // Verify param: topLeft; type: string_byref + DCHECK(topLeft); + if (!topLeft) + return 0; + // Verify param: topCenter; type: string_byref + DCHECK(topCenter); + if (!topCenter) + return 0; + // Verify param: topRight; type: string_byref + DCHECK(topRight); + if (!topRight) + return 0; + // Verify param: bottomLeft; type: string_byref + DCHECK(bottomLeft); + if (!bottomLeft) + return 0; + // Verify param: bottomCenter; type: string_byref + DCHECK(bottomCenter); + if (!bottomCenter) + return 0; + // Verify param: bottomRight; type: string_byref + DCHECK(bottomRight); + if (!bottomRight) + return 0; + + // Translate param: printInfo; type: struct_byref_const + CefPrintInfo printInfoObj; + if (printInfo) + printInfoObj.Set(*printInfo, false); + // Translate param: topLeft; type: string_byref + CefString topLeftStr(topLeft); + // Translate param: topCenter; type: string_byref + CefString topCenterStr(topCenter); + // Translate param: topRight; type: string_byref + CefString topRightStr(topRight); + // Translate param: bottomLeft; type: string_byref + CefString bottomLeftStr(bottomLeft); + // Translate param: bottomCenter; type: string_byref + CefString bottomCenterStr(bottomCenter); + // Translate param: bottomRight; type: string_byref + CefString bottomRightStr(bottomRight); + + // Execute + bool _retval = CefPrintHandlerCppToC::Get(self)->GetPrintHeaderFooter( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + printInfoObj, + CefString(url), + CefString(title), + currentPage, + maxPages, + topLeftStr, + topCenterStr, + topRightStr, + bottomLeftStr, + bottomCenterStr, + bottomRightStr); + + // Return type: bool + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefPrintHandlerCppToC::CefPrintHandlerCppToC(CefPrintHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.get_print_options = print_handler_get_print_options; + struct_.struct_.get_print_header_footer = + print_handler_get_print_header_footer; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/print_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/print_handler_cpptoc.h new file mode 100644 index 000000000..9289aa503 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/print_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefPrintHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PRINT_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/proxy_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/proxy_handler_cpptoc.cc new file mode 100644 index 000000000..2243abd5b --- /dev/null +++ b/cef1/libcef_dll/cpptoc/proxy_handler_cpptoc.cc @@ -0,0 +1,63 @@ +// 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/proxy_handler_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK proxy_handler_get_proxy_for_url( + struct _cef_proxy_handler_t* self, const cef_string_t* url, + struct _cef_proxy_info_t* proxy_info) { + // 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: proxy_info; type: struct_byref + DCHECK(proxy_info); + if (!proxy_info) + return; + + // Translate param: proxy_info; type: struct_byref + CefProxyInfo proxy_infoObj; + if (proxy_info) + proxy_infoObj.AttachTo(*proxy_info); + + // Execute + CefProxyHandlerCppToC::Get(self)->GetProxyForUrl( + CefString(url), + proxy_infoObj); + + // Restore param: proxy_info; type: struct_byref + if (proxy_info) + proxy_infoObj.DetachTo(*proxy_info); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefProxyHandlerCppToC::CefProxyHandlerCppToC(CefProxyHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.get_proxy_for_url = proxy_handler_get_proxy_for_url; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/proxy_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/proxy_handler_cpptoc.h new file mode 100644 index 000000000..7dd0b64ad --- /dev/null +++ b/cef1/libcef_dll/cpptoc/proxy_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_PROXY_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_PROXY_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_proxy_handler.h" +#include "include/capi/cef_proxy_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 CefProxyHandlerCppToC + : public CefCppToC { + public: + explicit CefProxyHandlerCppToC(CefProxyHandler* cls); + virtual ~CefProxyHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_PROXY_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/read_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/read_handler_cpptoc.cc new file mode 100644 index 000000000..6ac89f694 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/read_handler_cpptoc.cc @@ -0,0 +1,100 @@ +// 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/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; +} + + +// 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/read_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/read_handler_cpptoc.h new file mode 100644 index 000000000..b4ca3c0c3 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/read_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefReadHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_READ_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/render_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/render_handler_cpptoc.cc new file mode 100644 index 000000000..1aec01198 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/render_handler_cpptoc.cc @@ -0,0 +1,250 @@ +// 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/render_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_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)->GetScreenRect( + 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; +} + +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, enum cef_paint_element_type_t type, + size_t dirtyRectsCount, cef_rect_t const* dirtyRects, + const void* buffer) { + // 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); +} + +void CEF_CALLBACK render_handler_on_cursor_change( + struct _cef_render_handler_t* self, cef_browser_t* browser, + cef_cursor_handle_t cursor) { + // 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)->OnCursorChange( + CefBrowserCToCpp::Wrap(browser), + cursor); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRenderHandlerCppToC::CefRenderHandlerCppToC(CefRenderHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.get_view_rect = render_handler_get_view_rect; + struct_.struct_.get_screen_rect = render_handler_get_screen_rect; + struct_.struct_.get_screen_point = render_handler_get_screen_point; + 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/render_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/render_handler_cpptoc.h new file mode 100644 index 000000000..8c9b65c2a --- /dev/null +++ b/cef1/libcef_dll/cpptoc/render_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefRenderHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RENDER_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/request_cpptoc.cc b/cef1/libcef_dll/cpptoc/request_cpptoc.cc new file mode 100644 index 000000000..6d554cc1d --- /dev/null +++ b/cef1/libcef_dll/cpptoc/request_cpptoc.cc @@ -0,0 +1,295 @@ +// 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/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::CreateRequest(); + + // Return type: refptr_same + return CefRequestCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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); +} + +enum cef_weburlrequest_flags_t CEF_CALLBACK request_get_flags( + struct _cef_request_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return WUR_FLAG_NONE; + + // Execute + cef_weburlrequest_flags_t _retval = CefRequestCppToC::Get(self)->GetFlags(); + + // Return type: simple + return _retval; +} + +void CEF_CALLBACK request_set_flags(struct _cef_request_t* self, + enum cef_weburlrequest_flags_t 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)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefRequestCppToC::CefRequestCppToC(CefRequest* cls) + : CefCppToC(cls) { + 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/request_cpptoc.h b/cef1/libcef_dll/cpptoc/request_cpptoc.h new file mode 100644 index 000000000..00c9c2042 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/request_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefRequestCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_REQUEST_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/request_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/request_handler_cpptoc.cc new file mode 100644 index 000000000..9dfe7aed7 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/request_handler_cpptoc.cc @@ -0,0 +1,399 @@ +// 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/content_filter_cpptoc.h" +#include "libcef_dll/cpptoc/download_handler_cpptoc.h" +#include "libcef_dll/cpptoc/request_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/response_ctocpp.h" +#include "libcef_dll/ctocpp/stream_reader_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, + enum cef_handler_navtype_t navType, int isRedirect) { + // 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), + navType, + isRedirect?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_request_t* request, cef_string_t* redirectUrl, + struct _cef_stream_reader_t** resourceStream, + struct _cef_response_t* response, int loadFlags) { + // 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: request; type: refptr_diff + DCHECK(request); + if (!request) + return 0; + // Verify param: redirectUrl; type: string_byref + DCHECK(redirectUrl); + if (!redirectUrl) + return 0; + // Verify param: resourceStream; type: refptr_diff_byref + DCHECK(resourceStream); + if (!resourceStream) + return 0; + // Verify param: response; type: refptr_diff + DCHECK(response); + if (!response) + return 0; + + // Translate param: redirectUrl; type: string_byref + CefString redirectUrlStr(redirectUrl); + // Translate param: resourceStream; type: refptr_diff_byref + CefRefPtr resourceStreamPtr; + if (resourceStream && *resourceStream) + resourceStreamPtr = CefStreamReaderCToCpp::Wrap(*resourceStream); + CefStreamReader* resourceStreamOrig = resourceStreamPtr.get(); + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnBeforeResourceLoad( + CefBrowserCToCpp::Wrap(browser), + CefRequestCToCpp::Wrap(request), + redirectUrlStr, + resourceStreamPtr, + CefResponseCToCpp::Wrap(response), + loadFlags); + + // Restore param: resourceStream; type: refptr_diff_byref + if (resourceStream) { + if (resourceStreamPtr.get()) { + if (resourceStreamPtr.get() != resourceStreamOrig) { + *resourceStream = CefStreamReaderCToCpp::Unwrap(resourceStreamPtr); + } + } else { + *resourceStream = NULL; + } + } + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK request_handler_on_resource_redirect( + struct _cef_request_handler_t* self, cef_browser_t* browser, + 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: 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), + CefString(old_url), + new_urlStr); +} + +void CEF_CALLBACK request_handler_on_resource_response( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* url, struct _cef_response_t* response, + cef_content_filter_t** filter) { + // 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: response; type: refptr_diff + DCHECK(response); + if (!response) + return; + // Verify param: filter; type: refptr_same_byref + DCHECK(filter); + if (!filter) + return; + + // Translate param: filter; type: refptr_same_byref + CefRefPtr filterPtr; + if (filter && *filter) + filterPtr = CefContentFilterCppToC::Unwrap(*filter); + CefContentFilter* filterOrig = filterPtr.get(); + + // Execute + CefRequestHandlerCppToC::Get(self)->OnResourceResponse( + CefBrowserCToCpp::Wrap(browser), + CefString(url), + CefResponseCToCpp::Wrap(response), + filterPtr); + + // Restore param: filter; type: refptr_same_byref + if (filter) { + if (filterPtr.get()) { + if (filterPtr.get() != filterOrig) { + *filter = CefContentFilterCppToC::Wrap(filterPtr); + } + } else { + *filter = NULL; + } + } +} + +int CEF_CALLBACK request_handler_on_protocol_execution( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* url, int* allowOSExecution) { + // 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: url; type: string_byref_const + DCHECK(url); + if (!url) + return 0; + // Verify param: allowOSExecution; type: bool_byref + DCHECK(allowOSExecution); + if (!allowOSExecution) + return 0; + + // Translate param: allowOSExecution; type: bool_byref + bool allowOSExecutionBool = ( + allowOSExecution && *allowOSExecution)?true:false; + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->OnProtocolExecution( + CefBrowserCToCpp::Wrap(browser), + CefString(url), + allowOSExecutionBool); + + // Restore param: allowOSExecution; type: bool_byref + if (allowOSExecution) + *allowOSExecution = allowOSExecutionBool?true:false; + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK request_handler_get_download_handler( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* mimeType, const cef_string_t* fileName, + int64 contentLength, cef_download_handler_t** handler) { + // 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: mimeType; type: string_byref_const + DCHECK(mimeType); + if (!mimeType) + return 0; + // Verify param: fileName; type: string_byref_const + DCHECK(fileName); + if (!fileName) + return 0; + // Verify param: handler; type: refptr_same_byref + DCHECK(handler); + if (!handler) + return 0; + + // Translate param: handler; type: refptr_same_byref + CefRefPtr handlerPtr; + if (handler && *handler) + handlerPtr = CefDownloadHandlerCppToC::Unwrap(*handler); + CefDownloadHandler* handlerOrig = handlerPtr.get(); + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->GetDownloadHandler( + CefBrowserCToCpp::Wrap(browser), + CefString(mimeType), + CefString(fileName), + contentLength, + handlerPtr); + + // Restore param: handler; type: refptr_same_byref + if (handler) { + if (handlerPtr.get()) { + if (handlerPtr.get() != handlerOrig) { + *handler = CefDownloadHandlerCppToC::Wrap(handlerPtr); + } + } else { + *handler = NULL; + } + } + + // Return type: bool + return _retval; +} + +int CEF_CALLBACK request_handler_get_auth_credentials( + struct _cef_request_handler_t* self, cef_browser_t* browser, int isProxy, + const cef_string_t* host, int port, const cef_string_t* realm, + const cef_string_t* scheme, cef_string_t* username, + cef_string_t* password) { + // 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: 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: username; type: string_byref + DCHECK(username); + if (!username) + return 0; + // Verify param: password; type: string_byref + DCHECK(password); + if (!password) + return 0; + // Unverified params: realm + + // Translate param: username; type: string_byref + CefString usernameStr(username); + // Translate param: password; type: string_byref + CefString passwordStr(password); + + // Execute + bool _retval = CefRequestHandlerCppToC::Get(self)->GetAuthCredentials( + CefBrowserCToCpp::Wrap(browser), + isProxy?true:false, + CefString(host), + port, + CefString(realm), + CefString(scheme), + usernameStr, + passwordStr); + + // Return type: bool + return _retval; +} + +cef_cookie_manager_t* CEF_CALLBACK request_handler_get_cookie_manager( + struct _cef_request_handler_t* self, cef_browser_t* browser, + const cef_string_t* main_url) { + // 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: main_url; type: string_byref_const + DCHECK(main_url); + if (!main_url) + return NULL; + + // Execute + CefRefPtr _retval = CefRequestHandlerCppToC::Get( + self)->GetCookieManager( + CefBrowserCToCpp::Wrap(browser), + CefString(main_url)); + + // Return type: refptr_diff + return CefCookieManagerCToCpp::Unwrap(_retval); +} + + +// 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_.on_resource_redirect = request_handler_on_resource_redirect; + struct_.struct_.on_resource_response = request_handler_on_resource_response; + struct_.struct_.on_protocol_execution = request_handler_on_protocol_execution; + struct_.struct_.get_download_handler = request_handler_get_download_handler; + struct_.struct_.get_auth_credentials = request_handler_get_auth_credentials; + struct_.struct_.get_cookie_manager = request_handler_get_cookie_manager; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/request_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/request_handler_cpptoc.h new file mode 100644 index 000000000..1b4c79160 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/request_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefRequestHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_REQUEST_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc new file mode 100644 index 000000000..23dd259b3 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.cc @@ -0,0 +1,98 @@ +// 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/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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h new file mode 100644 index 000000000..3b11fb62c --- /dev/null +++ b/cef1/libcef_dll/cpptoc/resource_bundle_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefResourceBundleHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RESOURCE_BUNDLE_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/response_cpptoc.cc b/cef1/libcef_dll/cpptoc/response_cpptoc.cc new file mode 100644 index 000000000..be51c228f --- /dev/null +++ b/cef1/libcef_dll/cpptoc/response_cpptoc.cc @@ -0,0 +1,196 @@ +// 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/response_cpptoc.h" +#include "libcef_dll/transfer_util.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_.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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/response_cpptoc.h b/cef1/libcef_dll/cpptoc/response_cpptoc.h new file mode 100644 index 000000000..7397974e6 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/response_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefResponseCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_RESPONSE_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/scheme_handler_callback_cpptoc.cc b/cef1/libcef_dll/cpptoc/scheme_handler_callback_cpptoc.cc new file mode 100644 index 000000000..e67e86c9a --- /dev/null +++ b/cef1/libcef_dll/cpptoc/scheme_handler_callback_cpptoc.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_handler_callback_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK scheme_handler_callback_headers_available( + struct _cef_scheme_handler_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefSchemeHandlerCallbackCppToC::Get(self)->HeadersAvailable(); +} + +void CEF_CALLBACK scheme_handler_callback_bytes_available( + struct _cef_scheme_handler_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefSchemeHandlerCallbackCppToC::Get(self)->BytesAvailable(); +} + +void CEF_CALLBACK scheme_handler_callback_cancel( + struct _cef_scheme_handler_callback_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefSchemeHandlerCallbackCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeHandlerCallbackCppToC::CefSchemeHandlerCallbackCppToC( + CefSchemeHandlerCallback* cls) + : CefCppToC(cls) { + struct_.struct_.headers_available = scheme_handler_callback_headers_available; + struct_.struct_.bytes_available = scheme_handler_callback_bytes_available; + struct_.struct_.cancel = scheme_handler_callback_cancel; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/scheme_handler_callback_cpptoc.h b/cef1/libcef_dll/cpptoc/scheme_handler_callback_cpptoc.h new file mode 100644 index 000000000..3dd5d462b --- /dev/null +++ b/cef1/libcef_dll/cpptoc/scheme_handler_callback_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_CALLBACK_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_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_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 CefSchemeHandlerCallbackCppToC + : public CefCppToC { + public: + explicit CefSchemeHandlerCallbackCppToC(CefSchemeHandlerCallback* cls); + virtual ~CefSchemeHandlerCallbackCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_CALLBACK_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/scheme_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/scheme_handler_cpptoc.cc new file mode 100644 index 000000000..a613a3cf0 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/scheme_handler_cpptoc.cc @@ -0,0 +1,150 @@ +// 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/scheme_handler_cpptoc.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/response_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_handler_callback_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +int CEF_CALLBACK scheme_handler_process_request( + struct _cef_scheme_handler_t* self, cef_request_t* request, + cef_scheme_handler_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 = CefSchemeHandlerCppToC::Get(self)->ProcessRequest( + CefRequestCToCpp::Wrap(request), + CefSchemeHandlerCallbackCToCpp::Wrap(callback)); + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK scheme_handler_get_response_headers( + struct _cef_scheme_handler_t* self, 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 + CefSchemeHandlerCppToC::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 scheme_handler_read_response( + struct _cef_scheme_handler_t* self, void* data_out, int bytes_to_read, + int* bytes_read, cef_scheme_handler_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 = CefSchemeHandlerCppToC::Get(self)->ReadResponse( + data_out, + bytes_to_read, + bytes_readVal, + CefSchemeHandlerCallbackCToCpp::Wrap(callback)); + + // Restore param: bytes_read; type: simple_byref + if (bytes_read) + *bytes_read = bytes_readVal; + + // Return type: bool + return _retval; +} + +void CEF_CALLBACK scheme_handler_cancel(struct _cef_scheme_handler_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefSchemeHandlerCppToC::Get(self)->Cancel(); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeHandlerCppToC::CefSchemeHandlerCppToC(CefSchemeHandler* cls) + : CefCppToC( + cls) { + struct_.struct_.process_request = scheme_handler_process_request; + struct_.struct_.get_response_headers = scheme_handler_get_response_headers; + struct_.struct_.read_response = scheme_handler_read_response; + struct_.struct_.cancel = scheme_handler_cancel; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/scheme_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/scheme_handler_cpptoc.h new file mode 100644 index 000000000..e38e705f1 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/scheme_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_SCHEME_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_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 CefSchemeHandlerCppToC + : public CefCppToC { + public: + explicit CefSchemeHandlerCppToC(CefSchemeHandler* cls); + virtual ~CefSchemeHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc b/cef1/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.cc new file mode 100644 index 000000000..258543110 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/scheme_handler_factory_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/scheme_handler_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +struct _cef_scheme_handler_t* CEF_CALLBACK scheme_handler_factory_create( + struct _cef_scheme_handler_factory_t* self, cef_browser_t* browser, + 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: browser; type: refptr_diff + DCHECK(browser); + if (!browser) + 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; + + // Execute + CefRefPtr _retval = CefSchemeHandlerFactoryCppToC::Get( + self)->Create( + CefBrowserCToCpp::Wrap(browser), + CefString(scheme_name), + CefRequestCToCpp::Wrap(request)); + + // Return type: refptr_same + return CefSchemeHandlerCppToC::Wrap(_retval); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefSchemeHandlerFactoryCppToC::CefSchemeHandlerFactoryCppToC( + CefSchemeHandlerFactory* cls) + : CefCppToC(cls) { + struct_.struct_.create = scheme_handler_factory_create; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h b/cef1/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h new file mode 100644 index 000000000..c47b338da --- /dev/null +++ b/cef1/libcef_dll/cpptoc/scheme_handler_factory_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefSchemeHandlerFactoryCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_SCHEME_HANDLER_FACTORY_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/stream_reader_cpptoc.cc b/cef1/libcef_dll/cpptoc/stream_reader_cpptoc.cc new file mode 100644 index 000000000..bfaf07f2b --- /dev/null +++ b/cef1/libcef_dll/cpptoc/stream_reader_cpptoc.cc @@ -0,0 +1,157 @@ +// 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/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; +} + + +// 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/stream_reader_cpptoc.h b/cef1/libcef_dll/cpptoc/stream_reader_cpptoc.h new file mode 100644 index 000000000..3dee6cad0 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/stream_reader_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefStreamReaderCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_STREAM_READER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/stream_writer_cpptoc.cc b/cef1/libcef_dll/cpptoc/stream_writer_cpptoc.cc new file mode 100644 index 000000000..6c4c5b2dd --- /dev/null +++ b/cef1/libcef_dll/cpptoc/stream_writer_cpptoc.cc @@ -0,0 +1,139 @@ +// 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/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; +} + + +// 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/stream_writer_cpptoc.h b/cef1/libcef_dll/cpptoc/stream_writer_cpptoc.h new file mode 100644 index 000000000..b10d2f670 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/stream_writer_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefStreamWriterCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_STREAM_WRITER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/task_cpptoc.cc b/cef1/libcef_dll/cpptoc/task_cpptoc.cc new file mode 100644 index 000000000..a5e31e6b1 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/task_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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, + cef_thread_id_t threadId) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefTaskCppToC::Get(self)->Execute( + threadId); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefTaskCppToC::CefTaskCppToC(CefTask* cls) + : CefCppToC(cls) { + struct_.struct_.execute = task_execute; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/task_cpptoc.h b/cef1/libcef_dll/cpptoc/task_cpptoc.h new file mode 100644 index 000000000..8f2e2fc2e --- /dev/null +++ b/cef1/libcef_dll/cpptoc/task_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefTaskCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_TASK_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8accessor_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8accessor_cpptoc.cc new file mode 100644 index 000000000..d533fcf06 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8accessor_cpptoc.cc @@ -0,0 +1,126 @@ +// 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/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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8accessor_cpptoc.h b/cef1/libcef_dll/cpptoc/v8accessor_cpptoc.h new file mode 100644 index 000000000..b0dbb8ebd --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8accessor_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefV8AccessorCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8ACCESSOR_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8context_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8context_cpptoc.cc new file mode 100644 index 000000000..6aa3149ee --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8context_cpptoc.cc @@ -0,0 +1,228 @@ +// 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/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_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_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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8context_cpptoc.h b/cef1/libcef_dll/cpptoc/v8context_cpptoc.h new file mode 100644 index 000000000..c19fff2ad --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8context_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefV8ContextCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8CONTEXT_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8context_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8context_handler_cpptoc.cc new file mode 100644 index 000000000..2c426834c --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8context_handler_cpptoc.cc @@ -0,0 +1,91 @@ +// 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/v8context_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK v8context_handler_on_context_created( + struct _cef_v8context_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, 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 + CefV8ContextHandlerCppToC::Get(self)->OnContextCreated( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefV8ContextCToCpp::Wrap(context)); +} + +void CEF_CALLBACK v8context_handler_on_context_released( + struct _cef_v8context_handler_t* self, cef_browser_t* browser, + cef_frame_t* frame, 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 + CefV8ContextHandlerCppToC::Get(self)->OnContextReleased( + CefBrowserCToCpp::Wrap(browser), + CefFrameCToCpp::Wrap(frame), + CefV8ContextCToCpp::Wrap(context)); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefV8ContextHandlerCppToC::CefV8ContextHandlerCppToC(CefV8ContextHandler* cls) + : CefCppToC(cls) { + struct_.struct_.on_context_created = v8context_handler_on_context_created; + struct_.struct_.on_context_released = v8context_handler_on_context_released; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8context_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/v8context_handler_cpptoc.h new file mode 100644 index 000000000..d77b908e2 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8context_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_HANDLER_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_V8CONTEXT_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_v8context_handler.h" +#include "include/capi/cef_v8context_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 CefV8ContextHandlerCppToC + : public CefCppToC { + public: + explicit CefV8ContextHandlerCppToC(CefV8ContextHandler* cls); + virtual ~CefV8ContextHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8CONTEXT_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8exception_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8exception_cpptoc.cc new file mode 100644 index 000000000..264fa8da9 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8exception_cpptoc.cc @@ -0,0 +1,154 @@ +// 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/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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8exception_cpptoc.h b/cef1/libcef_dll/cpptoc/v8exception_cpptoc.h new file mode 100644 index 000000000..040d782a4 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8exception_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefV8ExceptionCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8EXCEPTION_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8handler_cpptoc.cc new file mode 100644 index 000000000..08f003247 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8handler_cpptoc.cc @@ -0,0 +1,99 @@ +// 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/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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8handler_cpptoc.h b/cef1/libcef_dll/cpptoc/v8handler_cpptoc.h new file mode 100644 index 000000000..1dd0886e9 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8handler_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefV8HandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8stack_frame_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8stack_frame_cpptoc.cc new file mode 100644 index 000000000..3da6bc6c8 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8stack_frame_cpptoc.cc @@ -0,0 +1,142 @@ +// 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/v8stack_frame_cpptoc.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +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_.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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8stack_frame_cpptoc.h b/cef1/libcef_dll/cpptoc/v8stack_frame_cpptoc.h new file mode 100644 index 000000000..d5ee79a23 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8stack_frame_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefV8StackFrameCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8STACK_FRAME_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8stack_trace_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8stack_trace_cpptoc.cc new file mode 100644 index 000000000..c7c884c5a --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8stack_trace_cpptoc.cc @@ -0,0 +1,79 @@ +// 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/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_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_.get_frame_count = v8stack_trace_get_frame_count; + struct_.struct_.get_frame = v8stack_trace_get_frame; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8stack_trace_cpptoc.h b/cef1/libcef_dll/cpptoc/v8stack_trace_cpptoc.h new file mode 100644 index 000000000..b2b65352f --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8stack_trace_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefV8StackTraceCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8STACK_TRACE_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/v8value_cpptoc.cc b/cef1/libcef_dll/cpptoc/v8value_cpptoc.cc new file mode 100644 index 000000000..0ebed8c85 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8value_cpptoc.cc @@ -0,0 +1,973 @@ +// 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/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_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; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // 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; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return 0; + + // 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; + // Verify param: key; type: string_byref_const + DCHECK(key); + if (!key) + return NULL; + + // 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, + enum cef_v8_propertyattribute_t attribute) { + // 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 = 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, enum cef_v8_accesscontrol_t settings, + enum cef_v8_propertyattribute_t attribute) { + // 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 = 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_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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/v8value_cpptoc.h b/cef1/libcef_dll/cpptoc/v8value_cpptoc.h new file mode 100644 index 000000000..086bda36d --- /dev/null +++ b/cef1/libcef_dll/cpptoc/v8value_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefV8ValueCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_V8VALUE_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/web_plugin_info_cpptoc.cc b/cef1/libcef_dll/cpptoc/web_plugin_info_cpptoc.cc new file mode 100644 index 000000000..46caf75f6 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/web_plugin_info_cpptoc.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/web_plugin_info_cpptoc.h b/cef1/libcef_dll/cpptoc/web_plugin_info_cpptoc.h new file mode 100644 index 000000000..9ede6a894 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/web_plugin_info_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefWebPluginInfoCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WEB_PLUGIN_INFO_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/web_urlrequest_client_cpptoc.cc b/cef1/libcef_dll/cpptoc/web_urlrequest_client_cpptoc.cc new file mode 100644 index 000000000..d576345e0 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/web_urlrequest_client_cpptoc.cc @@ -0,0 +1,174 @@ +// 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/web_urlrequest_client_cpptoc.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/response_ctocpp.h" +#include "libcef_dll/ctocpp/web_urlrequest_ctocpp.h" + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK web_urlrequest_client_on_state_change( + struct _cef_web_urlrequest_client_t* self, cef_web_urlrequest_t* requester, + enum cef_weburlrequest_state_t state) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: requester; type: refptr_diff + DCHECK(requester); + if (!requester) + return; + + // Execute + CefWebURLRequestClientCppToC::Get(self)->OnStateChange( + CefWebURLRequestCToCpp::Wrap(requester), + state); +} + +void CEF_CALLBACK web_urlrequest_client_on_redirect( + struct _cef_web_urlrequest_client_t* self, cef_web_urlrequest_t* requester, + cef_request_t* request, cef_response_t* response) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: requester; type: refptr_diff + DCHECK(requester); + if (!requester) + return; + // Verify param: request; type: refptr_diff + DCHECK(request); + if (!request) + return; + // Verify param: response; type: refptr_diff + DCHECK(response); + if (!response) + return; + + // Execute + CefWebURLRequestClientCppToC::Get(self)->OnRedirect( + CefWebURLRequestCToCpp::Wrap(requester), + CefRequestCToCpp::Wrap(request), + CefResponseCToCpp::Wrap(response)); +} + +void CEF_CALLBACK web_urlrequest_client_on_headers_received( + struct _cef_web_urlrequest_client_t* self, cef_web_urlrequest_t* requester, + cef_response_t* response) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: requester; type: refptr_diff + DCHECK(requester); + if (!requester) + return; + // Verify param: response; type: refptr_diff + DCHECK(response); + if (!response) + return; + + // Execute + CefWebURLRequestClientCppToC::Get(self)->OnHeadersReceived( + CefWebURLRequestCToCpp::Wrap(requester), + CefResponseCToCpp::Wrap(response)); +} + +void CEF_CALLBACK web_urlrequest_client_on_progress( + struct _cef_web_urlrequest_client_t* self, cef_web_urlrequest_t* requester, + uint64 bytesSent, uint64 totalBytesToBeSent) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: requester; type: refptr_diff + DCHECK(requester); + if (!requester) + return; + + // Execute + CefWebURLRequestClientCppToC::Get(self)->OnProgress( + CefWebURLRequestCToCpp::Wrap(requester), + bytesSent, + totalBytesToBeSent); +} + +void CEF_CALLBACK web_urlrequest_client_on_data( + struct _cef_web_urlrequest_client_t* self, cef_web_urlrequest_t* requester, + const void* data, int dataLength) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: requester; type: refptr_diff + DCHECK(requester); + if (!requester) + return; + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return; + + // Execute + CefWebURLRequestClientCppToC::Get(self)->OnData( + CefWebURLRequestCToCpp::Wrap(requester), + data, + dataLength); +} + +void CEF_CALLBACK web_urlrequest_client_on_error( + struct _cef_web_urlrequest_client_t* self, cef_web_urlrequest_t* requester, + enum cef_handler_errorcode_t errorCode) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + // Verify param: requester; type: refptr_diff + DCHECK(requester); + if (!requester) + return; + + // Execute + CefWebURLRequestClientCppToC::Get(self)->OnError( + CefWebURLRequestCToCpp::Wrap(requester), + errorCode); +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefWebURLRequestClientCppToC::CefWebURLRequestClientCppToC( + CefWebURLRequestClient* cls) + : CefCppToC(cls) { + struct_.struct_.on_state_change = web_urlrequest_client_on_state_change; + struct_.struct_.on_redirect = web_urlrequest_client_on_redirect; + struct_.struct_.on_headers_received = + web_urlrequest_client_on_headers_received; + struct_.struct_.on_progress = web_urlrequest_client_on_progress; + struct_.struct_.on_data = web_urlrequest_client_on_data; + struct_.struct_.on_error = web_urlrequest_client_on_error; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/web_urlrequest_client_cpptoc.h b/cef1/libcef_dll/cpptoc/web_urlrequest_client_cpptoc.h new file mode 100644 index 000000000..1aca5c15a --- /dev/null +++ b/cef1/libcef_dll/cpptoc/web_urlrequest_client_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_URLREQUEST_CLIENT_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_WEB_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_web_urlrequest.h" +#include "include/capi/cef_web_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 CefWebURLRequestClientCppToC + : public CefCppToC { + public: + explicit CefWebURLRequestClientCppToC(CefWebURLRequestClient* cls); + virtual ~CefWebURLRequestClientCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WEB_URLREQUEST_CLIENT_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/web_urlrequest_cpptoc.cc b/cef1/libcef_dll/cpptoc/web_urlrequest_cpptoc.cc new file mode 100644 index 000000000..fc2a0b569 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/web_urlrequest_cpptoc.cc @@ -0,0 +1,86 @@ +// 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/request_cpptoc.h" +#include "libcef_dll/cpptoc/web_urlrequest_cpptoc.h" +#include "libcef_dll/ctocpp/web_urlrequest_client_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT cef_web_urlrequest_t* cef_web_urlrequest_create( + cef_request_t* request, struct _cef_web_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 = CefWebURLRequest::CreateWebURLRequest( + CefRequestCppToC::Unwrap(request), + CefWebURLRequestClientCToCpp::Wrap(client)); + + // Return type: refptr_same + return CefWebURLRequestCppToC::Wrap(_retval); +} + + +// MEMBER FUNCTIONS - Body may be edited by hand. + +void CEF_CALLBACK web_urlrequest_cancel(struct _cef_web_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return; + + // Execute + CefWebURLRequestCppToC::Get(self)->Cancel(); +} + +enum cef_weburlrequest_state_t CEF_CALLBACK web_urlrequest_get_state( + struct _cef_web_urlrequest_t* self) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + DCHECK(self); + if (!self) + return WUR_STATE_UNSENT; + + // Execute + cef_weburlrequest_state_t _retval = CefWebURLRequestCppToC::Get( + self)->GetState(); + + // Return type: simple + return _retval; +} + + +// CONSTRUCTOR - Do not edit by hand. + +CefWebURLRequestCppToC::CefWebURLRequestCppToC(CefWebURLRequest* cls) + : CefCppToC( + cls) { + struct_.struct_.cancel = web_urlrequest_cancel; + struct_.struct_.get_state = web_urlrequest_get_state; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/web_urlrequest_cpptoc.h b/cef1/libcef_dll/cpptoc/web_urlrequest_cpptoc.h new file mode 100644 index 000000000..840844eae --- /dev/null +++ b/cef1/libcef_dll/cpptoc/web_urlrequest_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_URLREQUEST_CPPTOC_H_ +#define CEF_LIBCEF_DLL_CPPTOC_WEB_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_web_urlrequest.h" +#include "include/capi/cef_web_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 CefWebURLRequestCppToC + : public CefCppToC { + public: + explicit CefWebURLRequestCppToC(CefWebURLRequest* cls); + virtual ~CefWebURLRequestCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WEB_URLREQUEST_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/write_handler_cpptoc.cc b/cef1/libcef_dll/cpptoc/write_handler_cpptoc.cc new file mode 100644 index 000000000..07df04525 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/write_handler_cpptoc.cc @@ -0,0 +1,101 @@ +// 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/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; +} + + +// 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; +} + +#ifndef NDEBUG +template<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/write_handler_cpptoc.h b/cef1/libcef_dll/cpptoc/write_handler_cpptoc.h new file mode 100644 index 000000000..f0e75a9f6 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/write_handler_cpptoc.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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); + virtual ~CefWriteHandlerCppToC() {} +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_WRITE_HANDLER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/xml_reader_cpptoc.cc b/cef1/libcef_dll/cpptoc/xml_reader_cpptoc.cc new file mode 100644 index 000000000..a80c32b2e --- /dev/null +++ b/cef1/libcef_dll/cpptoc/xml_reader_cpptoc.cc @@ -0,0 +1,558 @@ +// 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/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, + enum 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(); +} + +enum 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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/xml_reader_cpptoc.h b/cef1/libcef_dll/cpptoc/xml_reader_cpptoc.h new file mode 100644 index 000000000..1674b2faf --- /dev/null +++ b/cef1/libcef_dll/cpptoc/xml_reader_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefXmlReaderCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_XML_READER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/cpptoc/zip_reader_cpptoc.cc b/cef1/libcef_dll/cpptoc/zip_reader_cpptoc.cc new file mode 100644 index 000000000..57335e96f --- /dev/null +++ b/cef1/libcef_dll/cpptoc/zip_reader_cpptoc.cc @@ -0,0 +1,249 @@ +// 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/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<> long CefCppToC::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/cpptoc/zip_reader_cpptoc.h b/cef1/libcef_dll/cpptoc/zip_reader_cpptoc.h new file mode 100644 index 000000000..2bfbbada8 --- /dev/null +++ b/cef1/libcef_dll/cpptoc/zip_reader_cpptoc.h @@ -0,0 +1,36 @@ +// 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_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); + virtual ~CefZipReaderCppToC() {} +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CPPTOC_ZIP_READER_CPPTOC_H_ + diff --git a/cef1/libcef_dll/ctocpp/app_ctocpp.cc b/cef1/libcef_dll/ctocpp/app_ctocpp.cc new file mode 100644 index 000000000..5f22ff770 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/app_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/app_ctocpp.h" +#include "libcef_dll/ctocpp/proxy_handler_ctocpp.h" +#include "libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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::GetProxyHandler() { + if (CEF_MEMBER_MISSING(struct_, get_proxy_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_proxy_handler_t* _retval = struct_->get_proxy_handler(struct_); + + // Return type: refptr_same + return CefProxyHandlerCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/app_ctocpp.h b/cef1/libcef_dll/ctocpp/app_ctocpp.h new file mode 100644 index 000000000..4f13e8563 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/app_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefAppCToCpp() {} + + // CefApp methods + virtual CefRefPtr GetResourceBundleHandler( + ) OVERRIDE; + virtual CefRefPtr GetProxyHandler() OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_APP_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/base_ctocpp.h b/cef1/libcef_dll/ctocpp/base_ctocpp.h new file mode 100644 index 000000000..650c08e33 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/base_ctocpp.h @@ -0,0 +1,98 @@ +// 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/cef_base.h" +#include "include/capi/cef_base_capi.h" +#include "libcef_dll/cef_logging.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. + int AddRef() { + UnderlyingAddRef(); + return refct_.AddRef(); + } + int Release() { + UnderlyingRelease(); + int retval = refct_.Release(); + if (retval == 0) + delete this; + return retval; + } + int GetRefCt() { return refct_.GetRefCt(); } + + // Increment/decrement reference counts on only the underlying class. + int UnderlyingAddRef() { + if (!struct_->add_ref) + return 0; + return struct_->add_ref(struct_); + } + int UnderlyingRelease() { + if (!struct_->release) + return 0; + return struct_->release(struct_); + } + int UnderlyingGetRefCt() { + if (!struct_->get_refct) + return 0; + return struct_->get_refct(struct_); + } + + protected: + CefRefCount refct_; + cef_base_t* struct_; +}; + + +#endif // CEF_LIBCEF_DLL_CTOCPP_BASE_CTOCPP_H_ diff --git a/cef1/libcef_dll/ctocpp/browser_ctocpp.cc b/cef1/libcef_dll/ctocpp/browser_ctocpp.cc new file mode 100644 index 000000000..cbce950c9 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/browser_ctocpp.cc @@ -0,0 +1,578 @@ +// 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/client_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// STATIC METHODS - Body may be edited by hand. + +bool CefBrowser::CreateBrowser(CefWindowInfo& windowInfo, + CefRefPtr client, const CefString& url, + const CefBrowserSettings& settings) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: client; type: refptr_diff + DCHECK(client.get()); + if (!client.get()) + return false; + // Unverified params: url + + // Execute + int _retval = cef_browser_create( + &windowInfo, + CefClientCppToC::Wrap(client), + url.GetStruct(), + &settings); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefBrowser::CreateBrowserSync(CefWindowInfo& windowInfo, + CefRefPtr client, const CefString& url, + const CefBrowserSettings& settings) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: client; type: refptr_diff + DCHECK(client.get()); + if (!client.get()) + return NULL; + // Unverified params: url + + // Execute + cef_browser_t* _retval = cef_browser_create_sync( + &windowInfo, + CefClientCppToC::Wrap(client), + url.GetStruct(), + &settings); + + // Return type: refptr_same + return CefBrowserCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefBrowserCToCpp::ParentWindowWillClose() { + if (CEF_MEMBER_MISSING(struct_, parent_window_will_close)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->parent_window_will_close(struct_); +} + +void CefBrowserCToCpp::CloseBrowser() { + if (CEF_MEMBER_MISSING(struct_, close_browser)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->close_browser(struct_); +} + +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_); +} + +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_); +} + +void CefBrowserCToCpp::SetFocus(bool enable) { + if (CEF_MEMBER_MISSING(struct_, set_focus)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_focus(struct_, + enable); +} + +CefWindowHandle CefBrowserCToCpp::GetWindowHandle() { + if (CEF_MEMBER_MISSING(struct_, get_window_handle)) + return NULL; + + // 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 CefBrowserCToCpp::GetOpenerWindowHandle() { + if (CEF_MEMBER_MISSING(struct_, get_opener_window_handle)) + return NULL; + + // 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; +} + +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::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 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(const CefString& name) { + if (CEF_MEMBER_MISSING(struct_, get_frame)) + return NULL; + + // 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_frame_t* _retval = struct_->get_frame(struct_, + name.GetStruct()); + + // Return type: refptr_same + return CefFrameCToCpp::Wrap(_retval); +} + +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); + } +} + +void CefBrowserCToCpp::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 CefBrowserCToCpp::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); +} + +double CefBrowserCToCpp::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 CefBrowserCToCpp::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 CefBrowserCToCpp::ClearHistory() { + if (CEF_MEMBER_MISSING(struct_, clear_history)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->clear_history(struct_); +} + +void CefBrowserCToCpp::ShowDevTools() { + if (CEF_MEMBER_MISSING(struct_, show_dev_tools)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->show_dev_tools(struct_); +} + +void CefBrowserCToCpp::CloseDevTools() { + if (CEF_MEMBER_MISSING(struct_, close_dev_tools)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->close_dev_tools(struct_); +} + +bool CefBrowserCToCpp::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; +} + +bool CefBrowserCToCpp::GetSize(PaintElementType type, int& width, int& height) { + if (CEF_MEMBER_MISSING(struct_, get_size)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->get_size(struct_, + type, + &width, + &height); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserCToCpp::SetSize(PaintElementType type, int width, int height) { + if (CEF_MEMBER_MISSING(struct_, set_size)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->set_size(struct_, + type, + width, + height); +} + +bool CefBrowserCToCpp::IsPopupVisible() { + if (CEF_MEMBER_MISSING(struct_, is_popup_visible)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->is_popup_visible(struct_); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserCToCpp::HidePopup() { + if (CEF_MEMBER_MISSING(struct_, hide_popup)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->hide_popup(struct_); +} + +void CefBrowserCToCpp::Invalidate(const CefRect& dirtyRect) { + if (CEF_MEMBER_MISSING(struct_, invalidate)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->invalidate(struct_, + &dirtyRect); +} + +bool CefBrowserCToCpp::GetImage(PaintElementType type, int width, int height, + void* buffer) { + if (CEF_MEMBER_MISSING(struct_, get_image)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return false; + + // Execute + int _retval = struct_->get_image(struct_, + type, + width, + height, + buffer); + + // Return type: bool + return _retval?true:false; +} + +void CefBrowserCToCpp::SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, + int modifiers) { + if (CEF_MEMBER_MISSING(struct_, send_key_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->send_key_event(struct_, + type, + &keyInfo, + modifiers); +} + +void CefBrowserCToCpp::SendMouseClickEvent(int x, int y, 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_, + x, + y, + type, + mouseUp, + clickCount); +} + +void CefBrowserCToCpp::SendMouseMoveEvent(int x, int y, 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_, + x, + y, + mouseLeave); +} + +void CefBrowserCToCpp::SendMouseWheelEvent(int x, int y, 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_, + x, + y, + deltaX, + deltaY); +} + +void CefBrowserCToCpp::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 CefBrowserCToCpp::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_); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/browser_ctocpp.h b/cef1/libcef_dll/ctocpp/browser_ctocpp.h new file mode 100644 index 000000000..d22900c55 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/browser_ctocpp.h @@ -0,0 +1,86 @@ +// 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_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) {} + virtual ~CefBrowserCToCpp() {} + + // CefBrowser methods + virtual void ParentWindowWillClose() OVERRIDE; + virtual void CloseBrowser() OVERRIDE; + virtual bool CanGoBack() OVERRIDE; + virtual void GoBack() OVERRIDE; + virtual bool CanGoForward() OVERRIDE; + virtual void GoForward() OVERRIDE; + virtual void Reload() OVERRIDE; + virtual void ReloadIgnoreCache() OVERRIDE; + virtual void StopLoad() OVERRIDE; + virtual void SetFocus(bool enable) OVERRIDE; + virtual CefWindowHandle GetWindowHandle() OVERRIDE; + virtual CefWindowHandle GetOpenerWindowHandle() OVERRIDE; + virtual bool IsPopup() OVERRIDE; + virtual bool HasDocument() OVERRIDE; + virtual CefRefPtr GetClient() OVERRIDE; + virtual CefRefPtr GetMainFrame() OVERRIDE; + virtual CefRefPtr GetFocusedFrame() OVERRIDE; + virtual CefRefPtr GetFrame(const CefString& name) OVERRIDE; + virtual void GetFrameNames(std::vector& names) OVERRIDE; + virtual void Find(int identifier, const CefString& searchText, bool forward, + bool matchCase, bool findNext) OVERRIDE; + virtual void StopFinding(bool clearSelection) OVERRIDE; + virtual double GetZoomLevel() OVERRIDE; + virtual void SetZoomLevel(double zoomLevel) OVERRIDE; + virtual void ClearHistory() OVERRIDE; + virtual void ShowDevTools() OVERRIDE; + virtual void CloseDevTools() OVERRIDE; + virtual bool IsWindowRenderingDisabled() OVERRIDE; + virtual bool GetSize(PaintElementType type, int& width, int& height) OVERRIDE; + virtual void SetSize(PaintElementType type, int width, int height) OVERRIDE; + virtual bool IsPopupVisible() OVERRIDE; + virtual void HidePopup() OVERRIDE; + virtual void Invalidate(const CefRect& dirtyRect) OVERRIDE; + virtual bool GetImage(PaintElementType type, int width, int height, + void* buffer) OVERRIDE; + virtual void SendKeyEvent(KeyType type, const CefKeyInfo& keyInfo, + int modifiers) OVERRIDE; + virtual void SendMouseClickEvent(int x, int y, MouseButtonType type, + bool mouseUp, int clickCount) OVERRIDE; + virtual void SendMouseMoveEvent(int x, int y, bool mouseLeave) OVERRIDE; + virtual void SendMouseWheelEvent(int x, int y, int deltaX, + int deltaY) OVERRIDE; + virtual void SendFocusEvent(bool setFocus) OVERRIDE; + virtual void SendCaptureLostEvent() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_BROWSER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/client_ctocpp.cc b/cef1/libcef_dll/ctocpp/client_ctocpp.cc new file mode 100644 index 000000000..69cdd97c1 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/client_ctocpp.cc @@ -0,0 +1,219 @@ +// 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/ctocpp/client_ctocpp.h" +#include "libcef_dll/ctocpp/display_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/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/menu_handler_ctocpp.h" +#include "libcef_dll/ctocpp/permission_handler_ctocpp.h" +#include "libcef_dll/ctocpp/print_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_handler_ctocpp.h" +#include "libcef_dll/ctocpp/request_handler_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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::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); +} + +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::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::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::GetMenuHandler() { + if (CEF_MEMBER_MISSING(struct_, get_menu_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_menu_handler_t* _retval = struct_->get_menu_handler(struct_); + + // Return type: refptr_same + return CefMenuHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::GetPermissionHandler() { + if (CEF_MEMBER_MISSING(struct_, get_permission_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_permission_handler_t* _retval = struct_->get_permission_handler(struct_); + + // Return type: refptr_same + return CefPermissionHandlerCToCpp::Wrap(_retval); +} + +CefRefPtr CefClientCToCpp::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); +} + +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::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::GetV8ContextHandler() { + if (CEF_MEMBER_MISSING(struct_, get_v8context_handler)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_v8context_handler_t* _retval = struct_->get_v8context_handler(struct_); + + // Return type: refptr_same + return CefV8ContextHandlerCToCpp::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::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); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/client_ctocpp.h b/cef1/libcef_dll/ctocpp/client_ctocpp.h new file mode 100644 index 000000000..a7ec8f9b4 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/client_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefClientCToCpp() {} + + // CefClient methods + virtual CefRefPtr GetLifeSpanHandler() OVERRIDE; + virtual CefRefPtr GetLoadHandler() OVERRIDE; + virtual CefRefPtr GetRequestHandler() OVERRIDE; + virtual CefRefPtr GetDisplayHandler() OVERRIDE; + virtual CefRefPtr GetFocusHandler() OVERRIDE; + virtual CefRefPtr GetKeyboardHandler() OVERRIDE; + virtual CefRefPtr GetMenuHandler() OVERRIDE; + virtual CefRefPtr GetPermissionHandler() OVERRIDE; + virtual CefRefPtr GetPrintHandler() OVERRIDE; + virtual CefRefPtr GetFindHandler() OVERRIDE; + virtual CefRefPtr GetJSDialogHandler() OVERRIDE; + virtual CefRefPtr GetV8ContextHandler() OVERRIDE; + virtual CefRefPtr GetRenderHandler() OVERRIDE; + virtual CefRefPtr GetDragHandler() OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_CLIENT_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/command_line_ctocpp.cc b/cef1/libcef_dll/ctocpp/command_line_ctocpp.cc new file mode 100644 index 000000000..7bbc1d313 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/command_line_ctocpp.cc @@ -0,0 +1,292 @@ +// 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 "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() { + int build_revision = cef_build_revision(); + if (build_revision != CEF_REVISION) { + // The libcef build revision does not match the CEF API revision. + DCHECK(false); + 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); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +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()); +} + +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()); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/command_line_ctocpp.h b/cef1/libcef_dll/ctocpp/command_line_ctocpp.h new file mode 100644 index 000000000..f66c7be1f --- /dev/null +++ b/cef1/libcef_dll/ctocpp/command_line_ctocpp.h @@ -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. +// + +#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/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) {} + virtual ~CefCommandLineCToCpp() {} + + // CefCommandLine methods + virtual void InitFromArgv(int argc, const char* const* argv) OVERRIDE; + virtual void InitFromString(const CefString& command_line) 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; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_COMMAND_LINE_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/content_filter_ctocpp.cc b/cef1/libcef_dll/ctocpp/content_filter_ctocpp.cc new file mode 100644 index 000000000..29b1862fc --- /dev/null +++ b/cef1/libcef_dll/ctocpp/content_filter_ctocpp.cc @@ -0,0 +1,84 @@ +// 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/stream_reader_cpptoc.h" +#include "libcef_dll/ctocpp/content_filter_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefContentFilterCToCpp::ProcessData(const void* data, int data_size, + CefRefPtr& substitute_data) { + if (CEF_MEMBER_MISSING(struct_, process_data)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return; + + // Translate param: substitute_data; type: refptr_diff_byref + cef_stream_reader_t* substitute_dataStruct = NULL; + if (substitute_data.get()) + substitute_dataStruct = CefStreamReaderCppToC::Wrap(substitute_data); + cef_stream_reader_t* substitute_dataOrig = substitute_dataStruct; + + // Execute + struct_->process_data(struct_, + data, + data_size, + &substitute_dataStruct); + + // Restore param:substitute_data; type: refptr_diff_byref + if (substitute_dataStruct) { + if (substitute_dataStruct != substitute_dataOrig) { + substitute_data = CefStreamReaderCppToC::Unwrap(substitute_dataStruct); + } + } else { + substitute_data = NULL; + } +} + +void CefContentFilterCToCpp::Drain(CefRefPtr& remainder) { + if (CEF_MEMBER_MISSING(struct_, drain)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Translate param: remainder; type: refptr_diff_byref + cef_stream_reader_t* remainderStruct = NULL; + if (remainder.get()) + remainderStruct = CefStreamReaderCppToC::Wrap(remainder); + cef_stream_reader_t* remainderOrig = remainderStruct; + + // Execute + struct_->drain(struct_, + &remainderStruct); + + // Restore param:remainder; type: refptr_diff_byref + if (remainderStruct) { + if (remainderStruct != remainderOrig) { + remainder = CefStreamReaderCppToC::Unwrap(remainderStruct); + } + } else { + remainder = NULL; + } +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/content_filter_ctocpp.h b/cef1/libcef_dll/ctocpp/content_filter_ctocpp.h new file mode 100644 index 000000000..716cc0f5b --- /dev/null +++ b/cef1/libcef_dll/ctocpp/content_filter_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_CONTENT_FILTER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_CONTENT_FILTER_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_content_filter.h" +#include "include/capi/cef_content_filter_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 CefContentFilterCToCpp + : public CefCToCpp { + public: + explicit CefContentFilterCToCpp(cef_content_filter_t* str) + : CefCToCpp(str) {} + virtual ~CefContentFilterCToCpp() {} + + // CefContentFilter methods + virtual void ProcessData(const void* data, int data_size, + CefRefPtr& substitute_data) OVERRIDE; + virtual void Drain(CefRefPtr& remainder) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_CONTENT_FILTER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/cookie_manager_ctocpp.cc b/cef1/libcef_dll/ctocpp/cookie_manager_ctocpp.cc new file mode 100644 index 000000000..f33ef0d7d --- /dev/null +++ b/cef1/libcef_dll/ctocpp/cookie_manager_ctocpp.cc @@ -0,0 +1,175 @@ +// 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/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) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: path + + // Execute + cef_cookie_manager_t* _retval = cef_cookie_manager_create_manager( + path.GetStruct()); + + // 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) { + 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()); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/cookie_manager_ctocpp.h b/cef1/libcef_dll/ctocpp/cookie_manager_ctocpp.h new file mode 100644 index 000000000..78cd1f460 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/cookie_manager_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefCookieManagerCToCpp() {} + + // 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) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_COOKIE_MANAGER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/cookie_visitor_ctocpp.cc b/cef1/libcef_dll/ctocpp/cookie_visitor_ctocpp.cc new file mode 100644 index 000000000..e5d9e4072 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/cookie_visitor_ctocpp.cc @@ -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. +// + +#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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/cookie_visitor_ctocpp.h b/cef1/libcef_dll/ctocpp/cookie_visitor_ctocpp.h new file mode 100644 index 000000000..41969281f --- /dev/null +++ b/cef1/libcef_dll/ctocpp/cookie_visitor_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefCookieVisitorCToCpp() {} + + // CefCookieVisitor methods + virtual 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/cef1/libcef_dll/ctocpp/ctocpp.h b/cef1/libcef_dll/ctocpp/ctocpp.h new file mode 100644 index 000000000..3697647c4 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/ctocpp.h @@ -0,0 +1,113 @@ +// 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/cef_base.h" +#include "include/capi/cef_base_capi.h" +#include "libcef_dll/cef_logging.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 + CefAtomicIncrement(&DebugObjCt); +#endif + } + virtual ~CefCToCpp() { +#ifndef NDEBUG + CefAtomicDecrement(&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. + int AddRef() { + UnderlyingAddRef(); + return refct_.AddRef(); + } + int Release() { + UnderlyingRelease(); + int retval = refct_.Release(); + if (retval == 0) + delete this; + return retval; + } + int GetRefCt() { return refct_.GetRefCt(); } + + // Increment/decrement reference counts on only the underlying class. + int UnderlyingAddRef() { + if (!struct_->base.add_ref) + return 0; + return struct_->base.add_ref(&struct_->base); + } + int UnderlyingRelease() { + if (!struct_->base.release) + return 0; + return struct_->base.release(&struct_->base); + } + int UnderlyingGetRefCt() { + if (!struct_->base.get_refct) + return 0; + return struct_->base.get_refct(&struct_->base); + } + +#ifndef NDEBUG + // Simple tracking of allocated objects. + static long DebugObjCt; // NOLINT(runtime/int) +#endif + + protected: + CefRefCount refct_; + StructName* struct_; +}; + +#endif // CEF_LIBCEF_DLL_CTOCPP_CTOCPP_H_ diff --git a/cef1/libcef_dll/ctocpp/display_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/display_handler_ctocpp.cc new file mode 100644 index 000000000..f47b89078 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/display_handler_ctocpp.cc @@ -0,0 +1,181 @@ +// 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/display_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefDisplayHandlerCToCpp::OnNavStateChange(CefRefPtr browser, + bool canGoBack, bool canGoForward) { + if (CEF_MEMBER_MISSING(struct_, on_nav_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_nav_state_change(struct_, + CefBrowserCppToC::Wrap(browser), + canGoBack, + canGoForward); +} + +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::OnContentsSizeChange( + CefRefPtr browser, CefRefPtr frame, int width, + int height) { + if (CEF_MEMBER_MISSING(struct_, on_contents_size_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; + + // Execute + struct_->on_contents_size_change(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + width, + height); +} + +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()); +} + +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, StatusType type) { + 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(), + type); +} + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/display_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/display_handler_ctocpp.h new file mode 100644 index 000000000..d539035fe --- /dev/null +++ b/cef1/libcef_dll/ctocpp/display_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/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) {} + virtual ~CefDisplayHandlerCToCpp() {} + + // CefDisplayHandler methods + virtual void OnNavStateChange(CefRefPtr browser, bool canGoBack, + bool canGoForward) OVERRIDE; + virtual void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, const CefString& url) OVERRIDE; + virtual void OnContentsSizeChange(CefRefPtr browser, + CefRefPtr frame, int width, int height) OVERRIDE; + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) OVERRIDE; + virtual bool OnTooltip(CefRefPtr browser, + CefString& text) OVERRIDE; + virtual void OnStatusMessage(CefRefPtr browser, + const CefString& value, StatusType type) OVERRIDE; + virtual 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/cef1/libcef_dll/ctocpp/domdocument_ctocpp.cc b/cef1/libcef_dll/ctocpp/domdocument_ctocpp.cc new file mode 100644 index 000000000..63aeafb67 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domdocument_ctocpp.cc @@ -0,0 +1,255 @@ +// 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/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; +} + +CefRefPtr CefDOMDocumentCToCpp::GetSelectionStartNode() { + if (CEF_MEMBER_MISSING(struct_, get_selection_start_node)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_selection_start_node(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +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; +} + +CefRefPtr CefDOMDocumentCToCpp::GetSelectionEndNode() { + if (CEF_MEMBER_MISSING(struct_, get_selection_end_node)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_selection_end_node(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/domdocument_ctocpp.h b/cef1/libcef_dll/ctocpp/domdocument_ctocpp.h new file mode 100644 index 000000000..92fc5957d --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domdocument_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefDOMDocumentCToCpp() {} + + // 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 CefRefPtr GetSelectionStartNode() OVERRIDE; + virtual int GetSelectionStartOffset() OVERRIDE; + virtual CefRefPtr GetSelectionEndNode() 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/cef1/libcef_dll/ctocpp/domevent_ctocpp.cc b/cef1/libcef_dll/ctocpp/domevent_ctocpp.cc new file mode 100644 index 000000000..d812312f2 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domevent_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/domevent_ctocpp.h" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +CefString CefDOMEventCToCpp::GetType() { + if (CEF_MEMBER_MISSING(struct_, get_type)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_type(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefDOMEvent::Category CefDOMEventCToCpp::GetCategory() { + if (CEF_MEMBER_MISSING(struct_, get_category)) + return DOM_EVENT_CATEGORY_UNKNOWN; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dom_event_category_t _retval = struct_->get_category(struct_); + + // Return type: simple + return _retval; +} + +CefDOMEvent::Phase CefDOMEventCToCpp::GetPhase() { + if (CEF_MEMBER_MISSING(struct_, get_phase)) + return DOM_EVENT_PHASE_UNKNOWN; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_dom_event_phase_t _retval = struct_->get_phase(struct_); + + // Return type: simple + return _retval; +} + +bool CefDOMEventCToCpp::CanBubble() { + if (CEF_MEMBER_MISSING(struct_, can_bubble)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->can_bubble(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefDOMEventCToCpp::CanCancel() { + if (CEF_MEMBER_MISSING(struct_, can_cancel)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->can_cancel(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefDOMEventCToCpp::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 CefDOMEventCToCpp::GetTarget() { + if (CEF_MEMBER_MISSING(struct_, get_target)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_target(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + +CefRefPtr CefDOMEventCToCpp::GetCurrentTarget() { + if (CEF_MEMBER_MISSING(struct_, get_current_target)) + return NULL; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_domnode_t* _retval = struct_->get_current_target(struct_); + + // Return type: refptr_same + return CefDOMNodeCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/domevent_ctocpp.h b/cef1/libcef_dll/ctocpp/domevent_ctocpp.h new file mode 100644 index 000000000..64b05c62a --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domevent_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_DOMEVENT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOMEVENT_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 CefDOMEventCToCpp + : public CefCToCpp { + public: + explicit CefDOMEventCToCpp(cef_domevent_t* str) + : CefCToCpp(str) {} + virtual ~CefDOMEventCToCpp() {} + + // CefDOMEvent methods + virtual CefString GetType() OVERRIDE; + virtual Category GetCategory() OVERRIDE; + virtual Phase GetPhase() OVERRIDE; + virtual bool CanBubble() OVERRIDE; + virtual bool CanCancel() OVERRIDE; + virtual CefRefPtr GetDocument() OVERRIDE; + virtual CefRefPtr GetTarget() OVERRIDE; + virtual CefRefPtr GetCurrentTarget() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOMEVENT_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/domevent_listener_ctocpp.cc b/cef1/libcef_dll/ctocpp/domevent_listener_ctocpp.cc new file mode 100644 index 000000000..3186604b1 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domevent_listener_ctocpp.cc @@ -0,0 +1,40 @@ +// 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/domevent_cpptoc.h" +#include "libcef_dll/ctocpp/domevent_listener_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefDOMEventListenerCToCpp::HandleEvent(CefRefPtr event) { + if (CEF_MEMBER_MISSING(struct_, handle_event)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: event; type: refptr_diff + DCHECK(event.get()); + if (!event.get()) + return; + + // Execute + struct_->handle_event(struct_, + CefDOMEventCppToC::Wrap(event)); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/domevent_listener_ctocpp.h b/cef1/libcef_dll/ctocpp/domevent_listener_ctocpp.h new file mode 100644 index 000000000..9d90727f3 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domevent_listener_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_DOMEVENT_LISTENER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_DOMEVENT_LISTENER_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 CefDOMEventListenerCToCpp + : public CefCToCpp { + public: + explicit CefDOMEventListenerCToCpp(cef_domevent_listener_t* str) + : CefCToCpp(str) {} + virtual ~CefDOMEventListenerCToCpp() {} + + // CefDOMEventListener methods + virtual void HandleEvent(CefRefPtr event) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOMEVENT_LISTENER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/domnode_ctocpp.cc b/cef1/libcef_dll/ctocpp/domnode_ctocpp.cc new file mode 100644 index 000000000..1dfb6a90c --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domnode_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/domevent_listener_cpptoc.h" +#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::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); +} + +void CefDOMNodeCToCpp::AddEventListener(const CefString& eventType, + CefRefPtr listener, bool useCapture) { + if (CEF_MEMBER_MISSING(struct_, add_event_listener)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: eventType; type: string_byref_const + DCHECK(!eventType.empty()); + if (eventType.empty()) + return; + // Verify param: listener; type: refptr_diff + DCHECK(listener.get()); + if (!listener.get()) + return; + + // Execute + struct_->add_event_listener(struct_, + eventType.GetStruct(), + CefDOMEventListenerCppToC::Wrap(listener), + useCapture); +} + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/domnode_ctocpp.h b/cef1/libcef_dll/ctocpp/domnode_ctocpp.h new file mode 100644 index 000000000..90311251d --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domnode_ctocpp.h @@ -0,0 +1,66 @@ +// 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_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) {} + virtual ~CefDOMNodeCToCpp() {} + + // CefDOMNode methods + virtual Type GetType() OVERRIDE; + virtual bool IsText() OVERRIDE; + virtual bool IsElement() 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 void AddEventListener(const CefString& eventType, + CefRefPtr listener, bool useCapture) 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/cef1/libcef_dll/ctocpp/domvisitor_ctocpp.cc b/cef1/libcef_dll/ctocpp/domvisitor_ctocpp.cc new file mode 100644 index 000000000..b652d633f --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domvisitor_ctocpp.cc @@ -0,0 +1,40 @@ +// 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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/domvisitor_ctocpp.h b/cef1/libcef_dll/ctocpp/domvisitor_ctocpp.h new file mode 100644 index 000000000..c2005ff48 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/domvisitor_ctocpp.h @@ -0,0 +1,40 @@ +// 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_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) {} + virtual ~CefDOMVisitorCToCpp() {} + + // CefDOMVisitor methods + virtual void Visit(CefRefPtr document) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOMVISITOR_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/download_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/download_handler_ctocpp.cc new file mode 100644 index 000000000..0e1ea6a00 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/download_handler_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefDownloadHandlerCToCpp::ReceivedData(void* data, int data_size) { + if (CEF_MEMBER_MISSING(struct_, received_data)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return false; + + // Execute + int _retval = struct_->received_data(struct_, + data, + data_size); + + // Return type: bool + return _retval?true:false; +} + +void CefDownloadHandlerCToCpp::Complete() { + if (CEF_MEMBER_MISSING(struct_, complete)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->complete(struct_); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/download_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/download_handler_ctocpp.h new file mode 100644 index 000000000..a12ef9e5e --- /dev/null +++ b/cef1/libcef_dll/ctocpp/download_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefDownloadHandlerCToCpp() {} + + // CefDownloadHandler methods + virtual bool ReceivedData(void* data, int data_size) OVERRIDE; + virtual void Complete() OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DOWNLOAD_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/drag_data_ctocpp.cc b/cef1/libcef_dll/ctocpp/drag_data_ctocpp.cc new file mode 100644 index 000000000..7bad29ace --- /dev/null +++ b/cef1/libcef_dll/ctocpp/drag_data_ctocpp.cc @@ -0,0 +1,195 @@ +// 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/ctocpp/drag_data_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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; +} + +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; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/drag_data_ctocpp.h b/cef1/libcef_dll/ctocpp/drag_data_ctocpp.h new file mode 100644 index 000000000..e418e072b --- /dev/null +++ b/cef1/libcef_dll/ctocpp/drag_data_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefDragDataCToCpp() {} + + // CefDragData methods + 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 bool GetFileNames(std::vector& names) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_DRAG_DATA_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/drag_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/drag_handler_ctocpp.cc new file mode 100644 index 000000000..0d55b1463 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/drag_handler_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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::OnDragStart(CefRefPtr browser, + CefRefPtr dragData, DragOperationsMask mask) { + if (CEF_MEMBER_MISSING(struct_, on_drag_start)) + 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_start(struct_, + CefBrowserCppToC::Wrap(browser), + CefDragDataCppToC::Wrap(dragData), + mask); + + // Return type: bool + return _retval?true:false; +} + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/drag_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/drag_handler_ctocpp.h new file mode 100644 index 000000000..4f8aeb8ab --- /dev/null +++ b/cef1/libcef_dll/ctocpp/drag_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefDragHandlerCToCpp() {} + + // CefDragHandler methods + virtual bool OnDragStart(CefRefPtr browser, + CefRefPtr dragData, DragOperationsMask mask) OVERRIDE; + virtual 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/cef1/libcef_dll/ctocpp/find_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/find_handler_ctocpp.cc new file mode 100644 index 000000000..e36409e66 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/find_handler_ctocpp.cc @@ -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. +// + +#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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/find_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/find_handler_ctocpp.h new file mode 100644 index 000000000..0ee376063 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/find_handler_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefFindHandlerCToCpp() {} + + // CefFindHandler methods + virtual 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/cef1/libcef_dll/ctocpp/focus_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/focus_handler_ctocpp.cc new file mode 100644 index 000000000..60404c6c1 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/focus_handler_ctocpp.cc @@ -0,0 +1,85 @@ +// 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/domnode_cpptoc.h" +#include "libcef_dll/cpptoc/frame_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::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)); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/focus_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/focus_handler_ctocpp.h new file mode 100644 index 000000000..e2644f436 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/focus_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefFocusHandlerCToCpp() {} + + // CefFocusHandler methods + virtual void OnTakeFocus(CefRefPtr browser, bool next) OVERRIDE; + virtual bool OnSetFocus(CefRefPtr browser, + FocusSource source) OVERRIDE; + virtual void OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, CefRefPtr node) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_FOCUS_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/frame_ctocpp.cc b/cef1/libcef_dll/ctocpp/frame_ctocpp.cc new file mode 100644 index 000000000..59c47cafa --- /dev/null +++ b/cef1/libcef_dll/ctocpp/frame_ctocpp.cc @@ -0,0 +1,368 @@ +// 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/domvisitor_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/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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::Print() { + if (CEF_MEMBER_MISSING(struct_, print)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->print(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_); +} + +CefString CefFrameCToCpp::GetSource() { + if (CEF_MEMBER_MISSING(struct_, get_source)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_source(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +CefString CefFrameCToCpp::GetText() { + if (CEF_MEMBER_MISSING(struct_, get_text)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_text(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +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::LoadStream(CefRefPtr stream, + const CefString& url) { + if (CEF_MEMBER_MISSING(struct_, load_stream)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: stream; type: refptr_same + DCHECK(stream.get()); + if (!stream.get()) + return; + // Verify param: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return; + + // Execute + struct_->load_stream(struct_, + CefStreamReaderCToCpp::Unwrap(stream), + url.GetStruct()); +} + +void CefFrameCToCpp::ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, int startLine) { + if (CEF_MEMBER_MISSING(struct_, execute_java_script)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: jsCode; type: string_byref_const + DCHECK(!jsCode.empty()); + if (jsCode.empty()) + return; + // Unverified params: scriptUrl + + // Execute + struct_->execute_java_script(struct_, + jsCode.GetStruct(), + scriptUrl.GetStruct(), + startLine); +} + +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); +} + +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)); +} + +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); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = + 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/frame_ctocpp.h b/cef1/libcef_dll/ctocpp/frame_ctocpp.h new file mode 100644 index 000000000..091d85cad --- /dev/null +++ b/cef1/libcef_dll/ctocpp/frame_ctocpp.h @@ -0,0 +1,71 @@ +// 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_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) {} + virtual ~CefFrameCToCpp() {} + + // CefFrame methods + 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 Print() OVERRIDE; + virtual void ViewSource() OVERRIDE; + virtual CefString GetSource() OVERRIDE; + virtual CefString GetText() 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 LoadStream(CefRefPtr stream, + const CefString& url) OVERRIDE; + virtual void ExecuteJavaScript(const CefString& jsCode, + const CefString& scriptUrl, int startLine) 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 void VisitDOM(CefRefPtr visitor) OVERRIDE; + virtual CefRefPtr GetV8Context() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_FRAME_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc new file mode 100644 index 000000000..f752a6996 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/jsdialog_handler_ctocpp.cc @@ -0,0 +1,123 @@ +// 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/jsdialog_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefJSDialogHandlerCToCpp::OnJSAlert(CefRefPtr browser, + CefRefPtr frame, const CefString& message) { + if (CEF_MEMBER_MISSING(struct_, on_jsalert)) + 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; + // Unverified params: message + + // Execute + int _retval = struct_->on_jsalert(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + message.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefJSDialogHandlerCToCpp::OnJSConfirm(CefRefPtr browser, + CefRefPtr frame, const CefString& message, bool& retval) { + if (CEF_MEMBER_MISSING(struct_, on_jsconfirm)) + 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; + // Unverified params: message + + // Translate param: retval; type: bool_byref + int retvalInt = retval; + + // Execute + int _retval = struct_->on_jsconfirm(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + message.GetStruct(), + &retvalInt); + + // Restore param:retval; type: bool_byref + retval = retvalInt?true:false; + + // Return type: bool + return _retval?true:false; +} + +bool CefJSDialogHandlerCToCpp::OnJSPrompt(CefRefPtr browser, + CefRefPtr frame, const CefString& message, + const CefString& defaultValue, bool& retval, CefString& result) { + if (CEF_MEMBER_MISSING(struct_, on_jsprompt)) + 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; + // Unverified params: message, defaultValue + + // Translate param: retval; type: bool_byref + int retvalInt = retval; + + // Execute + int _retval = struct_->on_jsprompt(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + message.GetStruct(), + defaultValue.GetStruct(), + &retvalInt, + result.GetWritableStruct()); + + // Restore param:retval; type: bool_byref + retval = retvalInt?true:false; + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/jsdialog_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/jsdialog_handler_ctocpp.h new file mode 100644 index 000000000..55feb8430 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/jsdialog_handler_ctocpp.h @@ -0,0 +1,50 @@ +// 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_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) {} + virtual ~CefJSDialogHandlerCToCpp() {} + + // CefJSDialogHandler methods + virtual bool OnJSAlert(CefRefPtr browser, + CefRefPtr frame, const CefString& message) OVERRIDE; + virtual bool OnJSConfirm(CefRefPtr browser, + CefRefPtr frame, const CefString& message, + bool& retval) OVERRIDE; + virtual bool OnJSPrompt(CefRefPtr browser, + CefRefPtr frame, const CefString& message, + const CefString& defaultValue, bool& retval, + CefString& result) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_JSDIALOG_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/keyboard_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/keyboard_handler_ctocpp.cc new file mode 100644 index 000000000..b49457d2e --- /dev/null +++ b/cef1/libcef_dll/ctocpp/keyboard_handler_ctocpp.cc @@ -0,0 +1,50 @@ +// 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/ctocpp/keyboard_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefKeyboardHandlerCToCpp::OnKeyEvent(CefRefPtr browser, + KeyEventType type, int code, int modifiers, bool isSystemKey, + bool isAfterJavaScript) { + 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), + type, + code, + modifiers, + isSystemKey, + isAfterJavaScript); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/keyboard_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/keyboard_handler_ctocpp.h new file mode 100644 index 000000000..91eabc78c --- /dev/null +++ b/cef1/libcef_dll/ctocpp/keyboard_handler_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefKeyboardHandlerCToCpp() {} + + // CefKeyboardHandler methods + virtual bool OnKeyEvent(CefRefPtr browser, KeyEventType type, + int code, int modifiers, bool isSystemKey, + bool isAfterJavaScript) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_KEYBOARD_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/life_span_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/life_span_handler_ctocpp.cc new file mode 100644 index 000000000..4db810135 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/life_span_handler_ctocpp.cc @@ -0,0 +1,138 @@ +// 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/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 parentBrowser, const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, const CefString& url, + CefRefPtr& client, CefBrowserSettings& settings) { + if (CEF_MEMBER_MISSING(struct_, on_before_popup)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: parentBrowser; type: refptr_diff + DCHECK(parentBrowser.get()); + if (!parentBrowser.get()) + return false; + // Unverified params: url + + // Translate param: client; type: refptr_same_byref + cef_client_t* clientStruct = NULL; + if (client.get()) + clientStruct = CefClientCToCpp::Unwrap(client); + cef_client_t* clientOrig = clientStruct; + + // Execute + int _retval = struct_->on_before_popup(struct_, + CefBrowserCppToC::Wrap(parentBrowser), + &popupFeatures, + &windowInfo, + url.GetStruct(), + &clientStruct, + &settings); + + // Restore param:client; type: refptr_same_byref + if (clientStruct) { + if (clientStruct != clientOrig) { + client = CefClientCToCpp::Wrap(clientStruct); + } + } else { + client = NULL; + } + + // 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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/life_span_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/life_span_handler_ctocpp.h new file mode 100644 index 000000000..7b5e45b48 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/life_span_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefLifeSpanHandlerCToCpp() {} + + // CefLifeSpanHandler methods + virtual bool OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, + const CefString& url, CefRefPtr& client, + CefBrowserSettings& settings) OVERRIDE; + virtual void OnAfterCreated(CefRefPtr browser) OVERRIDE; + virtual bool RunModal(CefRefPtr browser) OVERRIDE; + virtual bool DoClose(CefRefPtr browser) OVERRIDE; + virtual void OnBeforeClose(CefRefPtr browser) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_LIFE_SPAN_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/load_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/load_handler_ctocpp.cc new file mode 100644 index 000000000..642cd7de0 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/load_handler_ctocpp.cc @@ -0,0 +1,103 @@ +// 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/load_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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); +} + +bool CefLoadHandlerCToCpp::OnLoadError(CefRefPtr browser, + CefRefPtr frame, ErrorCode errorCode, const CefString& failedUrl, + CefString& errorText) { + if (CEF_MEMBER_MISSING(struct_, on_load_error)) + 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: failedUrl; type: string_byref_const + DCHECK(!failedUrl.empty()); + if (failedUrl.empty()) + return false; + + // Execute + int _retval = struct_->on_load_error(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + errorCode, + failedUrl.GetStruct(), + errorText.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/load_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/load_handler_ctocpp.h new file mode 100644 index 000000000..182c8eb8c --- /dev/null +++ b/cef1/libcef_dll/ctocpp/load_handler_ctocpp.h @@ -0,0 +1,48 @@ +// 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_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) {} + virtual ~CefLoadHandlerCToCpp() {} + + // CefLoadHandler methods + virtual void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) OVERRIDE; + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, int httpStatusCode) OVERRIDE; + virtual bool OnLoadError(CefRefPtr browser, + CefRefPtr frame, ErrorCode errorCode, + const CefString& failedUrl, CefString& errorText) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_LOAD_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/menu_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/menu_handler_ctocpp.cc new file mode 100644 index 000000000..585d87d84 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/menu_handler_ctocpp.cc @@ -0,0 +1,85 @@ +// 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/ctocpp/menu_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefMenuHandlerCToCpp::OnBeforeMenu(CefRefPtr browser, + const CefMenuInfo& menuInfo) { + if (CEF_MEMBER_MISSING(struct_, on_before_menu)) + 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_before_menu(struct_, + CefBrowserCppToC::Wrap(browser), + &menuInfo); + + // Return type: bool + return _retval?true:false; +} + +void CefMenuHandlerCToCpp::GetMenuLabel(CefRefPtr browser, + MenuId menuId, CefString& label) { + if (CEF_MEMBER_MISSING(struct_, get_menu_label)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: browser; type: refptr_diff + DCHECK(browser.get()); + if (!browser.get()) + return; + + // Execute + struct_->get_menu_label(struct_, + CefBrowserCppToC::Wrap(browser), + menuId, + label.GetWritableStruct()); +} + +bool CefMenuHandlerCToCpp::OnMenuAction(CefRefPtr browser, + MenuId menuId) { + if (CEF_MEMBER_MISSING(struct_, on_menu_action)) + 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_menu_action(struct_, + CefBrowserCppToC::Wrap(browser), + menuId); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/menu_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/menu_handler_ctocpp.h new file mode 100644 index 000000000..8c2bf2cf0 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/menu_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_MENU_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_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_menu_handler.h" +#include "include/capi/cef_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 CefMenuHandlerCToCpp + : public CefCToCpp { + public: + explicit CefMenuHandlerCToCpp(cef_menu_handler_t* str) + : CefCToCpp( + str) {} + virtual ~CefMenuHandlerCToCpp() {} + + // CefMenuHandler methods + virtual bool OnBeforeMenu(CefRefPtr browser, + const CefMenuInfo& menuInfo) OVERRIDE; + virtual void GetMenuLabel(CefRefPtr browser, MenuId menuId, + CefString& label) OVERRIDE; + virtual bool OnMenuAction(CefRefPtr browser, + MenuId menuId) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_MENU_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/permission_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/permission_handler_ctocpp.cc new file mode 100644 index 000000000..700e91b39 --- /dev/null +++ b/cef1/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/cef1/libcef_dll/ctocpp/permission_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/permission_handler_ctocpp.h new file mode 100644 index 000000000..a5b7d4d04 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/permission_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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 "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/cef1/libcef_dll/ctocpp/post_data_ctocpp.cc b/cef1/libcef_dll/ctocpp/post_data_ctocpp.cc new file mode 100644 index 000000000..0a0c593cf --- /dev/null +++ b/cef1/libcef_dll/ctocpp/post_data_ctocpp.cc @@ -0,0 +1,136 @@ +// 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/ctocpp/post_data_ctocpp.h" +#include "libcef_dll/ctocpp/post_data_element_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefPostData::CreatePostData() { + // 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. + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/post_data_ctocpp.h b/cef1/libcef_dll/ctocpp/post_data_ctocpp.h new file mode 100644 index 000000000..505980dfd --- /dev/null +++ b/cef1/libcef_dll/ctocpp/post_data_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefPostDataCToCpp() {} + + // CefPostData methods + 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/cef1/libcef_dll/ctocpp/post_data_element_ctocpp.cc b/cef1/libcef_dll/ctocpp/post_data_element_ctocpp.cc new file mode 100644 index 000000000..b931ecbca --- /dev/null +++ b/cef1/libcef_dll/ctocpp/post_data_element_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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::CreatePostDataElement() { + // 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. + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/post_data_element_ctocpp.h b/cef1/libcef_dll/ctocpp/post_data_element_ctocpp.h new file mode 100644 index 000000000..2840dbdbd --- /dev/null +++ b/cef1/libcef_dll/ctocpp/post_data_element_ctocpp.h @@ -0,0 +1,48 @@ +// 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_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) {} + virtual ~CefPostDataElementCToCpp() {} + + // CefPostDataElement methods + 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/cef1/libcef_dll/ctocpp/print_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/print_handler_ctocpp.cc new file mode 100644 index 000000000..81ae2a702 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/print_handler_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/print_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefPrintHandlerCToCpp::GetPrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions) { + if (CEF_MEMBER_MISSING(struct_, get_print_options)) + 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_print_options(struct_, + CefBrowserCppToC::Wrap(browser), + &printOptions); + + // Return type: bool + return _retval?true:false; +} + +bool CefPrintHandlerCToCpp::GetPrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, const CefPrintInfo& printInfo, + const CefString& url, const CefString& title, int currentPage, + int maxPages, CefString& topLeft, CefString& topCenter, + CefString& topRight, CefString& bottomLeft, CefString& bottomCenter, + CefString& bottomRight) { + if (CEF_MEMBER_MISSING(struct_, get_print_header_footer)) + 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: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return false; + // Verify param: title; type: string_byref_const + DCHECK(!title.empty()); + if (title.empty()) + return false; + + // Execute + int _retval = struct_->get_print_header_footer(struct_, + CefBrowserCppToC::Wrap(browser), + CefFrameCppToC::Wrap(frame), + &printInfo, + url.GetStruct(), + title.GetStruct(), + currentPage, + maxPages, + topLeft.GetWritableStruct(), + topCenter.GetWritableStruct(), + topRight.GetWritableStruct(), + bottomLeft.GetWritableStruct(), + bottomCenter.GetWritableStruct(), + bottomRight.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/print_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/print_handler_ctocpp.h new file mode 100644 index 000000000..1f20efb77 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/print_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefPrintHandlerCToCpp() {} + + // CefPrintHandler methods + virtual bool GetPrintOptions(CefRefPtr browser, + CefPrintOptions& printOptions) OVERRIDE; + virtual bool GetPrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, const CefPrintInfo& printInfo, + const CefString& url, const CefString& title, int currentPage, + int maxPages, CefString& topLeft, CefString& topCenter, + CefString& topRight, CefString& bottomLeft, CefString& bottomCenter, + CefString& bottomRight) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PRINT_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/proxy_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/proxy_handler_ctocpp.cc new file mode 100644 index 000000000..bdb490cea --- /dev/null +++ b/cef1/libcef_dll/ctocpp/proxy_handler_ctocpp.cc @@ -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. +// + +#include "libcef_dll/ctocpp/proxy_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefProxyHandlerCToCpp::GetProxyForUrl(const CefString& url, + CefProxyInfo& proxy_info) { + if (CEF_MEMBER_MISSING(struct_, get_proxy_for_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_->get_proxy_for_url(struct_, + url.GetStruct(), + &proxy_info); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/proxy_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/proxy_handler_ctocpp.h new file mode 100644 index 000000000..bf37ee4cd --- /dev/null +++ b/cef1/libcef_dll/ctocpp/proxy_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_PROXY_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_PROXY_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_proxy_handler.h" +#include "include/capi/cef_proxy_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 CefProxyHandlerCToCpp + : public CefCToCpp { + public: + explicit CefProxyHandlerCToCpp(cef_proxy_handler_t* str) + : CefCToCpp( + str) {} + virtual ~CefProxyHandlerCToCpp() {} + + // CefProxyHandler methods + virtual void GetProxyForUrl(const CefString& url, + CefProxyInfo& proxy_info) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_PROXY_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/read_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/read_handler_ctocpp.cc new file mode 100644 index 000000000..483b8699f --- /dev/null +++ b/cef1/libcef_dll/ctocpp/read_handler_ctocpp.cc @@ -0,0 +1,85 @@ +// 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/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; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/read_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/read_handler_ctocpp.h new file mode 100644 index 000000000..6e56c44b5 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/read_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefReadHandlerCToCpp() {} + + // 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; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_READ_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/render_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/render_handler_ctocpp.cc new file mode 100644 index 000000000..1a3163476 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/render_handler_ctocpp.cc @@ -0,0 +1,186 @@ +// 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/ctocpp/render_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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::GetScreenRect(CefRefPtr browser, + CefRect& rect) { + if (CEF_MEMBER_MISSING(struct_, get_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_screen_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; +} + +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) { + 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); + + // Restore param:dirtyRects; type: simple_vec_byref_const + if (dirtyRectsList) + delete [] dirtyRectsList; +} + +void CefRenderHandlerCToCpp::OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor) { + 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); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/render_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/render_handler_ctocpp.h new file mode 100644 index 000000000..3cd4daa5f --- /dev/null +++ b/cef1/libcef_dll/ctocpp/render_handler_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefRenderHandlerCToCpp() {} + + // CefRenderHandler methods + virtual bool GetViewRect(CefRefPtr browser, + CefRect& rect) OVERRIDE; + virtual bool GetScreenRect(CefRefPtr browser, + CefRect& rect) OVERRIDE; + virtual bool GetScreenPoint(CefRefPtr browser, int viewX, + int viewY, int& screenX, int& screenY) OVERRIDE; + virtual void OnPopupShow(CefRefPtr browser, bool show) OVERRIDE; + virtual void OnPopupSize(CefRefPtr browser, + const CefRect& rect) OVERRIDE; + virtual void OnPaint(CefRefPtr browser, PaintElementType type, + const RectList& dirtyRects, const void* buffer) OVERRIDE; + virtual void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_RENDER_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/request_ctocpp.cc b/cef1/libcef_dll/ctocpp/request_ctocpp.cc new file mode 100644 index 000000000..e34c508ea --- /dev/null +++ b/cef1/libcef_dll/ctocpp/request_ctocpp.cc @@ -0,0 +1,264 @@ +// 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/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::CreateRequest() { + // 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. + +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); +} + +CefRequest::RequestFlags CefRequestCToCpp::GetFlags() { + if (CEF_MEMBER_MISSING(struct_, get_flags)) + return WUR_FLAG_NONE; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_weburlrequest_flags_t _retval = struct_->get_flags(struct_); + + // Return type: simple + return _retval; +} + +void CefRequestCToCpp::SetFlags(RequestFlags 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()); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/request_ctocpp.h b/cef1/libcef_dll/ctocpp/request_ctocpp.h new file mode 100644 index 000000000..77be93ba2 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/request_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefRequestCToCpp() {} + + // CefRequest methods + 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 RequestFlags GetFlags() OVERRIDE; + virtual void SetFlags(RequestFlags flags) OVERRIDE; + virtual CefString GetFirstPartyForCookies() OVERRIDE; + virtual void SetFirstPartyForCookies(const CefString& url) OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/request_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/request_handler_ctocpp.cc new file mode 100644 index 000000000..69cb54f52 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/request_handler_ctocpp.cc @@ -0,0 +1,323 @@ +// 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/cookie_manager_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/response_cpptoc.h" +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" +#include "libcef_dll/ctocpp/content_filter_ctocpp.h" +#include "libcef_dll/ctocpp/download_handler_ctocpp.h" +#include "libcef_dll/ctocpp/request_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefRequestHandlerCToCpp::OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, CefRefPtr request, NavType navType, + bool isRedirect) { + 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), + navType, + isRedirect); + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestHandlerCToCpp::OnBeforeResourceLoad( + CefRefPtr browser, CefRefPtr request, + CefString& redirectUrl, CefRefPtr& resourceStream, + CefRefPtr response, int loadFlags) { + 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: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return false; + // Verify param: response; type: refptr_diff + DCHECK(response.get()); + if (!response.get()) + return false; + + // Translate param: resourceStream; type: refptr_diff_byref + cef_stream_reader_t* resourceStreamStruct = NULL; + if (resourceStream.get()) + resourceStreamStruct = CefStreamReaderCppToC::Wrap(resourceStream); + cef_stream_reader_t* resourceStreamOrig = resourceStreamStruct; + + // Execute + int _retval = struct_->on_before_resource_load(struct_, + CefBrowserCppToC::Wrap(browser), + CefRequestCppToC::Wrap(request), + redirectUrl.GetWritableStruct(), + &resourceStreamStruct, + CefResponseCppToC::Wrap(response), + loadFlags); + + // Restore param:resourceStream; type: refptr_diff_byref + if (resourceStreamStruct) { + if (resourceStreamStruct != resourceStreamOrig) { + resourceStream = CefStreamReaderCppToC::Unwrap(resourceStreamStruct); + } + } else { + resourceStream = NULL; + } + + // Return type: bool + return _retval?true:false; +} + +void CefRequestHandlerCToCpp::OnResourceRedirect(CefRefPtr browser, + 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: old_url; type: string_byref_const + DCHECK(!old_url.empty()); + if (old_url.empty()) + return; + + // Execute + struct_->on_resource_redirect(struct_, + CefBrowserCppToC::Wrap(browser), + old_url.GetStruct(), + new_url.GetWritableStruct()); +} + +void CefRequestHandlerCToCpp::OnResourceResponse(CefRefPtr browser, + const CefString& url, CefRefPtr response, + CefRefPtr& filter) { + if (CEF_MEMBER_MISSING(struct_, on_resource_response)) + 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; + // Verify param: response; type: refptr_diff + DCHECK(response.get()); + if (!response.get()) + return; + + // Translate param: filter; type: refptr_same_byref + cef_content_filter_t* filterStruct = NULL; + if (filter.get()) + filterStruct = CefContentFilterCToCpp::Unwrap(filter); + cef_content_filter_t* filterOrig = filterStruct; + + // Execute + struct_->on_resource_response(struct_, + CefBrowserCppToC::Wrap(browser), + url.GetStruct(), + CefResponseCppToC::Wrap(response), + &filterStruct); + + // Restore param:filter; type: refptr_same_byref + if (filterStruct) { + if (filterStruct != filterOrig) { + filter = CefContentFilterCToCpp::Wrap(filterStruct); + } + } else { + filter = NULL; + } +} + +bool CefRequestHandlerCToCpp::OnProtocolExecution(CefRefPtr browser, + const CefString& url, bool& allowOSExecution) { + if (CEF_MEMBER_MISSING(struct_, on_protocol_execution)) + 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: url; type: string_byref_const + DCHECK(!url.empty()); + if (url.empty()) + return false; + + // Translate param: allowOSExecution; type: bool_byref + int allowOSExecutionInt = allowOSExecution; + + // Execute + int _retval = struct_->on_protocol_execution(struct_, + CefBrowserCppToC::Wrap(browser), + url.GetStruct(), + &allowOSExecutionInt); + + // Restore param:allowOSExecution; type: bool_byref + allowOSExecution = allowOSExecutionInt?true:false; + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestHandlerCToCpp::GetDownloadHandler(CefRefPtr browser, + const CefString& mimeType, const CefString& fileName, int64 contentLength, + CefRefPtr& handler) { + if (CEF_MEMBER_MISSING(struct_, get_download_handler)) + 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: mimeType; type: string_byref_const + DCHECK(!mimeType.empty()); + if (mimeType.empty()) + return false; + // Verify param: fileName; type: string_byref_const + DCHECK(!fileName.empty()); + if (fileName.empty()) + return false; + + // Translate param: handler; type: refptr_same_byref + cef_download_handler_t* handlerStruct = NULL; + if (handler.get()) + handlerStruct = CefDownloadHandlerCToCpp::Unwrap(handler); + cef_download_handler_t* handlerOrig = handlerStruct; + + // Execute + int _retval = struct_->get_download_handler(struct_, + CefBrowserCppToC::Wrap(browser), + mimeType.GetStruct(), + fileName.GetStruct(), + contentLength, + &handlerStruct); + + // Restore param:handler; type: refptr_same_byref + if (handlerStruct) { + if (handlerStruct != handlerOrig) { + handler = CefDownloadHandlerCToCpp::Wrap(handlerStruct); + } + } else { + handler = NULL; + } + + // Return type: bool + return _retval?true:false; +} + +bool CefRequestHandlerCToCpp::GetAuthCredentials(CefRefPtr browser, + bool isProxy, const CefString& host, int port, const CefString& realm, + const CefString& scheme, CefString& username, CefString& password) { + 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: 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; + // Unverified params: realm + + // Execute + int _retval = struct_->get_auth_credentials(struct_, + CefBrowserCppToC::Wrap(browser), + isProxy, + host.GetStruct(), + port, + realm.GetStruct(), + scheme.GetStruct(), + username.GetWritableStruct(), + password.GetWritableStruct()); + + // Return type: bool + return _retval?true:false; +} + +CefRefPtr CefRequestHandlerCToCpp::GetCookieManager( + CefRefPtr browser, const CefString& main_url) { + if (CEF_MEMBER_MISSING(struct_, get_cookie_manager)) + 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: main_url; type: string_byref_const + DCHECK(!main_url.empty()); + if (main_url.empty()) + return NULL; + + // Execute + cef_cookie_manager_t* _retval = struct_->get_cookie_manager(struct_, + CefBrowserCppToC::Wrap(browser), + main_url.GetStruct()); + + // Return type: refptr_diff + return CefCookieManagerCppToC::Unwrap(_retval); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/request_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/request_handler_ctocpp.h new file mode 100644 index 000000000..e67127e54 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/request_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefRequestHandlerCToCpp() {} + + // CefRequestHandler methods + virtual bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, CefRefPtr request, + NavType navType, bool isRedirect) OVERRIDE; + virtual bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, int loadFlags) OVERRIDE; + virtual void OnResourceRedirect(CefRefPtr browser, + const CefString& old_url, CefString& new_url) OVERRIDE; + virtual void OnResourceResponse(CefRefPtr browser, + const CefString& url, CefRefPtr response, + CefRefPtr& filter) OVERRIDE; + virtual bool OnProtocolExecution(CefRefPtr browser, + const CefString& url, bool& allowOSExecution) OVERRIDE; + virtual bool GetDownloadHandler(CefRefPtr browser, + const CefString& mimeType, const CefString& fileName, + int64 contentLength, CefRefPtr& handler) OVERRIDE; + virtual bool GetAuthCredentials(CefRefPtr browser, bool isProxy, + const CefString& host, int port, const CefString& realm, + const CefString& scheme, CefString& username, + CefString& password) OVERRIDE; + virtual CefRefPtr GetCookieManager( + CefRefPtr browser, const CefString& main_url) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_REQUEST_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.cc new file mode 100644 index 000000000..27e996570 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/resource_bundle_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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h new file mode 100644 index 000000000..73279e7fc --- /dev/null +++ b/cef1/libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefResourceBundleHandlerCToCpp() {} + + // CefResourceBundleHandler methods + virtual bool GetLocalizedString(int message_id, CefString& string) OVERRIDE; + virtual 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/cef1/libcef_dll/ctocpp/response_ctocpp.cc b/cef1/libcef_dll/ctocpp/response_ctocpp.cc new file mode 100644 index 000000000..e5bfc0286 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/response_ctocpp.cc @@ -0,0 +1,176 @@ +// 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/ctocpp/response_ctocpp.h" +#include "libcef_dll/transfer_util.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/response_ctocpp.h b/cef1/libcef_dll/ctocpp/response_ctocpp.h new file mode 100644 index 000000000..8ec8a1fc2 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/response_ctocpp.h @@ -0,0 +1,48 @@ +// 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_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) {} + virtual ~CefResponseCToCpp() {} + + // CefResponse methods + 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/cef1/libcef_dll/ctocpp/scheme_handler_callback_ctocpp.cc b/cef1/libcef_dll/ctocpp/scheme_handler_callback_ctocpp.cc new file mode 100644 index 000000000..37773d592 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/scheme_handler_callback_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_handler_callback_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefSchemeHandlerCallbackCToCpp::HeadersAvailable() { + if (CEF_MEMBER_MISSING(struct_, headers_available)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->headers_available(struct_); +} + +void CefSchemeHandlerCallbackCToCpp::BytesAvailable() { + if (CEF_MEMBER_MISSING(struct_, bytes_available)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->bytes_available(struct_); +} + +void CefSchemeHandlerCallbackCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/scheme_handler_callback_ctocpp.h b/cef1/libcef_dll/ctocpp/scheme_handler_callback_ctocpp.h new file mode 100644 index 000000000..27f069086 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/scheme_handler_callback_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_CALLBACK_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_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_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 CefSchemeHandlerCallbackCToCpp + : public CefCToCpp { + public: + explicit CefSchemeHandlerCallbackCToCpp(cef_scheme_handler_callback_t* str) + : CefCToCpp(str) {} + virtual ~CefSchemeHandlerCallbackCToCpp() {} + + // CefSchemeHandlerCallback methods + virtual void HeadersAvailable() OVERRIDE; + virtual void BytesAvailable() OVERRIDE; + virtual void Cancel() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_CALLBACK_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/scheme_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/scheme_handler_ctocpp.cc new file mode 100644 index 000000000..e187a38e4 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/scheme_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/scheme_handler_callback_cpptoc.h" +#include "libcef_dll/ctocpp/scheme_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefSchemeHandlerCToCpp::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), + CefSchemeHandlerCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefSchemeHandlerCToCpp::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 CefSchemeHandlerCToCpp::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, + CefSchemeHandlerCallbackCppToC::Wrap(callback)); + + // Return type: bool + return _retval?true:false; +} + +void CefSchemeHandlerCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/scheme_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/scheme_handler_ctocpp.h new file mode 100644 index 000000000..421675774 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/scheme_handler_ctocpp.h @@ -0,0 +1,48 @@ +// 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_SCHEME_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_SCHEME_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_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 CefSchemeHandlerCToCpp + : public CefCToCpp { + public: + explicit CefSchemeHandlerCToCpp(cef_scheme_handler_t* str) + : CefCToCpp(str) {} + virtual ~CefSchemeHandlerCToCpp() {} + + // CefSchemeHandler 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; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc b/cef1/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.cc new file mode 100644 index 000000000..3c1aac234 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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/request_cpptoc.h" +#include "libcef_dll/ctocpp/scheme_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, const CefString& scheme_name, + CefRefPtr request) { + if (CEF_MEMBER_MISSING(struct_, create)) + 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: 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; + + // Execute + cef_scheme_handler_t* _retval = struct_->create(struct_, + CefBrowserCppToC::Wrap(browser), + scheme_name.GetStruct(), + CefRequestCppToC::Wrap(request)); + + // Return type: refptr_same + return CefSchemeHandlerCToCpp::Wrap(_retval); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h b/cef1/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h new file mode 100644 index 000000000..896bd591c --- /dev/null +++ b/cef1/libcef_dll/ctocpp/scheme_handler_factory_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefSchemeHandlerFactoryCToCpp() {} + + // CefSchemeHandlerFactory methods + virtual CefRefPtr Create(CefRefPtr browser, + const CefString& scheme_name, CefRefPtr request) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_SCHEME_HANDLER_FACTORY_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/stream_reader_ctocpp.cc b/cef1/libcef_dll/ctocpp/stream_reader_ctocpp.cc new file mode 100644 index 000000000..239d5c215 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/stream_reader_ctocpp.cc @@ -0,0 +1,141 @@ +// 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/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; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/stream_reader_ctocpp.h b/cef1/libcef_dll/ctocpp/stream_reader_ctocpp.h new file mode 100644 index 000000000..a153b2642 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/stream_reader_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefStreamReaderCToCpp() {} + + // 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; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_STREAM_READER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/stream_writer_ctocpp.cc b/cef1/libcef_dll/ctocpp/stream_writer_ctocpp.cc new file mode 100644 index 000000000..a520d99a3 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/stream_writer_ctocpp.cc @@ -0,0 +1,123 @@ +// 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/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; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/stream_writer_ctocpp.h b/cef1/libcef_dll/ctocpp/stream_writer_ctocpp.h new file mode 100644 index 000000000..a764b01ad --- /dev/null +++ b/cef1/libcef_dll/ctocpp/stream_writer_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefStreamWriterCToCpp() {} + + // 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; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_STREAM_WRITER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/task_ctocpp.cc b/cef1/libcef_dll/ctocpp/task_ctocpp.cc new file mode 100644 index 000000000..0a2e48a89 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/task_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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(CefThreadId threadId) { + if (CEF_MEMBER_MISSING(struct_, execute)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->execute(struct_, + threadId); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/task_ctocpp.h b/cef1/libcef_dll/ctocpp/task_ctocpp.h new file mode 100644 index 000000000..58dce8a2a --- /dev/null +++ b/cef1/libcef_dll/ctocpp/task_ctocpp.h @@ -0,0 +1,40 @@ +// 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_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) {} + virtual ~CefTaskCToCpp() {} + + // CefTask methods + virtual void Execute(CefThreadId threadId) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_TASK_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/v8accessor_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8accessor_ctocpp.cc new file mode 100644 index 000000000..f3b9b6e56 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8accessor_ctocpp.cc @@ -0,0 +1,99 @@ +// 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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8accessor_ctocpp.h b/cef1/libcef_dll/ctocpp/v8accessor_ctocpp.h new file mode 100644 index 000000000..3ae106e93 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8accessor_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefV8AccessorCToCpp() {} + + // CefV8Accessor methods + virtual bool Get(const CefString& name, const CefRefPtr object, + CefRefPtr& retval, CefString& exception) OVERRIDE; + virtual 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/cef1/libcef_dll/ctocpp/v8context_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8context_ctocpp.cc new file mode 100644 index 000000000..bc1e0559b --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8context_ctocpp.cc @@ -0,0 +1,194 @@ +// 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/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/frame_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::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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8context_ctocpp.h b/cef1/libcef_dll/ctocpp/v8context_ctocpp.h new file mode 100644 index 000000000..314082fee --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8context_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_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) {} + virtual ~CefV8ContextCToCpp() {} + + // CefV8Context methods + 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/cef1/libcef_dll/ctocpp/v8context_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8context_handler_ctocpp.cc new file mode 100644 index 000000000..7c9f8be92 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8context_handler_ctocpp.cc @@ -0,0 +1,80 @@ +// 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/cpptoc/v8context_cpptoc.h" +#include "libcef_dll/ctocpp/v8context_handler_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefV8ContextHandlerCToCpp::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 CefV8ContextHandlerCToCpp::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)); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8context_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/v8context_handler_ctocpp.h new file mode 100644 index 000000000..e02de1d6b --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8context_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_HANDLER_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_V8CONTEXT_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_v8context_handler.h" +#include "include/capi/cef_v8context_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 CefV8ContextHandlerCToCpp + : public CefCToCpp { + public: + explicit CefV8ContextHandlerCToCpp(cef_v8context_handler_t* str) + : CefCToCpp(str) {} + virtual ~CefV8ContextHandlerCToCpp() {} + + // CefV8ContextHandler methods + virtual void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, CefRefPtr context) OVERRIDE; + virtual void OnContextReleased(CefRefPtr browser, + CefRefPtr frame, CefRefPtr context) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_V8CONTEXT_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/v8exception_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8exception_ctocpp.cc new file mode 100644 index 000000000..277f24f01 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8exception_ctocpp.cc @@ -0,0 +1,133 @@ +// 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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8exception_ctocpp.h b/cef1/libcef_dll/ctocpp/v8exception_ctocpp.h new file mode 100644 index 000000000..8966e61a2 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8exception_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefV8ExceptionCToCpp() {} + + // 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/cef1/libcef_dll/ctocpp/v8handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8handler_ctocpp.cc new file mode 100644 index 000000000..9b9c2a790 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8handler_ctocpp.cc @@ -0,0 +1,84 @@ +// 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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8handler_ctocpp.h b/cef1/libcef_dll/ctocpp/v8handler_ctocpp.h new file mode 100644 index 000000000..ea3bba1c3 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8handler_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefV8HandlerCToCpp() {} + + // CefV8Handler methods + virtual 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/cef1/libcef_dll/ctocpp/v8stack_frame_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8stack_frame_ctocpp.cc new file mode 100644 index 000000000..8d685df90 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8stack_frame_ctocpp.cc @@ -0,0 +1,121 @@ +// 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/ctocpp/v8stack_frame_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8stack_frame_ctocpp.h b/cef1/libcef_dll/ctocpp/v8stack_frame_ctocpp.h new file mode 100644 index 000000000..6a6a32999 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8stack_frame_ctocpp.h @@ -0,0 +1,48 @@ +// 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_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) {} + virtual ~CefV8StackFrameCToCpp() {} + + // CefV8StackFrame methods + 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/cef1/libcef_dll/ctocpp/v8stack_trace_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8stack_trace_ctocpp.cc new file mode 100644 index 000000000..a569e3948 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8stack_trace_ctocpp.cc @@ -0,0 +1,65 @@ +// 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/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. + +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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8stack_trace_ctocpp.h b/cef1/libcef_dll/ctocpp/v8stack_trace_ctocpp.h new file mode 100644 index 000000000..05ac92a90 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8stack_trace_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefV8StackTraceCToCpp() {} + + // CefV8StackTrace methods + 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/cef1/libcef_dll/ctocpp/v8value_ctocpp.cc b/cef1/libcef_dll/ctocpp/v8value_ctocpp.cc new file mode 100644 index 000000000..39076c824 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8value_ctocpp.cc @@ -0,0 +1,876 @@ +// 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/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::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 + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // 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 + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // 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 + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return NULL; + + // 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: 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_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 + + // Verify param: key; type: string_byref_const + DCHECK(!key.empty()); + if (key.empty()) + return false; + + // 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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/v8value_ctocpp.h b/cef1/libcef_dll/ctocpp/v8value_ctocpp.h new file mode 100644 index 000000000..15efb7941 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/v8value_ctocpp.h @@ -0,0 +1,88 @@ +// 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_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) {} + virtual ~CefV8ValueCToCpp() {} + + // CefV8Value methods + 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/cef1/libcef_dll/ctocpp/web_plugin_info_ctocpp.cc b/cef1/libcef_dll/ctocpp/web_plugin_info_ctocpp.cc new file mode 100644 index 000000000..4c814e969 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/web_plugin_info_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/web_plugin_info_ctocpp.h b/cef1/libcef_dll/ctocpp/web_plugin_info_ctocpp.h new file mode 100644 index 000000000..b8bd1cbf0 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/web_plugin_info_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefWebPluginInfoCToCpp() {} + + // 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/cef1/libcef_dll/ctocpp/web_urlrequest_client_ctocpp.cc b/cef1/libcef_dll/ctocpp/web_urlrequest_client_ctocpp.cc new file mode 100644 index 000000000..bcddbcbbf --- /dev/null +++ b/cef1/libcef_dll/ctocpp/web_urlrequest_client_ctocpp.cc @@ -0,0 +1,155 @@ +// 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/request_cpptoc.h" +#include "libcef_dll/cpptoc/response_cpptoc.h" +#include "libcef_dll/cpptoc/web_urlrequest_cpptoc.h" +#include "libcef_dll/ctocpp/web_urlrequest_client_ctocpp.h" + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefWebURLRequestClientCToCpp::OnStateChange( + CefRefPtr requester, RequestState state) { + if (CEF_MEMBER_MISSING(struct_, on_state_change)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: requester; type: refptr_diff + DCHECK(requester.get()); + if (!requester.get()) + return; + + // Execute + struct_->on_state_change(struct_, + CefWebURLRequestCppToC::Wrap(requester), + state); +} + +void CefWebURLRequestClientCToCpp::OnRedirect( + CefRefPtr requester, CefRefPtr request, + CefRefPtr response) { + if (CEF_MEMBER_MISSING(struct_, on_redirect)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: requester; type: refptr_diff + DCHECK(requester.get()); + if (!requester.get()) + return; + // Verify param: request; type: refptr_diff + DCHECK(request.get()); + if (!request.get()) + return; + // Verify param: response; type: refptr_diff + DCHECK(response.get()); + if (!response.get()) + return; + + // Execute + struct_->on_redirect(struct_, + CefWebURLRequestCppToC::Wrap(requester), + CefRequestCppToC::Wrap(request), + CefResponseCppToC::Wrap(response)); +} + +void CefWebURLRequestClientCToCpp::OnHeadersReceived( + CefRefPtr requester, CefRefPtr response) { + if (CEF_MEMBER_MISSING(struct_, on_headers_received)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: requester; type: refptr_diff + DCHECK(requester.get()); + if (!requester.get()) + return; + // Verify param: response; type: refptr_diff + DCHECK(response.get()); + if (!response.get()) + return; + + // Execute + struct_->on_headers_received(struct_, + CefWebURLRequestCppToC::Wrap(requester), + CefResponseCppToC::Wrap(response)); +} + +void CefWebURLRequestClientCToCpp::OnProgress( + CefRefPtr requester, uint64 bytesSent, + uint64 totalBytesToBeSent) { + if (CEF_MEMBER_MISSING(struct_, on_progress)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: requester; type: refptr_diff + DCHECK(requester.get()); + if (!requester.get()) + return; + + // Execute + struct_->on_progress(struct_, + CefWebURLRequestCppToC::Wrap(requester), + bytesSent, + totalBytesToBeSent); +} + +void CefWebURLRequestClientCToCpp::OnData(CefRefPtr requester, + const void* data, int dataLength) { + if (CEF_MEMBER_MISSING(struct_, on_data)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: requester; type: refptr_diff + DCHECK(requester.get()); + if (!requester.get()) + return; + // Verify param: data; type: simple_byaddr + DCHECK(data); + if (!data) + return; + + // Execute + struct_->on_data(struct_, + CefWebURLRequestCppToC::Wrap(requester), + data, + dataLength); +} + +void CefWebURLRequestClientCToCpp::OnError( + CefRefPtr requester, ErrorCode errorCode) { + if (CEF_MEMBER_MISSING(struct_, on_error)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: requester; type: refptr_diff + DCHECK(requester.get()); + if (!requester.get()) + return; + + // Execute + struct_->on_error(struct_, + CefWebURLRequestCppToC::Wrap(requester), + errorCode); +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/web_urlrequest_client_ctocpp.h b/cef1/libcef_dll/ctocpp/web_urlrequest_client_ctocpp.h new file mode 100644 index 000000000..405d7380c --- /dev/null +++ b/cef1/libcef_dll/ctocpp/web_urlrequest_client_ctocpp.h @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_URLREQUEST_CLIENT_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_WEB_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_web_urlrequest.h" +#include "include/capi/cef_web_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 CefWebURLRequestClientCToCpp + : public CefCToCpp { + public: + explicit CefWebURLRequestClientCToCpp(cef_web_urlrequest_client_t* str) + : CefCToCpp(str) {} + virtual ~CefWebURLRequestClientCToCpp() {} + + // CefWebURLRequestClient methods + virtual void OnStateChange(CefRefPtr requester, + RequestState state) OVERRIDE; + virtual void OnRedirect(CefRefPtr requester, + CefRefPtr request, + CefRefPtr response) OVERRIDE; + virtual void OnHeadersReceived(CefRefPtr requester, + CefRefPtr response) OVERRIDE; + virtual void OnProgress(CefRefPtr requester, + uint64 bytesSent, uint64 totalBytesToBeSent) OVERRIDE; + virtual void OnData(CefRefPtr requester, const void* data, + int dataLength) OVERRIDE; + virtual void OnError(CefRefPtr requester, + ErrorCode errorCode) OVERRIDE; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WEB_URLREQUEST_CLIENT_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/web_urlrequest_ctocpp.cc b/cef1/libcef_dll/ctocpp/web_urlrequest_ctocpp.cc new file mode 100644 index 000000000..b99490e30 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/web_urlrequest_ctocpp.cc @@ -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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_urlrequest_client_cpptoc.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/web_urlrequest_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefWebURLRequest::CreateWebURLRequest( + 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_web_urlrequest_t* _retval = cef_web_urlrequest_create( + CefRequestCToCpp::Unwrap(request), + CefWebURLRequestClientCppToC::Wrap(client)); + + // Return type: refptr_same + return CefWebURLRequestCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +void CefWebURLRequestCToCpp::Cancel() { + if (CEF_MEMBER_MISSING(struct_, cancel)) + return; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + struct_->cancel(struct_); +} + +CefWebURLRequest::RequestState CefWebURLRequestCToCpp::GetState() { + if (CEF_MEMBER_MISSING(struct_, get_state)) + return WUR_STATE_UNSENT; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_weburlrequest_state_t _retval = struct_->get_state(struct_); + + // Return type: simple + return _retval; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/web_urlrequest_ctocpp.h b/cef1/libcef_dll/ctocpp/web_urlrequest_ctocpp.h new file mode 100644 index 000000000..0a363fc01 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/web_urlrequest_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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_URLREQUEST_CTOCPP_H_ +#define CEF_LIBCEF_DLL_CTOCPP_WEB_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_web_urlrequest.h" +#include "include/capi/cef_web_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 CefWebURLRequestCToCpp + : public CefCToCpp { + public: + explicit CefWebURLRequestCToCpp(cef_web_urlrequest_t* str) + : CefCToCpp(str) {} + virtual ~CefWebURLRequestCToCpp() {} + + // CefWebURLRequest methods + virtual void Cancel() OVERRIDE; + virtual RequestState GetState() OVERRIDE; +}; + +#endif // USING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WEB_URLREQUEST_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/write_handler_ctocpp.cc b/cef1/libcef_dll/ctocpp/write_handler_ctocpp.cc new file mode 100644 index 000000000..df8f3db97 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/write_handler_ctocpp.cc @@ -0,0 +1,85 @@ +// 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/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; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/write_handler_ctocpp.h b/cef1/libcef_dll/ctocpp/write_handler_ctocpp.h new file mode 100644 index 000000000..95713abe9 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/write_handler_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefWriteHandlerCToCpp() {} + + // CefWriteHandler 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; +}; + +#endif // BUILDING_CEF_SHARED +#endif // CEF_LIBCEF_DLL_CTOCPP_WRITE_HANDLER_CTOCPP_H_ + diff --git a/cef1/libcef_dll/ctocpp/xml_reader_ctocpp.cc b/cef1/libcef_dll/ctocpp/xml_reader_ctocpp.cc new file mode 100644 index 000000000..73f0724ad --- /dev/null +++ b/cef1/libcef_dll/ctocpp/xml_reader_ctocpp.cc @@ -0,0 +1,501 @@ +// 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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/xml_reader_ctocpp.h b/cef1/libcef_dll/ctocpp/xml_reader_ctocpp.h new file mode 100644 index 000000000..eeaad3dd6 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/xml_reader_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefXmlReaderCToCpp() {} + + // 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/cef1/libcef_dll/ctocpp/zip_reader_ctocpp.cc b/cef1/libcef_dll/ctocpp/zip_reader_ctocpp.cc new file mode 100644 index 000000000..44401ed48 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/zip_reader_ctocpp.cc @@ -0,0 +1,220 @@ +// 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/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<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/cef1/libcef_dll/ctocpp/zip_reader_ctocpp.h b/cef1/libcef_dll/ctocpp/zip_reader_ctocpp.h new file mode 100644 index 000000000..c9464a7d3 --- /dev/null +++ b/cef1/libcef_dll/ctocpp/zip_reader_ctocpp.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. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only 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) {} + virtual ~CefZipReaderCToCpp() {} + + // 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/cef1/libcef_dll/libcef_dll.cc b/cef1/libcef_dll/libcef_dll.cc new file mode 100644 index 000000000..f04f6fabb --- /dev/null +++ b/cef1/libcef_dll/libcef_dll.cc @@ -0,0 +1,474 @@ +// 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 "include/cef_app.h" +#include "include/capi/cef_app_capi.h" +#include "include/cef_origin_whitelist.h" +#include "include/capi/cef_origin_whitelist_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_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/browser_cpptoc.h" +#include "libcef_dll/cpptoc/cookie_manager_cpptoc.h" +#include "libcef_dll/cpptoc/domdocument_cpptoc.h" +#include "libcef_dll/cpptoc/domevent_cpptoc.h" +#include "libcef_dll/cpptoc/domnode_cpptoc.h" +#include "libcef_dll/cpptoc/drag_data_cpptoc.h" +#include "libcef_dll/cpptoc/frame_cpptoc.h" +#include "libcef_dll/cpptoc/post_data_cpptoc.h" +#include "libcef_dll/cpptoc/post_data_element_cpptoc.h" +#include "libcef_dll/cpptoc/request_cpptoc.h" +#include "libcef_dll/cpptoc/response_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_handler_callback_cpptoc.h" +#include "libcef_dll/cpptoc/stream_reader_cpptoc.h" +#include "libcef_dll/cpptoc/stream_writer_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/web_urlrequest_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/content_filter_ctocpp.h" +#include "libcef_dll/ctocpp/cookie_visitor_ctocpp.h" +#include "libcef_dll/ctocpp/domevent_listener_ctocpp.h" +#include "libcef_dll/ctocpp/domvisitor_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/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/menu_handler_ctocpp.h" +#include "libcef_dll/ctocpp/permission_handler_ctocpp.h" +#include "libcef_dll/ctocpp/print_handler_ctocpp.h" +#include "libcef_dll/ctocpp/proxy_handler_ctocpp.h" +#include "libcef_dll/ctocpp/read_handler_ctocpp.h" +#include "libcef_dll/ctocpp/render_handler_ctocpp.h" +#include "libcef_dll/ctocpp/request_handler_ctocpp.h" +#include "libcef_dll/ctocpp/resource_bundle_handler_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_handler_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_handler_factory_ctocpp.h" +#include "libcef_dll/ctocpp/task_ctocpp.h" +#include "libcef_dll/ctocpp/v8accessor_ctocpp.h" +#include "libcef_dll/ctocpp/v8context_handler_ctocpp.h" +#include "libcef_dll/ctocpp/v8handler_ctocpp.h" +#include "libcef_dll/ctocpp/web_urlrequest_client_ctocpp.h" +#include "libcef_dll/ctocpp/write_handler_ctocpp.h" + + +// GLOBAL FUNCTIONS - Body may be edited by hand. + +CEF_EXPORT int cef_initialize(const struct _cef_settings_t* settings, + struct _cef_app_t* application) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: settings; type: struct_byref_const + DCHECK(settings); + if (!settings) + return 0; + // Unverified params: application + + // Translate param: settings; type: struct_byref_const + CefSettings settingsObj; + if (settings) + settingsObj.Set(*settings, false); + + // Execute + bool _retval = CefInitialize( + settingsObj, + CefAppCToCpp::Wrap(application)); + + // 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_EQ(CefBrowserCppToC::DebugObjCt, 0); + DCHECK_EQ(CefContentFilterCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefCookieManagerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefCookieVisitorCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDOMDocumentCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDOMEventCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDOMEventListenerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDOMNodeCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDOMVisitorCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDisplayHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDownloadHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDragDataCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDragHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefFindHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefFocusHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefFrameCppToC::DebugObjCt, 0); + DCHECK_EQ(CefJSDialogHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefKeyboardHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefLifeSpanHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefLoadHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefMenuHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefPermissionHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefPostDataCppToC::DebugObjCt, 0); + DCHECK_EQ(CefPostDataElementCppToC::DebugObjCt, 0); + DCHECK_EQ(CefPrintHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefProxyHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefReadHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefRenderHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefRequestCppToC::DebugObjCt, 0); + DCHECK_EQ(CefRequestHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefResourceBundleHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefResponseCppToC::DebugObjCt, 0); + DCHECK_EQ(CefSchemeHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefSchemeHandlerCallbackCppToC::DebugObjCt, 0); + DCHECK_EQ(CefSchemeHandlerFactoryCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefStreamReaderCppToC::DebugObjCt, 0); + DCHECK_EQ(CefStreamWriterCppToC::DebugObjCt, 0); + DCHECK_EQ(CefTaskCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8AccessorCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8ContextCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8ContextHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8ExceptionCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8HandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8StackFrameCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8StackTraceCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8ValueCppToC::DebugObjCt, 0); + DCHECK_EQ(CefWebPluginInfoCppToC::DebugObjCt, 0); + DCHECK_EQ(CefWebURLRequestClientCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefWebURLRequestCppToC::DebugObjCt, 0); + DCHECK_EQ(CefWriteHandlerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefXmlReaderCppToC::DebugObjCt, 0); + DCHECK_EQ(CefZipReaderCppToC::DebugObjCt, 0); +#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 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_register_custom_scheme(const cef_string_t* scheme_name, + int is_standard, int is_local, int is_display_isolated) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: scheme_name; type: string_byref_const + DCHECK(scheme_name); + if (!scheme_name) + return 0; + + // Execute + bool _retval = CefRegisterCustomScheme( + CefString(scheme_name), + is_standard?true:false, + is_local?true:false, + is_display_isolated?true:false); + + // 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_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 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 size_t cef_get_web_plugin_count() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = CefGetWebPluginCount(); + + // Return type: simple + return _retval; +} + +CEF_EXPORT struct _cef_web_plugin_info_t* cef_get_web_plugin_info(int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + CefRefPtr _retval = CefGetWebPluginInfo( + index); + + // Return type: refptr_same + return CefWebPluginInfoCppToC::Wrap(_retval); +} + +CEF_EXPORT struct _cef_web_plugin_info_t* cef_get_web_plugin_info_byname( + 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 = CefGetWebPluginInfo( + CefString(name)); + + // Return type: refptr_same + return CefWebPluginInfoCppToC::Wrap(_retval); +} + diff --git a/cef1/libcef_dll/libcef_dll.rc b/cef1/libcef_dll/libcef_dll.rc new file mode 100644 index 000000000..7bb739152 --- /dev/null +++ b/cef1/libcef_dll/libcef_dll.rc @@ -0,0 +1,107 @@ +// 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 + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,CHROME_VERSION_BUILD,CEF_REVISION,0 + PRODUCTVERSION 1,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", "1." 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", "1." 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/cef1/libcef_dll/libcef_dll2.cc b/cef1/libcef_dll/libcef_dll2.cc new file mode 100644 index 000000000..5c7b18acc --- /dev/null +++ b/cef1/libcef_dll/libcef_dll2.cc @@ -0,0 +1,21 @@ +// 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_nplugin.h" +#include "include/capi/cef_nplugin_capi.h" +#include "include/cef_version.h" +#include "libcef_dll/cef_logging.h" + +CEF_EXPORT int cef_build_revision() { + return CEF_REVISION; +} + +CEF_EXPORT int cef_register_plugin(const cef_plugin_info_t* plugin_info) { + DCHECK(plugin_info); + if (!plugin_info) + return 0; + + return CefRegisterPlugin(*plugin_info); +} diff --git a/cef1/libcef_dll/resource.h b/cef1/libcef_dll/resource.h new file mode 100644 index 000000000..9553e1997 --- /dev/null +++ b/cef1/libcef_dll/resource.h @@ -0,0 +1,19 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by libcef_dll.rc +// + +// 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 130 +#define _APS_NEXT_COMMAND_VALUE 32000 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 110 +#endif +#endif diff --git a/cef1/libcef_dll/transfer_util.cpp b/cef1/libcef_dll/transfer_util.cpp new file mode 100644 index 000000000..e9d8d4e22 --- /dev/null +++ b/cef1/libcef_dll/transfer_util.cpp @@ -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/cef1/libcef_dll/transfer_util.h b/cef1/libcef_dll/transfer_util.h new file mode 100644 index 000000000..88dff1a38 --- /dev/null +++ b/cef1/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/cef1/libcef_dll/wrapper/cef_byte_read_handler.cc b/cef1/libcef_dll/wrapper/cef_byte_read_handler.cc new file mode 100644 index 000000000..8ae5b2d8b --- /dev/null +++ b/cef1/libcef_dll/wrapper/cef_byte_read_handler.cc @@ -0,0 +1,60 @@ +// 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 "libcef_dll/cef_logging.h" + +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) { + AutoLock lock_scope(this); + size_t s = (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; + AutoLock lock_scope(this); + switch (whence) { + case SEEK_CUR: + if (offset_ + offset > size_ || offset_ + offset < 0) + break; + offset_ += offset; + rv = 0; + break; + case SEEK_END: { + int64 offset_abs = abs(offset); + 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() { + AutoLock lock_scope(this); + return offset_; +} + +int CefByteReadHandler::Eof() { + AutoLock lock_scope(this); + return (offset_ >= size_); +} diff --git a/cef1/libcef_dll/wrapper/cef_xml_object.cc b/cef1/libcef_dll/wrapper/cef_xml_object.cc new file mode 100644 index 000000000..49b1ff586 --- /dev/null +++ b/cef1/libcef_dll/wrapper/cef_xml_object.cc @@ -0,0 +1,456 @@ +// 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/cef_stream.h" +#include "libcef_dll/cef_logging.h" +#include + +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 << L"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). + DCHECK(false); + 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_; +}; + +} // 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) { + AutoLock lock_scope(this); + 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()); + + AutoLock lock_scope1(this); + AutoLock lock_scope2(object); + + Clear(); + name_ = object->GetName(); + Append(object, true); +} + +void CefXmlObject::Append(CefRefPtr object, + bool overwriteAttributes) { + DCHECK(object.get()); + + AutoLock lock_scope1(this); + AutoLock lock_scope2(object); + + 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; + { + AutoLock lock_scope(this); + new_obj = new CefXmlObject(name_); + new_obj->Append(this, true); + } + return new_obj; +} + +void CefXmlObject::Clear() { + AutoLock lock_scope(this); + ClearChildren(); + ClearAttributes(); +} + +CefString CefXmlObject::GetName() { + CefString name; + { + AutoLock lock_scope(this); + name = name_; + } + return name; +} + +bool CefXmlObject::SetName(const CefString& name) { + DCHECK(!name.empty()); + if (name.empty()) + return false; + + AutoLock lock_scope(this); + name_ = name; + return true; +} + +bool CefXmlObject::HasParent() { + AutoLock lock_scope(this); + return (parent_ != NULL); +} + +CefRefPtr CefXmlObject::GetParent() { + CefRefPtr parent; + { + AutoLock lock_scope(this); + parent = parent_; + } + return parent; +} + +bool CefXmlObject::HasValue() { + AutoLock lock_scope(this); + return !value_.empty(); +} + +CefString CefXmlObject::GetValue() { + CefString value; + { + AutoLock lock_scope(this); + value = value_; + } + return value; +} + +bool CefXmlObject::SetValue(const CefString& value) { + AutoLock lock_scope(this); + DCHECK(children_.empty()); + if (!children_.empty()) + return false; + value_ = value; + return true; +} + +bool CefXmlObject::HasAttributes() { + AutoLock lock_scope(this); + return !attributes_.empty(); +} + +size_t CefXmlObject::GetAttributeCount() { + AutoLock lock_scope(this); + return attributes_.size(); +} + +bool CefXmlObject::HasAttribute(const CefString& name) { + if (name.empty()) + return false; + + AutoLock lock_scope(this); + 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()) { + AutoLock lock_scope(this); + 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; + + AutoLock lock_scope(this); + 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) { + AutoLock lock_scope(this); + attributes = attributes_; + return attributes_.size(); +} + +void CefXmlObject::ClearAttributes() { + AutoLock lock_scope(this); + attributes_.clear(); +} + +bool CefXmlObject::HasChildren() { + AutoLock lock_scope(this); + return !children_.empty(); +} + +size_t CefXmlObject::GetChildCount() { + AutoLock lock_scope(this); + return children_.size(); +} + +bool CefXmlObject::HasChild(CefRefPtr child) { + DCHECK(child.get()); + + AutoLock lock_scope(this); + 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; + + AutoLock lock_scope1(child); + + DCHECK(child->GetParent() == NULL); + if (child->GetParent() != NULL) + return false; + + AutoLock lock_scope2(this); + + children_.push_back(child); + child->SetParent(this); + return true; +} + +bool CefXmlObject::RemoveChild(CefRefPtr child) { + DCHECK(child.get()); + + AutoLock lock_scope(this); + 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) { + AutoLock lock_scope(this); + children = children_; + return children_.size(); +} + +void CefXmlObject::ClearChildren() { + AutoLock lock_scope(this); + 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; + + AutoLock lock_scope(this); + 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; + + AutoLock lock_scope(this); + 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) { + AutoLock lock_scope(this); + if (parent) { + DCHECK(parent_ == NULL); + parent_ = parent; + } else { + DCHECK(parent_ != NULL); + parent_ = NULL; + } +} diff --git a/cef1/libcef_dll/wrapper/cef_zip_archive.cc b/cef1/libcef_dll/wrapper/cef_zip_archive.cc new file mode 100644 index 000000000..b248e40d2 --- /dev/null +++ b/cef1/libcef_dll/wrapper/cef_zip_archive.cc @@ -0,0 +1,162 @@ +// 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. + +#if defined(__linux__) +#include +#endif + +#include +#include +#include "include/wrapper/cef_zip_archive.h" +#include "include/cef_stream.h" +#include "include/cef_zip_reader.h" +#include "include/wrapper/cef_byte_read_handler.h" +#include "libcef_dll/cef_logging.h" + +namespace { + +class CefZipFile : public CefZipArchive::File { + public: + explicit CefZipFile(size_t size) : data_(size) {} + ~CefZipFile() {} + + // Returns the read-only data contained in the file. + virtual const unsigned char* GetData() { return &data_[0]; } + + // Returns the size of the data in the file. + virtual size_t GetDataSize() { return data_.size(); } + + // Returns a CefStreamReader object for streaming the contents of the file. + virtual CefRefPtr GetStreamReader() { + CefRefPtr handler( + new CefByteReadHandler(GetData(), GetDataSize(), this)); + return CefStreamReader::CreateForHandler(handler); + } + + std::vector* GetDataVector() { return &data_; } + + private: + std::vector data_; + + IMPLEMENT_REFCOUNTING(CefZipFile); +}; + +} // namespace + +// CefZipArchive implementation + +CefZipArchive::CefZipArchive() { +} + +CefZipArchive::~CefZipArchive() { +} + +size_t CefZipArchive::Load(CefRefPtr stream, + bool overwriteExisting) { + AutoLock lock_scope(this); + + CefRefPtr reader(CefZipReader::Create(stream)); + if (!reader.get()) + return 0; + + if (!reader->MoveToFirstFile()) + return 0; + + std::wstring name; + CefRefPtr contents; + FileMap::iterator it; + std::vector* data; + size_t count = 0, size, offset; + + do { + size = static_cast(reader->GetFileSize()); + if (size == 0) { + // Skip directories and empty files. + continue; + } + + if (!reader->OpenFile(CefString())) + break; + + name = reader->GetFileName(); + std::transform(name.begin(), name.end(), name.begin(), towlower); + + it = contents_.find(name); + if (it != contents_.end()) { + if (overwriteExisting) + contents_.erase(it); + else // Skip files that already exist. + continue; + } + + contents = new CefZipFile(size); + data = contents->GetDataVector(); + 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() { + AutoLock lock_scope(this); + contents_.clear(); +} + +size_t CefZipArchive::GetFileCount() { + AutoLock lock_scope(this); + return contents_.size(); +} + +bool CefZipArchive::HasFile(const CefString& fileName) { + std::wstring str = fileName; + std::transform(str.begin(), str.end(), str.begin(), towlower); + + AutoLock lock_scope(this); + FileMap::const_iterator it = contents_.find(CefString(str)); + return (it != contents_.end()); +} + +CefRefPtr CefZipArchive::GetFile( + const CefString& fileName) { + std::wstring str = fileName; + std::transform(str.begin(), str.end(), str.begin(), towlower); + + AutoLock lock_scope(this); + FileMap::const_iterator it = contents_.find(CefString(str)); + if (it != contents_.end()) + return it->second; + return NULL; +} + +bool CefZipArchive::RemoveFile(const CefString& fileName) { + std::wstring str = fileName; + std::transform(str.begin(), str.end(), str.begin(), towlower); + + AutoLock lock_scope(this); + FileMap::iterator it = contents_.find(CefString(str)); + if (it != contents_.end()) { + contents_.erase(it); + return true; + } + return false; +} + +size_t CefZipArchive::GetFiles(FileMap& map) { + AutoLock lock_scope(this); + map = contents_; + return contents_.size(); +} diff --git a/cef1/libcef_dll/wrapper/libcef_dll_wrapper.cc b/cef1/libcef_dll/wrapper/libcef_dll_wrapper.cc new file mode 100644 index 000000000..14496bfff --- /dev/null +++ b/cef1/libcef_dll/wrapper/libcef_dll_wrapper.cc @@ -0,0 +1,444 @@ +// 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 "include/cef_app.h" +#include "include/capi/cef_app_capi.h" +#include "include/cef_origin_whitelist.h" +#include "include/capi/cef_origin_whitelist_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_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/content_filter_cpptoc.h" +#include "libcef_dll/cpptoc/cookie_visitor_cpptoc.h" +#include "libcef_dll/cpptoc/domevent_listener_cpptoc.h" +#include "libcef_dll/cpptoc/domvisitor_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/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/menu_handler_cpptoc.h" +#include "libcef_dll/cpptoc/permission_handler_cpptoc.h" +#include "libcef_dll/cpptoc/print_handler_cpptoc.h" +#include "libcef_dll/cpptoc/proxy_handler_cpptoc.h" +#include "libcef_dll/cpptoc/read_handler_cpptoc.h" +#include "libcef_dll/cpptoc/render_handler_cpptoc.h" +#include "libcef_dll/cpptoc/request_handler_cpptoc.h" +#include "libcef_dll/cpptoc/resource_bundle_handler_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_handler_cpptoc.h" +#include "libcef_dll/cpptoc/scheme_handler_factory_cpptoc.h" +#include "libcef_dll/cpptoc/task_cpptoc.h" +#include "libcef_dll/cpptoc/v8accessor_cpptoc.h" +#include "libcef_dll/cpptoc/v8context_handler_cpptoc.h" +#include "libcef_dll/cpptoc/v8handler_cpptoc.h" +#include "libcef_dll/cpptoc/web_urlrequest_client_cpptoc.h" +#include "libcef_dll/cpptoc/write_handler_cpptoc.h" +#include "libcef_dll/ctocpp/browser_ctocpp.h" +#include "libcef_dll/ctocpp/cookie_manager_ctocpp.h" +#include "libcef_dll/ctocpp/domdocument_ctocpp.h" +#include "libcef_dll/ctocpp/domevent_ctocpp.h" +#include "libcef_dll/ctocpp/domnode_ctocpp.h" +#include "libcef_dll/ctocpp/drag_data_ctocpp.h" +#include "libcef_dll/ctocpp/frame_ctocpp.h" +#include "libcef_dll/ctocpp/post_data_ctocpp.h" +#include "libcef_dll/ctocpp/post_data_element_ctocpp.h" +#include "libcef_dll/ctocpp/request_ctocpp.h" +#include "libcef_dll/ctocpp/response_ctocpp.h" +#include "libcef_dll/ctocpp/scheme_handler_callback_ctocpp.h" +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/stream_writer_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/web_urlrequest_ctocpp.h" +#include "libcef_dll/ctocpp/xml_reader_ctocpp.h" +#include "libcef_dll/ctocpp/zip_reader_ctocpp.h" + +// Define used to facilitate parsing. +#define CEF_GLOBAL + + +// GLOBAL METHODS - Body may be edited by hand. + +CEF_GLOBAL bool CefInitialize(const CefSettings& settings, + CefRefPtr application) { + int build_revision = cef_build_revision(); + if (build_revision != CEF_REVISION) { + // The libcef build revision does not match the CEF API revision. + DCHECK(false); + return false; + } + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: application + + // Execute + int _retval = cef_initialize( + &settings, + CefAppCppToC::Wrap(application)); + + // 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_EQ(CefBrowserCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefContentFilterCppToC::DebugObjCt, 0); + DCHECK_EQ(CefCookieManagerCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefCookieVisitorCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDOMDocumentCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDOMEventCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDOMEventListenerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDOMNodeCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDOMVisitorCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDisplayHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDownloadHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefDragDataCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefDragHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefFindHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefFocusHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefFrameCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefJSDialogHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefKeyboardHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefLifeSpanHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefLoadHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefMenuHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefPermissionHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefPostDataCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefPostDataElementCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefPrintHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefProxyHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefReadHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefRenderHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefRequestCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefRequestHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefResourceBundleHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefResponseCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefSchemeHandlerCallbackCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefSchemeHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefSchemeHandlerFactoryCppToC::DebugObjCt, 0); + DCHECK_EQ(CefStreamReaderCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefStreamWriterCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefTaskCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8AccessorCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8ContextCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8ContextHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8ExceptionCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8HandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefV8StackFrameCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8StackTraceCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefV8ValueCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefWebPluginInfoCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefWebURLRequestCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefWebURLRequestClientCppToC::DebugObjCt, 0); + DCHECK_EQ(CefWriteHandlerCppToC::DebugObjCt, 0); + DCHECK_EQ(CefXmlReaderCToCpp::DebugObjCt, 0); + DCHECK_EQ(CefZipReaderCToCpp::DebugObjCt, 0); +#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 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 CefRegisterCustomScheme(const CefString& scheme_name, + bool is_standard, bool is_local, bool is_display_isolated) { + // 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 = cef_register_custom_scheme( + scheme_name.GetStruct(), + is_standard, + is_local, + is_display_isolated); + + // 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 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 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 size_t CefGetWebPluginCount() { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + size_t _retval = cef_get_web_plugin_count(); + + // Return type: simple + return _retval; +} + +CEF_GLOBAL CefRefPtr CefGetWebPluginInfo(int index) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_web_plugin_info_t* _retval = cef_get_web_plugin_info( + index); + + // Return type: refptr_same + return CefWebPluginInfoCToCpp::Wrap(_retval); +} + +CEF_GLOBAL CefRefPtr CefGetWebPluginInfo( + 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_web_plugin_info_t* _retval = cef_get_web_plugin_info_byname( + name.GetStruct()); + + // Return type: refptr_same + return CefWebPluginInfoCToCpp::Wrap(_retval); +} + diff --git a/cef1/libcef_dll/wrapper/libcef_dll_wrapper2.cc b/cef1/libcef_dll/wrapper/libcef_dll_wrapper2.cc new file mode 100644 index 000000000..cb34a0a55 --- /dev/null +++ b/cef1/libcef_dll/wrapper/libcef_dll_wrapper2.cc @@ -0,0 +1,10 @@ +// 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_nplugin.h" +#include "include/capi/cef_nplugin_capi.h" + +bool CefRegisterPlugin(const CefPluginInfo& plugin_info) { + return cef_register_plugin(&plugin_info)?true:false; +} diff --git a/cef1/patch/README.txt b/cef1/patch/README.txt new file mode 100644 index 000000000..f96fe36a4 --- /dev/null +++ b/cef1/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/cef1/patch/patch.cfg b/cef1/patch/patch.cfg new file mode 100644 index 000000000..f4122f7ec --- /dev/null +++ b/cef1/patch/patch.cfg @@ -0,0 +1,30 @@ +# 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 = [ + { + # http://codereview.chromium.org/8086022/ + 'name': 'build', + 'path': '../build/', + }, + { + # http://codereview.chromium.org/6730028/ + 'name': 'base', + 'path': '../base/', + }, + { + # http://code.google.com/p/gyp/issues/detail?id=223 + 'name': 'tools_gyp', + 'path': '../tools/gyp/', + }, + { + # http://code.google.com/p/chromiumembedded/issues/detail?id=364 + 'name': 'spi_webcore_364', + 'path': '../third_party/WebKit/Source/WebCore/', + 'condition': 'CEF_SPI_BUILD', + }, +] diff --git a/cef1/patch/patches/base.patch b/cef1/patch/patches/base.patch new file mode 100644 index 000000000..249de41f2 --- /dev/null +++ b/cef1/patch/patches/base.patch @@ -0,0 +1,33 @@ +Index: message_loop.cc +=================================================================== +--- message_loop.cc (revision 140240) ++++ message_loop.cc (working copy) +@@ -369,9 +369,13 @@ + } + + void MessageLoop::AssertIdle() const { ++ DCHECK(IsIdle()); ++} ++ ++bool MessageLoop::IsIdle() const { + // We only check |incoming_queue_|, since we don't want to lock |work_queue_|. + base::AutoLock lock(incoming_queue_lock_); +- DCHECK(incoming_queue_.empty()); ++ return incoming_queue_.empty(); + } + + bool MessageLoop::is_running() const { +Index: message_loop.h +=================================================================== +--- message_loop.h (revision 140240) ++++ message_loop.h (working copy) +@@ -347,6 +347,9 @@ + // Asserts that the MessageLoop is "idle". + void AssertIdle() const; + ++ // Returns true if the MessageLoop is "idle". ++ bool IsIdle() const; ++ + #if defined(OS_WIN) + void set_os_modal_loop(bool os_modal_loop) { + os_modal_loop_ = os_modal_loop; diff --git a/cef1/patch/patches/build.patch b/cef1/patch/patches/build.patch new file mode 100644 index 000000000..e73ddb02c --- /dev/null +++ b/cef1/patch/patches/build.patch @@ -0,0 +1,27 @@ +Index: common.gypi +=================================================================== +--- common.gypi (revision 102269) ++++ common.gypi (working copy) +@@ -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 +Index: mac/strip_save_dsym +=================================================================== +--- mac/strip_save_dsym (revision 102269) ++++ mac/strip_save_dsym (working copy) +@@ -48,7 +48,7 @@ + "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/cef1/patch/patches/spi_webcore_364.patch b/cef1/patch/patches/spi_webcore_364.patch new file mode 100644 index 000000000..9f66afaef --- /dev/null +++ b/cef1/patch/patches/spi_webcore_364.patch @@ -0,0 +1,35 @@ +Index: page/FrameView.cpp +=================================================================== +--- page/FrameView.cpp (revision 112327) ++++ page/FrameView.cpp (working copy) +@@ -159,10 +159,12 @@ + if (!page) + return; + ++#if 0 + if (m_frame == page->mainFrame()) { + ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed); + ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed); + } ++#endif + } + + PassRefPtr FrameView::create(Frame* frame) +Index: platform/chromium/ScrollbarOverlayUtilitiesChromiumMac.mm +=================================================================== +--- platform/chromium/ScrollbarOverlayUtilitiesChromiumMac.mm (revision 101144) ++++ platform/chromium/ScrollbarOverlayUtilitiesChromiumMac.mm (working copy) +@@ -356,9 +356,13 @@ + + bool isScrollbarOverlayAPIAvailable() + { ++#if 0 + static bool apiAvailable = [lookUpNSScrollerImpClass() respondsToSelector:@selector(scrollerImpWithStyle:controlSize:horizontal:replacingScrollerImp:)] && + [lookUpNSScrollerImpPairClass() instancesRespondToSelector:@selector(scrollerStyle)]; + return apiAvailable; ++#else ++ return false; ++#endif + } + + #endif // USE(WK_SCROLLBAR_PAINTER) diff --git a/cef1/patch/patches/tools_gyp.patch b/cef1/patch/patches/tools_gyp.patch new file mode 100644 index 000000000..77beae74f --- /dev/null +++ b/cef1/patch/patches/tools_gyp.patch @@ -0,0 +1,14 @@ +Index: pylib/gyp/input.py +=================================================================== +--- pylib/gyp/input.py (revision 1402) ++++ pylib/gyp/input.py (working copy) +@@ -684,7 +684,8 @@ + # that don't load quickly, this can be faster than + # +#include +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_v8.h" + + +// Implementation of the V8 handler class for the "window.cef_test.Dump" +// function. +class ClientV8FunctionHandler : public CefV8Handler { + public: + ClientV8FunctionHandler() {} + virtual ~ClientV8FunctionHandler() {} + + // Execute with the specified argument list and return value. Return true if + // the method was handled. + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + if (name == "Dump") { + // The "Dump" function will return a human-readable dump of the input + // arguments. + std::stringstream stream; + size_t i; + + for (i = 0; i < arguments.size(); ++i) { + stream << "arg[" << i << "] = "; + PrintValue(arguments[i], stream, 0); + stream << "\n"; + } + + retval = CefV8Value::CreateString(stream.str()); + return true; + } else if (name == "Call") { + // The "Call" function will execute a function to get an object and then + // return the result of calling a function belonging to that object. The + // first arument is the function that will return an object and the second + // argument is the function that will be called on that returned object. + int argSize = arguments.size(); + if (argSize < 2 || !arguments[0]->IsFunction() + || !arguments[1]->IsString()) + return false; + + CefV8ValueList argList; + + // Execute the function stored in the first argument to retrieve an + // object. + CefRefPtr objectPtr = + arguments[0]->ExecuteFunction(object, argList); + if (arguments[0]->HasException()) + exception = arguments[0]->GetException()->GetMessage(); + + // Verify that the returned value is an object. + if (!objectPtr.get() || !objectPtr->IsObject()) + return false; + + // Retrieve the member function specified by name in the second argument + // from the object. + CefRefPtr funcPtr = + objectPtr->GetValue(arguments[1]->GetStringValue()); + // Verify that the returned value is a function. + if (!funcPtr.get() || !funcPtr->IsFunction()) + return false; + + // Pass any additional arguments on to the member function. + for (int i = 2; i < argSize; ++i) + argList.push_back(arguments[i]); + + // Execute the member function. + funcPtr->ExecuteFunction(arguments[0], argList); + if (funcPtr->HasException()) + exception = funcPtr->GetException()->GetMessage(); + return true; + } + return false; + } + + // Simple function for formatted output of a V8 value. + void PrintValue(CefRefPtr value, std::stringstream &stream, + int indent) { + std::stringstream indent_stream; + for (int i = 0; i < indent; ++i) + indent_stream << " "; + std::string indent_str = indent_stream.str(); + + if (value->IsUndefined()) + stream << "(undefined)"; + else if (value->IsNull()) + stream << "(null)"; + else if (value->IsBool()) + stream << "(bool) " << (value->GetBoolValue() ? "true" : "false"); + else if (value->IsInt()) + stream << "(int) " << value->GetIntValue(); + else if (value->IsDouble()) + stream << "(double) " << value->GetDoubleValue(); + else if (value->IsString()) + stream << "(string) " << std::string(value->GetStringValue()); + else if (value->IsFunction()) + stream << "(function) " << std::string(value->GetFunctionName()); + else if (value->IsArray()) { + stream << "(array) ["; + int len = value->GetArrayLength(); + for (int i = 0; i < len; ++i) { + stream << "\n " << indent_str.c_str() << i << " = "; + PrintValue(value->GetValue(i), stream, indent+1); + } + stream << "\n" << indent_str.c_str() << "]"; + } else if (value->IsObject()) { + stream << "(object) ["; + std::vector keys; + if (value->GetKeys(keys)) { + for (size_t i = 0; i < keys.size(); ++i) { + stream << "\n " << indent_str.c_str() << keys[i].c_str() << " = "; + PrintValue(value->GetValue(keys[i]), stream, indent+1); + } + } + stream << "\n" << indent_str.c_str() << "]"; + } + } + + IMPLEMENT_REFCOUNTING(ClientV8FunctionHandler); +}; + + +void InitBindingTest(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object) { + // Create the new V8 object. + CefRefPtr testObjPtr = CefV8Value::CreateObject(NULL); + // Add the new V8 object to the global window object with the name + // "cef_test". + object->SetValue("cef_test", testObjPtr, V8_PROPERTY_ATTRIBUTE_NONE); + + // Create an instance of ClientV8FunctionHandler as the V8 handler. + CefRefPtr handlerPtr = new ClientV8FunctionHandler(); + + // Add a new V8 function to the cef_test object with the name "Dump". + testObjPtr->SetValue("Dump", + CefV8Value::CreateFunction("Dump", handlerPtr), + V8_PROPERTY_ATTRIBUTE_NONE); + // Add a new V8 function to the cef_test object with the name "Call". + testObjPtr->SetValue("Call", + CefV8Value::CreateFunction("Call", handlerPtr), + V8_PROPERTY_ATTRIBUTE_NONE); +} + +void RunBindingTest(CefRefPtr browser) { + std::string html = + "ClientV8FunctionHandler says:
"
+    ""
+    "
"; + browser->GetMainFrame()->LoadString(html, "about:blank"); +} diff --git a/cef1/tests/cefclient/binding_test.h b/cef1/tests/cefclient/binding_test.h new file mode 100644 index 000000000..4aa7948a5 --- /dev/null +++ b/cef1/tests/cefclient/binding_test.h @@ -0,0 +1,23 @@ +// 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_BINDING_TEST_H_ +#define CEF_TESTS_CEFCLIENT_BINDING_TEST_H_ +#pragma once + +#include "include/cef_base.h" + +class CefBrowser; +class CefFrame; +class CefV8Value; + +// Add the V8 bindings. +void InitBindingTest(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr object); + +// Run the test. +void RunBindingTest(CefRefPtr browser); + +#endif // CEF_TESTS_CEFCLIENT_BINDING_TEST_H_ diff --git a/cef1/tests/cefclient/cefclient.cpp b/cef1/tests/cefclient/cefclient.cpp new file mode 100644 index 000000000..d00d72b75 --- /dev/null +++ b/cef1/tests/cefclient/cefclient.cpp @@ -0,0 +1,652 @@ +// 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 "cefclient/cefclient.h" +#include +#include +#include +#include +#include "include/cef_app.h" +#include "include/cef_browser.h" +#include "include/cef_command_line.h" +#include "include/cef_frame.h" +#include "include/cef_runnable.h" +#include "include/cef_web_plugin.h" +#include "include/cef_web_urlrequest.h" +#include "cefclient/cefclient_switches.h" +#include "cefclient/client_handler.h" +#include "cefclient/binding_test.h" +#include "cefclient/string_util.h" +#include "cefclient/util.h" + +namespace { + +void UIT_InvokeScript(CefRefPtr browser) { + REQUIRE_UI_THREAD(); + + CefRefPtr frame = browser->GetMainFrame(); + CefRefPtr v8Context = frame->GetV8Context(); + CefString url = frame->GetURL(); + + if (!v8Context.get()) { + frame->ExecuteJavaScript("alert('Failed to get V8 context!');", url, 0); + } else if (v8Context->Enter()) { + CefRefPtr globalObj = v8Context->GetGlobal(); + CefRefPtr evalFunc = globalObj->GetValue("eval"); + + CefRefPtr arg0 = CefV8Value::CreateString("1+2"); + + CefV8ValueList args; + args.push_back(arg0); + + CefRefPtr retVal = + evalFunc->ExecuteFunctionWithContext(v8Context, globalObj, args); + if (!evalFunc->HasException()) { + if (retVal.get()) { + frame->ExecuteJavaScript( + std::string("alert('InvokeScript returns ") + + retVal->GetStringValue().ToString() + "!');", + url, 0); + } else { + frame->ExecuteJavaScript( + std::string("alert('InvokeScript returned no value!"), url, 0); + } + } else { + frame->ExecuteJavaScript( + std::string("alert('InvokeScript returns exception: ") + + evalFunc->GetException()->GetMessage().ToString() + "!');", + url, 0); + } + + v8Context->Exit(); + } else { + frame->ExecuteJavaScript("alert('Failed to enter into V8 context!');", + url, 0); + } +} + +void UIT_RunPluginInfoTest(CefRefPtr browser) { + std::string html = "Plugin Info Test"; + + // Find the flash plugin first to test that get by name works. + std::string flash_name; + CefRefPtr info = CefGetWebPluginInfo("Shockwave Flash"); + if (info.get()) { + flash_name = info->GetName(); + html += "\nFlash is installed!" + "
Name: " + flash_name + + "\n
Description: " + info->GetDescription().ToString() + + "\n
Version: " + info->GetVersion().ToString() + + "\n
Path: " + info->GetPath().ToString(); + } + + if (!flash_name.empty()) { + html += "\n

Other installed plugins:"; + } else { + html += "\nInstalled plugins:"; + } + + // Display all other plugins. + size_t count = CefGetWebPluginCount(); + for (size_t i = 0; i < count; ++i) { + CefRefPtr info = CefGetWebPluginInfo(i); + ASSERT(info.get()); + if (!flash_name.empty() && info->GetName() == flash_name) + continue; + + html += "\n

Name: " + info->GetName().ToString() + + "\n
Description: " + info->GetDescription().ToString() + + "\n
Version: " + info->GetVersion().ToString() + + "\n
Path: " + info->GetPath().ToString(); + } + + html += ""; + + browser->GetMainFrame()->LoadString(html, "http://tests/plugin_info"); +} + +// Return the int representation of the specified string. +int GetIntValue(const CefString& str) { + if (str.empty()) + return 0; + + std::string stdStr = str; + return atoi(stdStr.c_str()); +} + + +// ClientApp implementation. +class ClientApp : public CefApp, + public CefProxyHandler { + public: + ClientApp(cef_proxy_type_t proxy_type, const CefString& proxy_config) + : proxy_type_(proxy_type), + proxy_config_(proxy_config) { + } + + // CefApp methods + virtual CefRefPtr GetProxyHandler() OVERRIDE { return this; } + + // CefProxyHandler methods + virtual void GetProxyForUrl(const CefString& url, + CefProxyInfo& proxy_info) OVERRIDE { + proxy_info.proxyType = proxy_type_; + if (!proxy_config_.empty()) + CefString(&proxy_info.proxyList) = proxy_config_; + } + + protected: + cef_proxy_type_t proxy_type_; + CefString proxy_config_; + + IMPLEMENT_REFCOUNTING(ClientApp); +}; + +} // namespace + +CefRefPtr g_handler; +CefRefPtr g_command_line; + +CefRefPtr AppGetBrowser() { + if (!g_handler.get()) + return NULL; + return g_handler->GetBrowser(); +} + +CefWindowHandle AppGetMainHwnd() { + if (!g_handler.get()) + return NULL; + return g_handler->GetMainHwnd(); +} + +void AppInitCommandLine(int argc, const char* const* argv) { + g_command_line = CefCommandLine::CreateCommandLine(); +#if defined(OS_WIN) + g_command_line->InitFromString(::GetCommandLineW()); +#else + g_command_line->InitFromArgv(argc, argv); +#endif +} + +// Returns the application command line object. +CefRefPtr AppGetCommandLine() { + return g_command_line; +} + +// Returns the application settings based on command line arguments. +void AppGetSettings(CefSettings& settings, CefRefPtr& app) { + ASSERT(g_command_line.get()); + if (!g_command_line.get()) + return; + + CefString str; + +#if defined(OS_WIN) + settings.multi_threaded_message_loop = + g_command_line->HasSwitch(cefclient::kMultiThreadedMessageLoop); +#endif + + CefString(&settings.cache_path) = + g_command_line->GetSwitchValue(cefclient::kCachePath); + CefString(&settings.user_agent) = + g_command_line->GetSwitchValue(cefclient::kUserAgent); + CefString(&settings.product_version) = + g_command_line->GetSwitchValue(cefclient::kProductVersion); + CefString(&settings.locale) = + g_command_line->GetSwitchValue(cefclient::kLocale); + CefString(&settings.log_file) = + g_command_line->GetSwitchValue(cefclient::kLogFile); + + { + std::string str = g_command_line->GetSwitchValue(cefclient::kLogSeverity); + bool invalid = false; + if (!str.empty()) { + if (str == cefclient::kLogSeverity_Verbose) + settings.log_severity = LOGSEVERITY_VERBOSE; + else if (str == cefclient::kLogSeverity_Info) + settings.log_severity = LOGSEVERITY_INFO; + else if (str == cefclient::kLogSeverity_Warning) + settings.log_severity = LOGSEVERITY_WARNING; + else if (str == cefclient::kLogSeverity_Error) + settings.log_severity = LOGSEVERITY_ERROR; + else if (str == cefclient::kLogSeverity_ErrorReport) + settings.log_severity = LOGSEVERITY_ERROR_REPORT; + else if (str == cefclient::kLogSeverity_Disable) + settings.log_severity = LOGSEVERITY_DISABLE; + else + invalid = true; + } + if (str.empty() || invalid) { +#ifdef NDEBUG + // Only log error messages and higher in release build. + settings.log_severity = LOGSEVERITY_ERROR; +#endif + } + } + + { + std::string str = g_command_line->GetSwitchValue(cefclient::kGraphicsImpl); + if (!str.empty()) { +#if defined(OS_WIN) + if (str == cefclient::kGraphicsImpl_Angle) + settings.graphics_implementation = ANGLE_IN_PROCESS; + else if (str == cefclient::kGraphicsImpl_AngleCmdBuffer) + settings.graphics_implementation = ANGLE_IN_PROCESS_COMMAND_BUFFER; + else +#endif + if (str == cefclient::kGraphicsImpl_Desktop) + settings.graphics_implementation = DESKTOP_IN_PROCESS; + else if (str == cefclient::kGraphicsImpl_DesktopCmdBuffer) + settings.graphics_implementation = DESKTOP_IN_PROCESS_COMMAND_BUFFER; + } + } + + settings.local_storage_quota = GetIntValue( + g_command_line->GetSwitchValue(cefclient::kLocalStorageQuota)); + settings.session_storage_quota = GetIntValue( + g_command_line->GetSwitchValue(cefclient::kSessionStorageQuota)); + + CefString(&settings.javascript_flags) = + g_command_line->GetSwitchValue(cefclient::kJavascriptFlags); + + CefString(&settings.pack_file_path) = + g_command_line->GetSwitchValue(cefclient::kPackFilePath); + CefString(&settings.locales_dir_path) = + g_command_line->GetSwitchValue(cefclient::kLocalesDirPath); + + settings.pack_loading_disabled = + g_command_line->HasSwitch(cefclient::kPackLoadingDisabled); + + // Retrieve command-line proxy configuration, if any. + bool has_proxy = false; + cef_proxy_type_t proxy_type = PROXY_TYPE_DIRECT; + CefString proxy_config; + + if (g_command_line->HasSwitch(cefclient::kProxyType)) { + std::string str = g_command_line->GetSwitchValue(cefclient::kProxyType); + if (str == cefclient::kProxyType_Direct) { + has_proxy = true; + proxy_type = PROXY_TYPE_DIRECT; + } else if (str == cefclient::kProxyType_Named || + str == cefclient::kProxyType_Pac) { + proxy_config = g_command_line->GetSwitchValue(cefclient::kProxyConfig); + if (!proxy_config.empty()) { + has_proxy = true; + proxy_type = (str == cefclient::kProxyType_Named? + PROXY_TYPE_NAMED:PROXY_TYPE_PAC_STRING); + } + } + } + + if (has_proxy) { + // Provide a ClientApp instance to handle proxy resolution. + app = new ClientApp(proxy_type, proxy_config); + } +} + +// Returns the application browser settings based on command line arguments. +void AppGetBrowserSettings(CefBrowserSettings& settings) { + ASSERT(g_command_line.get()); + if (!g_command_line.get()) + return; + + settings.drag_drop_disabled = + g_command_line->HasSwitch(cefclient::kDragDropDisabled); + settings.load_drops_disabled = + g_command_line->HasSwitch(cefclient::kLoadDropsDisabled); + settings.history_disabled = + g_command_line->HasSwitch(cefclient::kHistoryDisabled); + settings.remote_fonts_disabled = + g_command_line->HasSwitch(cefclient::kRemoteFontsDisabled); + + CefString(&settings.default_encoding) = + g_command_line->GetSwitchValue(cefclient::kDefaultEncoding); + + settings.encoding_detector_enabled = + g_command_line->HasSwitch(cefclient::kEncodingDetectorEnabled); + settings.javascript_disabled = + g_command_line->HasSwitch(cefclient::kJavascriptDisabled); + settings.javascript_open_windows_disallowed = + g_command_line->HasSwitch(cefclient::kJavascriptOpenWindowsDisallowed); + settings.javascript_close_windows_disallowed = + g_command_line->HasSwitch(cefclient::kJavascriptCloseWindowsDisallowed); + settings.javascript_access_clipboard_disallowed = + g_command_line->HasSwitch( + cefclient::kJavascriptAccessClipboardDisallowed); + settings.dom_paste_disabled = + g_command_line->HasSwitch(cefclient::kDomPasteDisabled); + settings.caret_browsing_enabled = + g_command_line->HasSwitch(cefclient::kCaretBrowsingDisabled); + settings.java_disabled = + g_command_line->HasSwitch(cefclient::kJavaDisabled); + settings.plugins_disabled = + g_command_line->HasSwitch(cefclient::kPluginsDisabled); + settings.universal_access_from_file_urls_allowed = + g_command_line->HasSwitch(cefclient::kUniversalAccessFromFileUrlsAllowed); + settings.file_access_from_file_urls_allowed = + g_command_line->HasSwitch(cefclient::kFileAccessFromFileUrlsAllowed); + settings.web_security_disabled = + g_command_line->HasSwitch(cefclient::kWebSecurityDisabled); + settings.xss_auditor_enabled = + g_command_line->HasSwitch(cefclient::kXssAuditorEnabled); + settings.image_load_disabled = + g_command_line->HasSwitch(cefclient::kImageLoadingDisabled); + settings.shrink_standalone_images_to_fit = + g_command_line->HasSwitch(cefclient::kShrinkStandaloneImagesToFit); + settings.site_specific_quirks_disabled = + g_command_line->HasSwitch(cefclient::kSiteSpecificQuirksDisabled); + settings.text_area_resize_disabled = + g_command_line->HasSwitch(cefclient::kTextAreaResizeDisabled); + settings.page_cache_disabled = + g_command_line->HasSwitch(cefclient::kPageCacheDisabled); + settings.tab_to_links_disabled = + g_command_line->HasSwitch(cefclient::kTabToLinksDisabled); + settings.hyperlink_auditing_disabled = + g_command_line->HasSwitch(cefclient::kHyperlinkAuditingDisabled); + settings.user_style_sheet_enabled = + g_command_line->HasSwitch(cefclient::kUserStyleSheetEnabled); + + CefString(&settings.user_style_sheet_location) = + g_command_line->GetSwitchValue(cefclient::kUserStyleSheetLocation); + + settings.author_and_user_styles_disabled = + g_command_line->HasSwitch(cefclient::kAuthorAndUserStylesDisabled); + settings.local_storage_disabled = + g_command_line->HasSwitch(cefclient::kLocalStorageDisabled); + settings.databases_disabled = + g_command_line->HasSwitch(cefclient::kDatabasesDisabled); + settings.application_cache_disabled = + g_command_line->HasSwitch(cefclient::kApplicationCacheDisabled); + settings.webgl_disabled = + g_command_line->HasSwitch(cefclient::kWebglDisabled); + settings.accelerated_compositing_enabled = + g_command_line->HasSwitch(cefclient::kAcceleratedCompositingEnabled); + settings.accelerated_layers_disabled = + g_command_line->HasSwitch(cefclient::kAcceleratedLayersDisabled); + settings.accelerated_video_disabled = + g_command_line->HasSwitch(cefclient::kAcceleratedVideoDisabled); + settings.accelerated_2d_canvas_disabled = + g_command_line->HasSwitch(cefclient::kAcceledated2dCanvasDisabled); + settings.accelerated_painting_disabled = + g_command_line->HasSwitch(cefclient::kAcceleratedPaintingDisabled); + settings.accelerated_filters_disabled = + g_command_line->HasSwitch(cefclient::kAcceleratedFiltersDisabled); + settings.accelerated_plugins_disabled = + g_command_line->HasSwitch(cefclient::kAcceleratedPluginsDisabled); + settings.developer_tools_disabled = + g_command_line->HasSwitch(cefclient::kDeveloperToolsDisabled); + settings.fullscreen_enabled = + g_command_line->HasSwitch(cefclient::kFullscreenEnabled); +} + +static void ExecuteGetSource(CefRefPtr frame) { + // Retrieve the current page source and display. + std::string source = frame->GetSource(); + source = StringReplace(source, "<", "<"); + source = StringReplace(source, ">", ">"); + std::stringstream ss; + ss << "Source:
" << source << "
"; + frame->LoadString(ss.str(), "http://tests/getsource"); +} + +void RunGetSourceTest(CefRefPtr browser) { + // Execute the GetSource() call on the UI thread. + CefPostTask(TID_UI, + NewCefRunnableFunction(&ExecuteGetSource, browser->GetMainFrame())); +} + +static void ExecuteGetText(CefRefPtr frame) { + std::string text = frame->GetText(); + text = StringReplace(text, "<", "<"); + text = StringReplace(text, ">", ">"); + std::stringstream ss; + ss << "Text:
" << text << "
"; + frame->LoadString(ss.str(), "http://tests/gettext"); +} + +void RunGetTextTest(CefRefPtr browser) { + // Execute the GetText() call on the UI thread. + CefPostTask(TID_UI, + NewCefRunnableFunction(&ExecuteGetText, browser->GetMainFrame())); +} + +void RunRequestTest(CefRefPtr browser) { + // Create a new request + CefRefPtr request(CefRequest::CreateRequest()); + + // 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::CreatePostDataElement()); + std::string data = "arg1=val1&arg2=val2"; + postDataElement->SetToBytes(data.length(), data.c_str()); + CefRefPtr postData(CefPostData::CreatePostData()); + 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 RunJavaScriptExecuteTest(CefRefPtr browser) { + browser->GetMainFrame()->ExecuteJavaScript( + "alert('JavaScript execute works!');", "about:blank", 0); +} + +void RunJavaScriptInvokeTest(CefRefPtr browser) { + if (CefCurrentlyOn(TID_UI)) { + UIT_InvokeScript(browser); + } else { + // Execute on the UI thread. + CefPostTask(TID_UI, NewCefRunnableFunction(&UIT_InvokeScript, browser)); + } +} + +void RunPopupTest(CefRefPtr browser) { + browser->GetMainFrame()->ExecuteJavaScript( + "window.open('http://www.google.com');", "about:blank", 0); +} + +void RunLocalStorageTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("http://tests/localstorage"); +} + +void RunAccelerated2DCanvasTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL( + "http://mudcu.be/labs/JS1k/BreathingGalaxies.html"); +} + +void RunAcceleratedLayersTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL( + "http://webkit.org/blog-files/3d-transforms/poster-circle.html"); +} + +void RunWebGLTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL( + "http://webglsamples.googlecode.com/hg/field/field.html"); +} + +void RunHTML5VideoTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL( + "http://www.youtube.com/watch?v=siOHh0uzcuY&html5=True"); +} + +void RunXMLHTTPRequestTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("http://tests/xmlhttprequest"); +} + +void RunWebURLRequestTest(CefRefPtr browser) { + class RequestClient : public CefWebURLRequestClient { + public: + explicit RequestClient(CefRefPtr browser) : browser_(browser) {} + + virtual void OnStateChange(CefRefPtr requester, + RequestState state) { + REQUIRE_UI_THREAD(); + if (state == WUR_STATE_DONE) { + buffer_ = StringReplace(buffer_, "<", "<"); + buffer_ = StringReplace(buffer_, ">", ">"); + std::stringstream ss; + ss << "Source:
" << buffer_ << "
"; + + browser_->GetMainFrame()->LoadString(ss.str(), + "http://tests/weburlrequest"); + } + } + + virtual void OnRedirect(CefRefPtr requester, + CefRefPtr request, + CefRefPtr response) { + REQUIRE_UI_THREAD(); + } + + virtual void OnHeadersReceived(CefRefPtr requester, + CefRefPtr response) { + REQUIRE_UI_THREAD(); + } + + virtual void OnProgress(CefRefPtr requester, + uint64 bytesSent, uint64 totalBytesToBeSent) { + REQUIRE_UI_THREAD(); + } + + virtual void OnData(CefRefPtr requester, + const void* data, int dataLength) { + REQUIRE_UI_THREAD(); + buffer_.append(static_cast(data), dataLength); + } + + virtual void OnError(CefRefPtr requester, + ErrorCode errorCode) { + REQUIRE_UI_THREAD(); + std::stringstream ss; + ss << "Load failed with error code " << errorCode; + browser_->GetMainFrame()->LoadString(ss.str(), + "http://tests/weburlrequest"); + } + + protected: + CefRefPtr browser_; + std::string buffer_; + + IMPLEMENT_REFCOUNTING(CefWebURLRequestClient); + }; + + CefRefPtr request(CefRequest::CreateRequest()); + request->SetURL("http://www.google.com"); + + CefRefPtr client(new RequestClient(browser)); + CefRefPtr requester( + CefWebURLRequest::CreateWebURLRequest(request, client)); +} + +void RunDOMAccessTest(CefRefPtr browser) { + class Listener : public CefDOMEventListener { + public: + Listener() {} + virtual void HandleEvent(CefRefPtr event) { + CefRefPtr document = event->GetDocument(); + ASSERT(document.get()); + + std::stringstream ss; + + CefRefPtr button = event->GetTarget(); + ASSERT(button.get()); + std::string buttonValue = button->GetElementAttribute("value"); + ss << "You clicked the " << buttonValue.c_str() << " button. "; + + if (document->HasSelection()) { + std::string startName, endName; + + // Determine the start name by first trying to locate the "id" attribute + // and then defaulting to the tag name. + { + CefRefPtr node = document->GetSelectionStartNode(); + if (!node->IsElement()) + node = node->GetParent(); + if (node->IsElement() && node->HasElementAttribute("id")) + startName = node->GetElementAttribute("id"); + else + startName = node->GetName(); + } + + // Determine the end name by first trying to locate the "id" attribute + // and then defaulting to the tag name. + { + CefRefPtr node = document->GetSelectionEndNode(); + if (!node->IsElement()) + node = node->GetParent(); + if (node->IsElement() && node->HasElementAttribute("id")) + endName = node->GetElementAttribute("id"); + else + endName = node->GetName(); + } + + ss << "The selection is from " << + startName.c_str() << ":" << document->GetSelectionStartOffset() << + " to " << + endName.c_str() << ":" << document->GetSelectionEndOffset(); + } else { + ss << "Nothing is selected."; + } + + // Update the description. + CefRefPtr desc = document->GetElementById("description"); + ASSERT(desc.get()); + CefRefPtr text = desc->GetFirstChild(); + ASSERT(text.get()); + ASSERT(text->IsText()); + text->SetValue(ss.str()); + } + + IMPLEMENT_REFCOUNTING(Listener); + }; + + class Visitor : public CefDOMVisitor { + public: + Visitor() {} + virtual void Visit(CefRefPtr document) { + // Register an click listener for the button. + CefRefPtr button = document->GetElementById("button"); + ASSERT(button.get()); + button->AddEventListener("click", new Listener(), false); + } + + IMPLEMENT_REFCOUNTING(Visitor); + }; + + // The DOM visitor will be called after the path is loaded. + CefRefPtr client = browser->GetClient(); + static_cast(client.get())->AddDOMVisitor( + "http://tests/domaccess", new Visitor()); + + browser->GetMainFrame()->LoadURL("http://tests/domaccess"); +} + +void RunDragDropTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("http://html5demos.com/drag"); +} + +void RunModalDialogTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("http://tests/modalmain"); +} + +void RunPluginInfoTest(CefRefPtr browser) { + if (CefCurrentlyOn(TID_UI)) { + UIT_RunPluginInfoTest(browser); + } else { + // Execute on the UI thread. + CefPostTask(TID_UI, + NewCefRunnableFunction(&UIT_RunPluginInfoTest, browser)); + } +} diff --git a/cef1/tests/cefclient/cefclient.h b/cef1/tests/cefclient/cefclient.h new file mode 100644 index 000000000..27ba93576 --- /dev/null +++ b/cef1/tests/cefclient/cefclient.h @@ -0,0 +1,61 @@ +// 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_CEFCLIENT_H_ +#define CEF_TESTS_CEFCLIENT_CEFCLIENT_H_ +#pragma once + +#include +#include "include/cef_base.h" + +class CefApp; +class CefBrowser; +class CefCommandLine; + +// Returns the main browser window instance. +CefRefPtr AppGetBrowser(); + +// Returns the main application window handle. +CefWindowHandle AppGetMainHwnd(); + +// Returns the application working directory. +std::string AppGetWorkingDirectory(); + +// Initialize the application command line. +void AppInitCommandLine(int argc, const char* const* argv); + +// Returns the application command line object. +CefRefPtr AppGetCommandLine(); + +// Returns the application settings based on command line arguments. +void AppGetSettings(CefSettings& settings, CefRefPtr& app); + +// Returns the application browser settings based on command line arguments. +void AppGetBrowserSettings(CefBrowserSettings& settings); + +// Implementations for various tests. +void RunGetSourceTest(CefRefPtr browser); +void RunGetTextTest(CefRefPtr browser); +void RunRequestTest(CefRefPtr browser); +void RunJavaScriptExecuteTest(CefRefPtr browser); +void RunJavaScriptInvokeTest(CefRefPtr browser); +void RunPopupTest(CefRefPtr browser); +void RunLocalStorageTest(CefRefPtr browser); +void RunAccelerated2DCanvasTest(CefRefPtr browser); +void RunAcceleratedLayersTest(CefRefPtr browser); +void RunWebGLTest(CefRefPtr browser); +void RunHTML5VideoTest(CefRefPtr browser); +void RunXMLHTTPRequestTest(CefRefPtr browser); +void RunWebURLRequestTest(CefRefPtr browser); +void RunDOMAccessTest(CefRefPtr browser); +void RunDragDropTest(CefRefPtr browser); +void RunModalDialogTest(CefRefPtr browser); +void RunPluginInfoTest(CefRefPtr browser); + +#if defined(OS_WIN) +void RunTransparentPopupTest(CefRefPtr browser); +void RunGetImageTest(CefRefPtr browser); +#endif + +#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_H_ diff --git a/cef1/tests/cefclient/cefclient.rc b/cef1/tests/cefclient/cefclient.rc new file mode 100644 index 000000000..277ca44b7 --- /dev/null +++ b/cef1/tests/cefclient/cefclient.rc @@ -0,0 +1,192 @@ +// 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_LOGO BINARY "res\\logo.png" +IDS_UIPLUGIN BINARY "res\\uiplugin.html" +IDS_OSRPLUGIN BINARY "res\\osrplugin.html" +IDS_LOGOBALL BINARY "res\\logoball.png" +IDS_LOCALSTORAGE BINARY "res\\localstorage.html" +IDS_XMLHTTPREQUEST BINARY "res\\xmlhttprequest.html" +IDS_DOMACCESS BINARY "res\\domaccess.html" +IDS_MODALMAIN BINARY "res\\modalmain.html" +IDS_MODALDIALOG BINARY "res\\modaldialog.html" +IDS_EXTENSIONPERF BINARY "res\\extensionperf.html" +IDS_TRANSPARENCY BINARY "res\\transparency.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 "&Print...", ID_PRINT + 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 "JavaScript Binding Handler", ID_TESTS_JAVASCRIPT_BINDING + MENUITEM "JavaScript Extension Handler",ID_TESTS_JAVASCRIPT_EXTENSION + MENUITEM "JavaScript Extension Performance",ID_TESTS_JAVASCRIPT_PERFORMANCE + MENUITEM "JavaScript Execute", ID_TESTS_JAVASCRIPT_EXECUTE + MENUITEM "JavaScript Invoke", ID_TESTS_JAVASCRIPT_INVOKE + MENUITEM "Plugin", ID_TESTS_PLUGIN + MENUITEM "Plugin Info", ID_TESTS_PLUGIN_INFO + MENUITEM "Popup Window", ID_TESTS_POPUP + MENUITEM "Transparent Popup Window", ID_TESTS_TRANSPARENT_POPUP + MENUITEM "Request", ID_TESTS_REQUEST + MENUITEM "Scheme Handler", ID_TESTS_SCHEME_HANDLER + MENUITEM "UI App Example", ID_TESTS_UIAPP + MENUITEM "Off-Screen Rendering Example",ID_TESTS_OSRAPP + MENUITEM "Transparent Off-Screen Rendering Example",ID_TESTS_TRANSPARENT_OSRAPP + MENUITEM "Local Storage", ID_TESTS_LOCALSTORAGE + MENUITEM "XMLHttpRequest", ID_TESTS_XMLHTTPREQUEST + MENUITEM "WebURLRequest", ID_TESTS_WEBURLREQUEST + MENUITEM "DOM Access", ID_TESTS_DOMACCESS + MENUITEM "Accelerated 2D Canvas", ID_TESTS_ACCELERATED2DCANVAS + MENUITEM "Accelerated Layers", ID_TESTS_ACCELERATEDLAYERS + MENUITEM "WebGL", ID_TESTS_WEBGL + MENUITEM "HTML5 Video", ID_TESTS_HTML5VIDEO + MENUITEM "Drag && Drop", ID_TESTS_DRAGDROP + MENUITEM "Zoom In", ID_TESTS_ZOOM_IN + MENUITEM "Zoom Out", ID_TESTS_ZOOM_OUT + MENUITEM "Reset Zoom", ID_TESTS_ZOOM_RESET + MENUITEM "Show Developer Tools", ID_TESTS_DEVTOOLS_SHOW + MENUITEM "Close Developer Tools", ID_TESTS_DEVTOOLS_CLOSE + MENUITEM "Modal Dialog", ID_TESTS_MODALDIALOG + MENUITEM "Get Image", ID_TESTS_GETIMAGE + 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" +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/cef1/tests/cefclient/cefclient_gtk.cpp b/cef1/tests/cefclient/cefclient_gtk.cpp new file mode 100644 index 000000000..853e2c27a --- /dev/null +++ b/cef1/tests/cefclient/cefclient_gtk.cpp @@ -0,0 +1,444 @@ +// 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 +#include +#include "cefclient/cefclient.h" +#include "include/cef_app.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_runnable.h" +#include "cefclient/binding_test.h" +#include "cefclient/client_handler.h" +#include "cefclient/extension_test.h" +#include "cefclient/scheme_test.h" +#include "cefclient/string_util.h" + +char szWorkingDir[512]; // The current working directory + +// The global ClientHandler reference. +extern CefRefPtr g_handler; + +void destroy(void) { + CefQuitMessageLoop(); +} + +void TerminationSignalHandler(int signatl) { + destroy(); +} + +// Callback for Debug > Get Source... menu item. +gboolean GetSourceActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunGetSourceTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Get Source... menu item. +gboolean GetTextActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunGetTextTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > JS Binding... menu item. +gboolean JSBindngActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunBindingTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > JS Extension... menu item. +gboolean JSExtensionActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunExtensionTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > JS Execute... menu item. +gboolean JSExecuteActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunJavaScriptExecuteTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Request... menu item. +gboolean RequestActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunRequestTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Local Storage... menu item. +gboolean LocalStorageActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunLocalStorageTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > XMLHttpRequest... menu item. +gboolean XMLHttpRequestActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunXMLHTTPRequestTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > WebURLRequest... menu item. +gboolean WebURLRequestActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunWebURLRequestTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > DOM Access... menu item. +gboolean DOMAccessActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunDOMAccessTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Scheme Handler... menu item. +gboolean SchemeHandlerActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunSchemeTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Popup Window... menu item. +gboolean PopupWindowActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunPopupTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Accelerated 2D Canvas:... menu item. +gboolean Accelerated2DCanvasActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunAccelerated2DCanvasTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Accelerated Layers:... menu item. +gboolean AcceleratedLayersActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunAcceleratedLayersTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > WebGL:... menu item. +gboolean WebGLActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunWebGLTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > HTML5 Video... menu item. +gboolean HTML5VideoActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunHTML5VideoTest(g_handler->GetBrowser()); + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Zoom In... menu item. +gboolean ZoomInActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->SetZoomLevel(browser->GetZoomLevel() + 0.5); + } + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Zoom Out... menu item. +gboolean ZoomOutActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->SetZoomLevel(browser->GetZoomLevel() - 0.5); + } + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Zoom Reset... menu item. +gboolean ZoomResetActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->SetZoomLevel(0.0); + } + + return FALSE; // Don't stop this message. +} + +gboolean DragDropActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + RunDragDropTest(browser); + } + + return FALSE; // Don't stop this message. +} + +gboolean ShowDevtoolsActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->ShowDevTools(); + } + + return FALSE; // Don't stop this message. +} + +// Callback for Debug > Plugin Info... menu item. +gboolean PluginInfoActivated(GtkWidget* widget) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunPluginInfoTest(g_handler->GetBrowser()); + + 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->GetBrowserHwnd()) + g_handler->GetBrowser()->GoBack(); +} + +// Callback for when you click the forward button. +void ForwardButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->GoForward(); +} + +// Callback for when you click the stop button. +void StopButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->StopLoad(); +} + +// Callback for when you click the reload button. +void ReloadButtonClicked(GtkButton* button) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->Reload(); +} + +// Callback for when you press enter in the URL box. +void URLEntryActivate(GtkEntry* entry) { + if (!g_handler.get() || !g_handler->GetBrowserHwnd()) + return; + + const gchar* url = gtk_entry_get_text(entry); + g_handler->GetBrowser()->GetMainFrame()->LoadURL(std::string(url).c_str()); +} + +// GTK utility functions ---------------------------------------------- + +GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text, + GCallback callback) { + GtkWidget* entry = gtk_menu_item_new_with_label(text); + g_signal_connect(entry, "activate", callback, NULL); + 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", + G_CALLBACK(GetSourceActivated)); + AddMenuEntry(debug_menu, "Get Text", + G_CALLBACK(GetTextActivated)); + AddMenuEntry(debug_menu, "JS Binding", + G_CALLBACK(JSBindngActivated)); + AddMenuEntry(debug_menu, "JS Extension", + G_CALLBACK(JSExtensionActivated)); + AddMenuEntry(debug_menu, "JS Execute", + G_CALLBACK(JSExecuteActivated)); + AddMenuEntry(debug_menu, "Request", + G_CALLBACK(RequestActivated)); + AddMenuEntry(debug_menu, "Local Storage", + G_CALLBACK(LocalStorageActivated)); + AddMenuEntry(debug_menu, "XMLHttpRequest", + G_CALLBACK(XMLHttpRequestActivated)); + AddMenuEntry(debug_menu, "DOM Access", + G_CALLBACK(DOMAccessActivated)); + AddMenuEntry(debug_menu, "Scheme Handler", + G_CALLBACK(SchemeHandlerActivated)); + AddMenuEntry(debug_menu, "Popup Window", + G_CALLBACK(PopupWindowActivated)); + AddMenuEntry(debug_menu, "Accelerated 2D Canvas", + G_CALLBACK(Accelerated2DCanvasActivated)); + AddMenuEntry(debug_menu, "Accelerated Layers", + G_CALLBACK(AcceleratedLayersActivated)); + AddMenuEntry(debug_menu, "WebGL", + G_CALLBACK(WebGLActivated)); + AddMenuEntry(debug_menu, "HTML5 Video", + G_CALLBACK(HTML5VideoActivated)); + AddMenuEntry(debug_menu, "Zoom In", + G_CALLBACK(ZoomInActivated)); + AddMenuEntry(debug_menu, "Zoom Out", + G_CALLBACK(ZoomOutActivated)); + AddMenuEntry(debug_menu, "Zoom Reset", + G_CALLBACK(ZoomResetActivated)); + AddMenuEntry(debug_menu, "Test DragDrop", + G_CALLBACK(DragDropActivated)); + AddMenuEntry(debug_menu, "Show DevTools", + G_CALLBACK(ShowDevtoolsActivated)); + AddMenuEntry(debug_menu, "Plugin Info", + G_CALLBACK(PluginInfoActivated)); + + return menu_bar; +} + +// WebViewDelegate::TakeFocus in the test webview delegate. +static gboolean HandleFocus(GtkWidget* widget, + GdkEventFocus* focus) { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + // Give focus to the browser window. + g_handler->GetBrowser()->SetFocus(true); + } + + return TRUE; +} + +int main(int argc, char *argv[]) { + if (!getcwd(szWorkingDir, sizeof (szWorkingDir))) + return -1; + + GtkWidget* window; + + gtk_init(&argc, &argv); + + // Parse command line arguments. + AppInitCommandLine(argc, argv); + + CefSettings settings; + CefRefPtr app; + + // Populate the settings based on command line arguments. + AppGetSettings(settings, app); + + // Initialize CEF. + CefInitialize(settings, app); + + // Register the V8 extension handler. + InitExtensionTest(); + + // Register the scheme handler. + InitSchemeTest(); + + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); + + g_signal_connect(window, "focus", G_CALLBACK(&HandleFocus), NULL); + + GtkWidget* vbox = gtk_vbox_new(FALSE, 0); + + GtkWidget* menu_bar = CreateMenuBar(); + + 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); + + 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* m_editWnd = gtk_entry_new(); + g_signal_connect(G_OBJECT(m_editWnd), "activate", + G_CALLBACK(URLEntryActivate), NULL); + + GtkToolItem* tool_item = gtk_tool_item_new(); + gtk_container_add(GTK_CONTAINER(tool_item), m_editWnd); + 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(gtk_widget_destroyed), &window); + g_signal_connect(G_OBJECT(window), "destroy", + G_CALLBACK(destroy), NULL); + + // Create the handler. + g_handler = new ClientHandler(); + g_handler->SetMainHwnd(vbox); + g_handler->SetEditHwnd(m_editWnd); + g_handler->SetButtonHwnds(GTK_WIDGET(back), GTK_WIDGET(forward), + GTK_WIDGET(reload), GTK_WIDGET(stop)); + + // Create the browser view. + CefWindowInfo window_info; + CefBrowserSettings browserSettings; + + // Populate the settings based on command line arguments. + AppGetBrowserSettings(browserSettings); + + window_info.SetAsChild(vbox); + + CefBrowser::CreateBrowserSync(window_info, + static_cast >(g_handler), + "http://www.google.com", browserSettings); + + gtk_container_add(GTK_CONTAINER(window), vbox); + gtk_widget_show_all(GTK_WIDGET(window)); + + // Install an signal handler so we clean up after ourselves. + signal(SIGINT, TerminationSignalHandler); + signal(SIGTERM, TerminationSignalHandler); + + CefRunMessageLoop(); + + CefShutdown(); + + return 0; +} + +// Global functions + +std::string AppGetWorkingDirectory() { + return szWorkingDir; +} diff --git a/cef1/tests/cefclient/cefclient_mac.mm b/cef1/tests/cefclient/cefclient_mac.mm new file mode 100644 index 000000000..c4ddf38f9 --- /dev/null +++ b/cef1/tests/cefclient/cefclient_mac.mm @@ -0,0 +1,610 @@ +// Copyright (c) 2010 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 "cefclient/cefclient.h" +#include "include/cef_app.h" +#import "include/cef_application_mac.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_runnable.h" +#include "cefclient/binding_test.h" +#include "cefclient/client_handler.h" +#include "cefclient/extension_test.h" +#include "cefclient/osrtest_mac.h" +#include "cefclient/resource_util.h" +#include "cefclient/scheme_test.h" +#include "cefclient/string_util.h" + +// The global ClientHandler reference. +extern CefRefPtr g_handler; + +char szWorkingDir[512]; // The current working directory + +// 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; + +// Memory AutoRelease pool. +static NSAutoreleasePool* g_autopool = nil; + +// 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]; +} +@end + + +// Receives notifications from controls and the browser window. Will delete +// itself when done. +@interface ClientWindowDelegate : NSObject +- (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; +- (void)notifyConsoleMessage:(id)object; +- (void)notifyDownloadComplete:(id)object; +- (void)notifyDownloadError:(id)object; +@end + +@implementation ClientWindowDelegate + +- (IBAction)goBack:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->GoBack(); +} + +- (IBAction)goForward:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->GoForward(); +} + +- (IBAction)reload:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->Reload(); +} + +- (IBAction)stopLoading:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + g_handler->GetBrowser()->StopLoad(); +} + +- (IBAction)takeURLStringValueFrom:(NSTextField *)sender { + if (!g_handler.get() || !g_handler->GetBrowserHwnd()) + 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]; +} + +- (void)notifyConsoleMessage:(id)object { + std::stringstream ss; + ss << "Console messages will be written to " << g_handler->GetLogFile(); + NSString* str = [NSString stringWithUTF8String:(ss.str().c_str())]; + [self alert:@"Console Messages" withMessage:str]; +} + +- (void)notifyDownloadComplete:(id)object { + std::stringstream ss; + ss << "File \"" << g_handler->GetLastDownloadFile() << + "\" downloaded successfully."; + NSString* str = [NSString stringWithUTF8String:(ss.str().c_str())]; + [self alert:@"File Download" withMessage:str]; +} + +- (void)notifyDownloadError:(id)object { + std::stringstream ss; + ss << "File \"" << g_handler->GetLastDownloadFile() << + "\" failed to download."; + NSString* str = [NSString stringWithUTF8String:(ss.str().c_str())]; + [self alert:@"File Download" withMessage:str]; +} + +- (void)windowDidBecomeKey:(NSNotification*)notification { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + // Give focus to the browser window. + g_handler->GetBrowser()->SetFocus(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 { + // 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]; + + return YES; +} + +// Deletes itself. +- (void)cleanup:(id)window { + [self release]; +} + +@end + + +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; +} + +// Receives notifications from the application. Will delete itself when done. +@interface ClientAppDelegate : NSObject +- (void)createApp:(id)object; +- (IBAction)testGetSource:(id)sender; +- (IBAction)testGetText:(id)sender; +- (IBAction)testJSBinding:(id)sender; +- (IBAction)testJSExtension:(id)sender; +- (IBAction)testJSExtensionPerf:(id)sender; +- (IBAction)testJSExecute:(id)sender; +- (IBAction)testJSInvoke:(id)sender; +- (IBAction)testRequest:(id)sender; +- (IBAction)testLocalStorage:(id)sender; +- (IBAction)testXMLHttpRequest:(id)sender; +- (IBAction)testWebURLRequest:(id)sender; +- (IBAction)testDOMAccess:(id)sender; +- (IBAction)testSchemeHandler:(id)sender; +- (IBAction)testPopupWindow:(id)sender; +- (IBAction)testAccelerated2DCanvas:(id)sender; +- (IBAction)testAcceleratedLayers:(id)sender; +- (IBAction)testWebGL:(id)sender; +- (IBAction)testHTML5Video:(id)sender; +- (IBAction)testDragDrop:(id)sender; +- (IBAction)testZoomIn:(id)sender; +- (IBAction)testZoomOut:(id)sender; +- (IBAction)testZoomReset:(id)sender; +- (IBAction)testDevToolsShow:(id)sender; +- (IBAction)testDevToolsClose:(id)sender; +- (IBAction)testPluginInfo:(id)sender; +- (IBAction)testOffscreenRendering:(id)sender; +- (IBAction)testTransparentOffscreenRendering:(id)sender; +@end + +@implementation ClientAppDelegate + +// Create the application on the UI thread. +- (void)createApp:(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]; + [testMenu addItemWithTitle:@"Get Source" + action:@selector(testGetSource:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Get Text" + action:@selector(testGetText:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"JavaScript Binding Handler" + action:@selector(testJSBinding:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"JavaScript Extension Handler" + action:@selector(testJSExtension:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"JavaScript Extension Performance" + action:@selector(testJSExtensionPerf:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"JavaScript Execute" + action:@selector(testJSExecute:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"JavaScript Invoke" + action:@selector(testJSInvoke:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Popup Window" + action:@selector(testPopupWindow:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Request" + action:@selector(testRequest:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Scheme Handler" + action:@selector(testSchemeHandler:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Local Storage" + action:@selector(testLocalStorage:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"XMLHttpRequest" + action:@selector(testXMLHttpRequest:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"WebURLRequest" + action:@selector(testWebURLRequest:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"DOM Access" + action:@selector(testDOMAccess:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Accelerated 2D Canvas" + action:@selector(testAccelerated2DCanvas:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Accelerated Layers" + action:@selector(testAcceleratedLayers:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"WebGL" + action:@selector(testWebGL:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"HTML5 Video" + action:@selector(testHTML5Video:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Drag & Drop" + action:@selector(testDragDrop:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Zoom In" + action:@selector(testZoomIn:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Zoom Out" + action:@selector(testZoomOut:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Zoom Reset" + action:@selector(testZoomReset:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Show DevTools" + action:@selector(testDevToolsShow:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Close DevTools" + action:@selector(testDevToolsClose:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Plugin Info" + action:@selector(testPluginInfo:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Offscreen Rendering" + action:@selector(testOffscreenRendering:) + keyEquivalent:@""]; + [testMenu addItemWithTitle:@"Transparent Offscreen Rendering" + action:@selector(testTransparentOffscreenRendering:) + keyEquivalent:@""]; + [testItem setSubmenu:testMenu]; + [menubar addItem:testItem]; + + // Create the delegate for control and browser window events. + ClientWindowDelegate* delegate = [[ClientWindowDelegate alloc] init]; + + // Create the main application window. + NSRect screen_rect = [[NSScreen mainScreen] visibleFrame]; + NSRect window_rect = { {0, screen_rect.size.height - kWindowHeight}, + {kWindowWidth, kWindowHeight} }; + NSWindow* mainWnd = [[NSWindow alloc] + initWithContentRect:window_rect + styleMask:(NSTitledWindowMask | + NSClosableWindowMask | + NSMiniaturizableWindowMask | + NSResizableWindowMask ) + backing:NSBackingStoreBuffered + defer:NO]; + [mainWnd setTitle:@"cefclient"]; + [mainWnd setDelegate:delegate]; + + // 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 ClientHandler(); + g_handler->SetMainHwnd(contentView); + g_handler->SetEditHwnd(editWnd); + + // Create the browser view. + CefWindowInfo window_info; + CefBrowserSettings settings; + + // Populate the settings based on command line arguments. + AppGetBrowserSettings(settings); + + window_info.SetAsChild(contentView, 0, 0, kWindowWidth, kWindowHeight); + CefBrowser::CreateBrowser(window_info, g_handler.get(), + "http://www.google.com", settings); + + // 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]; +} + +- (IBAction)testGetSource:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunGetSourceTest(g_handler->GetBrowser()); +} + +- (IBAction)testGetText:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunGetTextTest(g_handler->GetBrowser()); +} + +- (IBAction)testJSBinding:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunBindingTest(g_handler->GetBrowser()); +} + +- (IBAction)testJSExtension:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunExtensionTest(g_handler->GetBrowser()); +} + +- (IBAction)testJSExtensionPerf:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunExtensionPerfTest(g_handler->GetBrowser()); +} + +- (IBAction)testJSExecute:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunJavaScriptExecuteTest(g_handler->GetBrowser()); +} + +- (IBAction)testJSInvoke:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunJavaScriptInvokeTest(g_handler->GetBrowser()); +} + +- (IBAction)testRequest:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunRequestTest(g_handler->GetBrowser()); +} + +- (IBAction)testLocalStorage:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunLocalStorageTest(g_handler->GetBrowser()); +} + +- (IBAction)testXMLHttpRequest:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunXMLHTTPRequestTest(g_handler->GetBrowser()); +} + +- (IBAction)testWebURLRequest:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunWebURLRequestTest(g_handler->GetBrowser()); +} + +- (IBAction)testDOMAccess:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunDOMAccessTest(g_handler->GetBrowser()); +} + +- (IBAction)testSchemeHandler:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunSchemeTest(g_handler->GetBrowser()); +} + +- (IBAction)testPopupWindow:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunPopupTest(g_handler->GetBrowser()); +} + +- (IBAction)testAccelerated2DCanvas:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunAccelerated2DCanvasTest(g_handler->GetBrowser()); +} + +- (IBAction)testAcceleratedLayers:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunAcceleratedLayersTest(g_handler->GetBrowser()); +} + +- (IBAction)testWebGL:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunWebGLTest(g_handler->GetBrowser()); +} + +- (IBAction)testHTML5Video:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunHTML5VideoTest(g_handler->GetBrowser()); +} + +- (IBAction)testDragDrop:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunDragDropTest(g_handler->GetBrowser()); +} + +- (IBAction)testZoomIn:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->SetZoomLevel(browser->GetZoomLevel() + 0.5); + } +} + +- (IBAction)testZoomOut:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->SetZoomLevel(browser->GetZoomLevel() - 0.5); + } +} + +- (IBAction)testZoomReset:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->SetZoomLevel(0.0); + } +} + +- (IBAction)testDevToolsShow:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->ShowDevTools(); + } +} + +- (IBAction)testDevToolsClose:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + CefRefPtr browser = g_handler->GetBrowser(); + browser->CloseDevTools(); + } +} + +- (IBAction)testPluginInfo:(id)sender { + if (g_handler.get() && g_handler->GetBrowserHwnd()) + RunPluginInfoTest(g_handler->GetBrowser()); +} + +- (IBAction)testOffscreenRendering:(id)sender { + osrtest::RunTest(false); +} + +- (IBAction)testTransparentOffscreenRendering:(id)sender { + osrtest::RunTest(true); +} + +// Sent by the default notification center immediately before the application +// terminates. +- (void)applicationWillTerminate:(NSNotification *)aNotification { + // Shut down CEF. + g_handler = NULL; + CefShutdown(); + + [self release]; + + // Release the AutoRelease pool. + [g_autopool release]; +} + +@end + + +int main(int argc, char* argv[]) { + // Retrieve the current working directory. + getcwd(szWorkingDir, sizeof(szWorkingDir)); + + // Initialize the AutoRelease pool. + g_autopool = [[NSAutoreleasePool alloc] init]; + + // Initialize the ClientApplication instance. + [ClientApplication sharedApplication]; + + // Parse command line arguments. + AppInitCommandLine(argc, argv); + + CefSettings settings; + CefRefPtr app; + + // Populate the settings based on command line arguments. + AppGetSettings(settings, app); + + // Initialize CEF. + CefInitialize(settings, app); + + // Initialize tests. + InitExtensionTest(); + InitSchemeTest(); + + // Create the application delegate and window. + NSObject* delegate = [[ClientAppDelegate alloc] init]; + [delegate performSelectorOnMainThread:@selector(createApp:) withObject:nil + waitUntilDone:NO]; + + // Run the application message loop. + CefRunMessageLoop(); + + // Don't put anything below this line because it won't be executed. + return 0; +} + + +// Global functions + +std::string AppGetWorkingDirectory() { + return szWorkingDir; +} diff --git a/cef1/tests/cefclient/cefclient_switches.cpp b/cef1/tests/cefclient/cefclient_switches.cpp new file mode 100644 index 000000000..806a8967f --- /dev/null +++ b/cef1/tests/cefclient/cefclient_switches.cpp @@ -0,0 +1,92 @@ +// 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. + +// This file is shared by cefclient and cef_unittests so don't include using +// a qualified path. +#include "cefclient_switches.h" // NOLINT(build/include) + +namespace cefclient { + +// CefSettings attributes. +const char kMultiThreadedMessageLoop[] = "multi-threaded-message-loop"; +const char kCachePath[] = "cache-path"; +const char kUserAgent[] = "user-agent"; +const char kProductVersion[] = "product-version"; +const char kLocale[] = "locale"; +const char kLogFile[] = "log-file"; +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_ErrorReport[] = "error-report"; +const char kLogSeverity_Disable[] = "disable"; +const char kGraphicsImpl[] = "graphics-implementation"; +const char kGraphicsImpl_Angle[] = "angle"; +const char kGraphicsImpl_AngleCmdBuffer[] = "angle-command-buffer"; +const char kGraphicsImpl_Desktop[] = "desktop"; +const char kGraphicsImpl_DesktopCmdBuffer[] = "desktop-command-buffer"; +const char kLocalStorageQuota[] = "local-storage-quota"; +const char kSessionStorageQuota[] = "session-storage-quota"; +const char kJavascriptFlags[] = "javascript-flags"; +const char kPackFilePath[] = "pack-file-path"; +const char kLocalesDirPath[] = "locales-dir-path"; +const char kPackLoadingDisabled[] = "pack-loading-disabled"; + +// CefBrowserSettings attributes. +const char kDragDropDisabled[] = "drag-drop-disabled"; +const char kLoadDropsDisabled[] = "load-drops-disabled"; +const char kHistoryDisabled[] = "history-disabled"; +const char kRemoteFontsDisabled[] = "remote-fonts-disabled"; +const char kDefaultEncoding[] = "default-encoding"; +const char kEncodingDetectorEnabled[] = "encoding-detector-enabled"; +const char kJavascriptDisabled[] = "javascript-disabled"; +const char kJavascriptOpenWindowsDisallowed[] = + "javascript-open-windows-disallowed"; +const char kJavascriptCloseWindowsDisallowed[] = + "javascript-close-windows-disallowed"; +const char kJavascriptAccessClipboardDisallowed[] = + "javascript-access-clipboard-disallowed"; +const char kDomPasteDisabled[] = "dom-paste-disabled"; +const char kCaretBrowsingDisabled[] = "caret-browsing-enabled"; +const char kJavaDisabled[] = "java-disabled"; +const char kPluginsDisabled[] = "plugins-disabled"; +const char kUniversalAccessFromFileUrlsAllowed[] = + "universal-access-from-file-urls-allowed"; +const char kFileAccessFromFileUrlsAllowed[] = + "file-access-from-file-urls-allowed"; +const char kWebSecurityDisabled[] = "web-security-disabled"; +const char kXssAuditorEnabled[] = "xss-auditor-enabled"; +const char kImageLoadingDisabled[] = "image-load-disabled"; +const char kShrinkStandaloneImagesToFit[] = "shrink-standalone-images-to-fit"; +const char kSiteSpecificQuirksDisabled[] = "site-specific-quirks-disabled"; +const char kTextAreaResizeDisabled[] = "text-area-resize-disabled"; +const char kPageCacheDisabled[] = "page-cache-disabled"; +const char kTabToLinksDisabled[] = "tab-to-links-disabled"; +const char kHyperlinkAuditingDisabled[] = "hyperlink-auditing-disabled"; +const char kUserStyleSheetEnabled[] = "user-style-sheet-enabled"; +const char kUserStyleSheetLocation[] = "user-style-sheet-location"; +const char kAuthorAndUserStylesDisabled[] = "author-and-user-styles-disabled"; +const char kLocalStorageDisabled[] = "local-storage-disabled"; +const char kDatabasesDisabled[] = "databases-disabled"; +const char kApplicationCacheDisabled[] = "application-cache-disabled"; +const char kWebglDisabled[] = "webgl-disabled"; +const char kAcceleratedCompositingEnabled[] = "accelerated-compositing-enabled"; +const char kAcceleratedLayersDisabled[] = "accelerated-layers-disabled"; +const char kAcceleratedVideoDisabled[] = "accelerated-video-disabled"; +const char kAcceledated2dCanvasDisabled[] = "accelerated-2d-canvas-disabled"; +const char kAcceleratedPaintingDisabled[] = "accelerated-painting-disabled"; +const char kAcceleratedFiltersDisabled[] = "accelerated-filters-disabled"; +const char kAcceleratedPluginsDisabled[] = "accelerated-plugins-disabled"; +const char kDeveloperToolsDisabled[] = "developer-tools-disabled"; +const char kFullscreenEnabled[] = "fullscreen-enabled"; + +// Other attributes. +const char kProxyType[] = "proxy-type"; +const char kProxyType_Direct[] = "direct"; +const char kProxyType_Named[] = "named"; +const char kProxyType_Pac[] = "pac"; +const char kProxyConfig[] = "proxy-config"; + +} // namespace cefclient diff --git a/cef1/tests/cefclient/cefclient_switches.h b/cef1/tests/cefclient/cefclient_switches.h new file mode 100644 index 000000000..335ebd7fc --- /dev/null +++ b/cef1/tests/cefclient/cefclient_switches.h @@ -0,0 +1,91 @@ +// 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. + +// 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 cefclient { + +// CefSettings attributes. +extern const char kMultiThreadedMessageLoop[]; +extern const char kCachePath[]; +extern const char kUserAgent[]; +extern const char kProductVersion[]; +extern const char kLocale[]; +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_ErrorReport[]; +extern const char kLogSeverity_Disable[]; +extern const char kGraphicsImpl[]; +extern const char kGraphicsImpl_Angle[]; +extern const char kGraphicsImpl_AngleCmdBuffer[]; +extern const char kGraphicsImpl_Desktop[]; +extern const char kGraphicsImpl_DesktopCmdBuffer[]; +extern const char kLocalStorageQuota[]; +extern const char kSessionStorageQuota[]; +extern const char kJavascriptFlags[]; +extern const char kPackFilePath[]; +extern const char kLocalesDirPath[]; +extern const char kPackLoadingDisabled[]; + +// CefBrowserSettings attributes. +extern const char kDragDropDisabled[]; +extern const char kLoadDropsDisabled[]; +extern const char kHistoryDisabled[]; +extern const char kRemoteFontsDisabled[]; +extern const char kDefaultEncoding[]; +extern const char kEncodingDetectorEnabled[]; +extern const char kJavascriptDisabled[]; +extern const char kJavascriptOpenWindowsDisallowed[]; +extern const char kJavascriptCloseWindowsDisallowed[]; +extern const char kJavascriptAccessClipboardDisallowed[]; +extern const char kDomPasteDisabled[]; +extern const char kCaretBrowsingDisabled[]; +extern const char kJavaDisabled[]; +extern const char kPluginsDisabled[]; +extern const char kUniversalAccessFromFileUrlsAllowed[]; +extern const char kFileAccessFromFileUrlsAllowed[]; +extern const char kWebSecurityDisabled[]; +extern const char kXssAuditorEnabled[]; +extern const char kImageLoadingDisabled[]; +extern const char kShrinkStandaloneImagesToFit[]; +extern const char kSiteSpecificQuirksDisabled[]; +extern const char kTextAreaResizeDisabled[]; +extern const char kPageCacheDisabled[]; +extern const char kTabToLinksDisabled[]; +extern const char kHyperlinkAuditingDisabled[]; +extern const char kUserStyleSheetEnabled[]; +extern const char kUserStyleSheetLocation[]; +extern const char kAuthorAndUserStylesDisabled[]; +extern const char kLocalStorageDisabled[]; +extern const char kDatabasesDisabled[]; +extern const char kApplicationCacheDisabled[]; +extern const char kWebglDisabled[]; +extern const char kAcceleratedCompositingEnabled[]; +extern const char kAcceleratedLayersDisabled[]; +extern const char kAcceleratedVideoDisabled[]; +extern const char kAcceledated2dCanvasDisabled[]; +extern const char kAcceleratedPaintingDisabled[]; +extern const char kAcceleratedFiltersDisabled[]; +extern const char kAcceleratedPluginsDisabled[]; +extern const char kDeveloperToolsDisabled[]; +extern const char kFullscreenEnabled[]; + +// Other attributes. +extern const char kProxyType[]; +extern const char kProxyType_Direct[]; +extern const char kProxyType_Named[]; +extern const char kProxyType_Pac[]; +extern const char kProxyConfig[]; + +} // namespace cefclient + +#endif // CEF_TESTS_CEFCLIENT_CEFCLIENT_SWITCHES_H_ diff --git a/cef1/tests/cefclient/cefclient_win.cpp b/cef1/tests/cefclient/cefclient_win.cpp new file mode 100644 index 000000000..3f3d89b32 --- /dev/null +++ b/cef1/tests/cefclient/cefclient_win.cpp @@ -0,0 +1,771 @@ +// 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 "cefclient/cefclient.h" +#include +#include +#include +#include +#include +#include +#include "include/cef_app.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_runnable.h" +#include "cefclient/binding_test.h" +#include "cefclient/client_handler.h" +#include "cefclient/extension_test.h" +#include "cefclient/osrplugin_test.h" +#include "cefclient/plugin_test.h" +#include "cefclient/resource.h" +#include "cefclient/scheme_test.h" +#include "cefclient/string_util.h" +#include "cefclient/uiplugin_test.h" + +#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 +char szWorkingDir[MAX_PATH]; // The current working directory +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 MyRegisterClass(HINSTANCE hInstance); +BOOL InitInstance(HINSTANCE, int); +LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); +INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); + +// The global ClientHandler reference. +extern CefRefPtr g_handler; + +#if defined(OS_WIN) +// Add Common Controls to the application manifest because it's required to +// support the default tooltip implementation. +#pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") // NOLINT(whitespace/line_length) +#endif + +// Program entry point function. +int APIENTRY wWinMain(HINSTANCE hInstance, + HINSTANCE hPrevInstance, + LPTSTR lpCmdLine, + int nCmdShow) { + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + + // Retrieve the current working directory. + if (_getcwd(szWorkingDir, MAX_PATH) == NULL) + szWorkingDir[0] = 0; + + // Parse command line arguments. The passed in values are ignored on Windows. + AppInitCommandLine(0, NULL); + + CefSettings settings; + CefRefPtr app; + + // Populate the settings based on command line arguments. + AppGetSettings(settings, app); + + // Initialize CEF. + CefInitialize(settings, app); + + // Register the internal client plugin. + InitPluginTest(); + + // Register the internal UI client plugin. + InitUIPluginTest(); + + // Register the internal OSR client plugin. + InitOSRPluginTest(); + + // Register the V8 extension handler. + InitExtensionTest(); + + // Register the scheme handler. + InitSchemeTest(); + + HACCEL hAccelTable; + + // Initialize global strings + LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); + LoadString(hInstance, IDC_CEFCLIENT, szWindowClass, MAX_LOADSTRING); + MyRegisterClass(hInstance); + + // Perform application initialization + if (!InitInstance (hInstance, nCmdShow)) + return FALSE; + + hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_CEFCLIENT)); + + // Register the find event message. + uFindMsg = RegisterWindowMessage(FINDMSGSTRING); + + int result = 0; + + if (!settings.multi_threaded_message_loop) { + // Run the CEF message loop. This function will block until the application + // recieves a WM_QUIT message. + CefRunMessageLoop(); + } else { + MSG msg; + + // Run the application message loop. + while (GetMessage(&msg, NULL, 0, 0)) { + // Allow processing of find dialog messages. + if (hFindDlg && IsDialogMessage(hFindDlg, &msg)) + continue; + + if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + } + + result = static_cast(msg.wParam); + } + + // Shut down CEF. + CefShutdown(); + + return result; +} + +// +// FUNCTION: MyRegisterClass() +// +// PURPOSE: Registers the window class. +// +// COMMENTS: +// +// This function and its usage are only necessary if you want this code +// to be compatible with Win32 systems prior to the 'RegisterClassEx' +// function that was added to Windows 95. It is important to call this +// function so that the application will get 'well formed' small icons +// associated with it. +// +ATOM MyRegisterClass(HINSTANCE hInstance) { + WNDCLASSEX wcex; + + wcex.cbSize = sizeof(WNDCLASSEX); + + wcex.style = CS_HREDRAW | CS_VREDRAW; + wcex.lpfnWndProc = WndProc; + 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); +} + +// +// FUNCTION: InitInstance(HINSTANCE, int) +// +// PURPOSE: Saves instance handle and creates main window +// +// COMMENTS: +// +// In this function, we save the instance handle in a global variable and +// create and display the main program window. +// +BOOL InitInstance(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; +} + +// +// FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) +// +// PURPOSE: Processes messages for the main window. +// +LRESULT CALLBACK WndProc(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()->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()->StopFinding(true); + findNext = false; + } + lastMatchCase = matchCase; + wcscpy_s(szLastFindWhat, sizeof(szLastFindWhat)/sizeof(WCHAR), + szFindWhat); + } + + g_handler->GetBrowser()->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->SetMainHwnd(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(WndProc)); + g_handler->SetEditHwnd(editWnd); + g_handler->SetButtonHwnds(backWnd, forwardWnd, reloadWnd, stopWnd); + + rect.top += URLBAR_HEIGHT; + + CefWindowInfo info; + CefBrowserSettings settings; + + // Populate the settings based on command line arguments. + AppGetBrowserSettings(settings); + + // Initialize window info to the defaults for a child window + info.SetAsChild(hWnd, rect); + + // Creat the new child browser window + CefBrowser::CreateBrowser(info, + static_cast >(g_handler), + "http://www.google.com", settings); + + return 0; + } + + case WM_COMMAND: { + CefRefPtr browser; + if (g_handler.get()) + browser = g_handler->GetBrowser(); + + wmId = LOWORD(wParam); + wmEvent = HIWORD(wParam); + // Parse the menu selections: + switch (wmId) { + case IDM_ABOUT: + DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); + return 0; + case IDM_EXIT: + DestroyWindow(hWnd); + return 0; + case ID_WARN_CONSOLEMESSAGE: + if (g_handler.get()) { + std::wstringstream ss; + ss << L"Console messages will be written to " + << std::wstring(CefString(g_handler->GetLogFile())); + MessageBox(hWnd, ss.str().c_str(), L"Console Messages", + MB_OK | MB_ICONINFORMATION); + } + return 0; + case ID_WARN_DOWNLOADCOMPLETE: + case ID_WARN_DOWNLOADERROR: + if (g_handler.get()) { + std::wstringstream ss; + ss << L"File \"" << + std::wstring(CefString(g_handler->GetLastDownloadFile())) << + L"\" "; + + if (wmId == ID_WARN_DOWNLOADCOMPLETE) + ss << L"downloaded successfully."; + else + ss << L"failed to download."; + + MessageBox(hWnd, ss.str().c_str(), L"File Download", + MB_OK | MB_ICONINFORMATION); + } + 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); + } else { + // Give focus to the existing find dialog. + ::SetFocus(hFindDlg); + } + return 0; + case ID_PRINT: + if (browser.get()) + browser->GetMainFrame()->Print(); + 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; + case ID_TESTS_GETSOURCE: // Test the GetSource function + if (browser.get()) + RunGetSourceTest(browser); + return 0; + case ID_TESTS_GETTEXT: // Test the GetText function + if (browser.get()) + RunGetTextTest(browser); + return 0; + case ID_TESTS_JAVASCRIPT_BINDING: // Test the V8 binding handler + if (browser.get()) + RunBindingTest(browser); + return 0; + case ID_TESTS_JAVASCRIPT_EXTENSION: // Test the V8 extension handler + if (browser.get()) + RunExtensionTest(browser); + return 0; + case ID_TESTS_JAVASCRIPT_PERFORMANCE: // Test the V8 performance + if (browser.get()) + RunExtensionPerfTest(browser); + return 0; + case ID_TESTS_JAVASCRIPT_EXECUTE: // Test execution of javascript + if (browser.get()) + RunJavaScriptExecuteTest(browser); + return 0; + case ID_TESTS_JAVASCRIPT_INVOKE: + if (browser.get()) + RunJavaScriptInvokeTest(browser); + return 0; + case ID_TESTS_PLUGIN: // Test the custom plugin + if (browser.get()) + RunPluginTest(browser); + return 0; + case ID_TESTS_PLUGIN_INFO: // Test plugin info + if (browser.get()) + RunPluginInfoTest(browser); + return 0; + case ID_TESTS_POPUP: // Test a popup window + if (browser.get()) + RunPopupTest(browser); + return 0; + case ID_TESTS_TRANSPARENT_POPUP: // Test a transparent popup window + if (browser.get()) + RunTransparentPopupTest(browser); + return 0; + case ID_TESTS_REQUEST: // Test a request + if (browser.get()) + RunRequestTest(browser); + return 0; + case ID_TESTS_SCHEME_HANDLER: // Test the scheme handler + if (browser.get()) + RunSchemeTest(browser); + return 0; + case ID_TESTS_UIAPP: // Test the UI app + if (browser.get()) + RunUIPluginTest(browser); + return 0; + case ID_TESTS_OSRAPP: // Test the OSR app + if (browser.get()) + RunOSRPluginTest(browser, false); + return 0; + case ID_TESTS_TRANSPARENT_OSRAPP: // Test the OSR app with transparency + if (browser.get()) + RunOSRPluginTest(browser, true); + return 0; + case ID_TESTS_DOMACCESS: // Test DOM access + if (browser.get()) + RunDOMAccessTest(browser); + return 0; + case ID_TESTS_LOCALSTORAGE: // Test localStorage + if (browser.get()) + RunLocalStorageTest(browser); + return 0; + case ID_TESTS_ACCELERATED2DCANVAS: // Test accelerated 2d canvas + if (browser.get()) + RunAccelerated2DCanvasTest(browser); + return 0; + case ID_TESTS_ACCELERATEDLAYERS: // Test accelerated layers + if (browser.get()) + RunAcceleratedLayersTest(browser); + return 0; + case ID_TESTS_WEBGL: // Test WebGL + if (browser.get()) + RunWebGLTest(browser); + return 0; + case ID_TESTS_HTML5VIDEO: // Test HTML5 video + if (browser.get()) + RunHTML5VideoTest(browser); + return 0; + case ID_TESTS_DRAGDROP: // Test drag & drop + if (browser.get()) + RunDragDropTest(browser); + return 0; + case ID_TESTS_XMLHTTPREQUEST: // Test XMLHttpRequest + if (browser.get()) + RunXMLHTTPRequestTest(browser); + return 0; + case ID_TESTS_WEBURLREQUEST: + if (browser.get()) + RunWebURLRequestTest(browser); + return 0; + case ID_TESTS_ZOOM_IN: + if (browser.get()) + browser->SetZoomLevel(browser->GetZoomLevel() + 0.5); + return 0; + case ID_TESTS_ZOOM_OUT: + if (browser.get()) + browser->SetZoomLevel(browser->GetZoomLevel() - 0.5); + return 0; + case ID_TESTS_ZOOM_RESET: + if (browser.get()) + browser->SetZoomLevel(0.0); + return 0; + case ID_TESTS_DEVTOOLS_SHOW: + if (browser.get()) + browser->ShowDevTools(); + return 0; + case ID_TESTS_DEVTOOLS_CLOSE: + if (browser.get()) + browser->CloseDevTools(); + return 0; + case ID_TESTS_MODALDIALOG: + if (browser.get()) + RunModalDialogTest(browser); + return 0; + case ID_TESTS_GETIMAGE: + if (browser.get()) + RunGetImageTest(browser); + return 0; + } + break; + } + + case WM_PAINT: + hdc = BeginPaint(hWnd, &ps); + EndPaint(hWnd, &ps); + return 0; + + case WM_SETFOCUS: + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + // Pass focus to the browser window + PostMessage(g_handler->GetBrowserHwnd(), WM_SETFOCUS, wParam, NULL); + } + return 0; + + case WM_SIZE: + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + // Resize the browser window and address bar to match the new frame + // window 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, g_handler->GetBrowserHwnd(), NULL, + rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, + SWP_NOZORDER); + EndDeferWindowPos(hdwp); + } + break; + + case WM_ERASEBKGND: + if (g_handler.get() && g_handler->GetBrowserHwnd()) { + // Dont erase the background if the browser window has been loaded + // (this avoids flashing) + return 0; + } + break; + + case WM_CLOSE: + if (g_handler.get()) { + CefRefPtr browser = g_handler->GetBrowser(); + if (browser.get()) { + // Let the browser window know we are about to destroy it. + browser->ParentWindowWillClose(); + } + } + break; + + case WM_DESTROY: + // The frame window has exited + PostQuitMessage(0); + return 0; + } + + return DefWindowProc(hWnd, message, wParam, lParam); + } +} + +// Message handler for about box. +INT_PTR CALLBACK About(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; +} + + +// Global functions + +std::string AppGetWorkingDirectory() { + return szWorkingDir; +} + +void RunTransparentPopupTest(CefRefPtr browser) { + CefWindowInfo info; + CefBrowserSettings settings; + + // Initialize window info to the defaults for a popup window + info.SetAsPopup(NULL, "TransparentPopup"); + info.SetTransparentPainting(TRUE); + info.m_nWidth = 500; + info.m_nHeight = 500; + + // Creat the popup browser window + CefBrowser::CreateBrowser(info, + static_cast >(g_handler), + "http://tests/transparency", settings); +} + +namespace { + +// Determine a temporary path for the bitmap file. +bool GetBitmapTempPath(LPWSTR szTempName) { + DWORD dwRetVal; + DWORD dwBufSize = 512; + TCHAR lpPathBuffer[512]; + UINT uRetVal; + + dwRetVal = GetTempPath(dwBufSize, // length of the buffer + lpPathBuffer); // buffer for path + if (dwRetVal > dwBufSize || (dwRetVal == 0)) + return false; + + // Create a temporary file. + uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files + L"image", // temp file name prefix + 0, // create unique name + szTempName); // buffer for name + if (uRetVal == 0) + return false; + + size_t len = wcslen(szTempName); + wcscpy(szTempName + len - 3, L"bmp"); + return true; +} + +void UIT_RunGetImageTest(CefRefPtr browser) { + REQUIRE_UI_THREAD(); + + int width, height; + bool success = false; + + // Retrieve the image size. + if (browser->GetSize(PET_VIEW, width, height)) { + void* bits; + + // Populate the bitmap info header. + BITMAPINFOHEADER info; + info.biSize = sizeof(BITMAPINFOHEADER); + info.biWidth = width; + info.biHeight = -height; // minus means top-down bitmap + info.biPlanes = 1; + info.biBitCount = 32; + info.biCompression = BI_RGB; // no compression + info.biSizeImage = 0; + info.biXPelsPerMeter = 1; + info.biYPelsPerMeter = 1; + info.biClrUsed = 0; + info.biClrImportant = 0; + + // Create the bitmap and retrieve the bit buffer. + HDC screen_dc = GetDC(NULL); + HBITMAP bitmap = + CreateDIBSection(screen_dc, reinterpret_cast(&info), + DIB_RGB_COLORS, &bits, NULL, 0); + ReleaseDC(NULL, screen_dc); + + // Read the image into the bit buffer. + if (bitmap && browser->GetImage(PET_VIEW, width, height, bits)) { + // Populate the bitmap file header. + BITMAPFILEHEADER file; + file.bfType = 0x4d42; + file.bfSize = sizeof(BITMAPFILEHEADER); + file.bfReserved1 = 0; + file.bfReserved2 = 0; + file.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); + + TCHAR temp_path[512]; + if (GetBitmapTempPath(temp_path)) { + // Write the bitmap to file. + HANDLE file_handle = + CreateFile(temp_path, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, 0); + if (file_handle != INVALID_HANDLE_VALUE) { + DWORD bytes_written = 0; + WriteFile(file_handle, &file, sizeof(file), &bytes_written, 0); + WriteFile(file_handle, &info, sizeof(info), &bytes_written, 0); + WriteFile(file_handle, bits, width * height * 4, &bytes_written, 0); + + CloseHandle(file_handle); + + // Open the bitmap in the default viewer. + ShellExecute(NULL, L"open", temp_path, NULL, NULL, SW_SHOWNORMAL); + success = true; + } + } + } + + DeleteObject(bitmap); + } + + if (!success) { + browser->GetMainFrame()->ExecuteJavaScript( + "alert('Failed to create image!');", + browser->GetMainFrame()->GetURL(), 0); + } +} + +} // namespace + +void RunGetImageTest(CefRefPtr browser) { + // Execute the test function on the UI thread. + CefPostTask(TID_UI, NewCefRunnableFunction(UIT_RunGetImageTest, browser)); +} diff --git a/cef1/tests/cefclient/client_handler.cpp b/cef1/tests/cefclient/client_handler.cpp new file mode 100644 index 000000000..df0b126cd --- /dev/null +++ b/cef1/tests/cefclient/client_handler.cpp @@ -0,0 +1,359 @@ +// 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 "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/binding_test.h" +#include "cefclient/cefclient.h" +#include "cefclient/download_handler.h" +#include "cefclient/string_util.h" + + +ClientHandler::ClientHandler() + : m_MainHwnd(NULL), + m_BrowserHwnd(NULL), + m_EditHwnd(NULL), + m_BackHwnd(NULL), + m_ForwardHwnd(NULL), + m_StopHwnd(NULL), + m_ReloadHwnd(NULL), + m_bFormElementHasFocus(false) { +} + +ClientHandler::~ClientHandler() { +} + + +void ClientHandler::OnAfterCreated(CefRefPtr browser) { + REQUIRE_UI_THREAD(); + + AutoLock lock_scope(this); + if (!m_Browser.get()) { + // We need to keep the main child window, but not popup windows + m_Browser = browser; + m_BrowserHwnd = browser->GetWindowHandle(); + } +} + +bool ClientHandler::DoClose(CefRefPtr browser) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle()) { + // Since the main window contains the browser window, we need to close + // the parent window instead of the browser window. + CloseMainWindow(); + + // Return true here so that we can skip closing the browser window + // in this pass. (It will be destroyed due to the call to close + // the parent above.) + return true; + } + + // A popup browser window is not contained in another window, so we can let + // these windows close by themselves. + return false; +} + +void ClientHandler::OnBeforeClose(CefRefPtr browser) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle()) { + // Free the browser pointer so that the browser can be destroyed + m_Browser = NULL; + } +} + +void ClientHandler::OnLoadStart(CefRefPtr browser, + CefRefPtr frame) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) { + // We've just started loading a page + SetLoading(true); + } +} + +void ClientHandler::OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) { + // We've just finished loading a page + SetLoading(false); + + CefRefPtr visitor = GetDOMVisitor(frame->GetURL()); + if (visitor.get()) + frame->VisitDOM(visitor); + } +} + +bool ClientHandler::OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& failedUrl, + CefString& errorText) { + REQUIRE_UI_THREAD(); + + if (errorCode == ERR_CACHE_MISS) { + // Usually caused by navigating to a page with POST data via back or + // forward buttons. + errorText = "Expired Form Data" + "

Expired Form Data

" + "

Your form request has expired. " + "Click reload to re-submit the form data.

" + ""; + } else { + // All other messages. + std::stringstream ss; + ss << "Load Failed" + "

Load Failed

" + "

Load of URL " << std::string(failedUrl) << + " failed with error code " << static_cast(errorCode) << + ".

" + ""; + errorText = ss.str(); + } + + return false; +} + +bool ClientHandler::GetDownloadHandler(CefRefPtr browser, + const CefString& mimeType, + const CefString& fileName, + int64 contentLength, + CefRefPtr& handler) { + REQUIRE_UI_THREAD(); + + // Create the handler for the file download. + handler = CreateDownloadHandler(this, fileName); + + // Close the browser window if it is a popup with no other document contents. + if (browser->IsPopup() && !browser->HasDocument()) + browser->CloseBrowser(); + + return true; +} + +void ClientHandler::OnNavStateChange(CefRefPtr browser, + bool canGoBack, + bool canGoForward) { + REQUIRE_UI_THREAD(); + + SetNavState(canGoBack, canGoForward); +} + +bool ClientHandler::OnConsoleMessage(CefRefPtr browser, + const CefString& message, + const CefString& source, + int line) { + REQUIRE_UI_THREAD(); + + bool first_message; + std::string logFile; + + { + AutoLock lock_scope(this); + + first_message = m_LogFile.empty(); + if (first_message) { + std::stringstream ss; + ss << AppGetWorkingDirectory(); +#if defined(OS_WIN) + ss << "\\"; +#else + ss << "/"; +#endif + ss << "console.log"; + m_LogFile = ss.str(); + } + logFile = m_LogFile; + } + + FILE* file = fopen(logFile.c_str(), "a"); + if (file) { + std::stringstream ss; + ss << "Message: " << std::string(message) << "\r\nSource: " << + std::string(source) << "\r\nLine: " << line << + "\r\n-----------------------\r\n"; + fputs(ss.str().c_str(), file); + fclose(file); + + if (first_message) + SendNotification(NOTIFY_CONSOLE_MESSAGE); + } + + return false; +} + +void ClientHandler::OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) { + REQUIRE_UI_THREAD(); + + // Set to true if a form element has focus. + m_bFormElementHasFocus = (node.get() && node->IsFormControlElement()); +} + +bool ClientHandler::OnKeyEvent(CefRefPtr browser, + KeyEventType type, + int code, + int modifiers, + bool isSystemKey, + bool isAfterJavaScript) { + REQUIRE_UI_THREAD(); + + if (isAfterJavaScript && !m_bFormElementHasFocus && code == 0x20) { + // Special handling for the space character if a form element does not have + // focus. + if (type == KEYEVENT_RAWKEYDOWN) { + browser->GetMainFrame()->ExecuteJavaScript( + "alert('You pressed the space bar!');", "", 0); + } + return true; + } + + return false; +} + +bool ClientHandler::GetPrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, + const CefPrintInfo& printInfo, + const CefString& url, + const CefString& title, + int currentPage, + int maxPages, + CefString& topLeft, + CefString& topCenter, + CefString& topRight, + CefString& bottomLeft, + CefString& bottomCenter, + CefString& bottomRight) { + REQUIRE_UI_THREAD(); + + // Place the page title at top left + topLeft = title; + // Place the page URL at top right + topRight = url; + + // Place "Page X of Y" at bottom center + std::stringstream strstream; + strstream << "Page " << currentPage << " of " << maxPages; + bottomCenter = strstream.str(); + + return false; +} + +void ClientHandler::OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) { + REQUIRE_UI_THREAD(); + + // Add the V8 bindings. + InitBindingTest(browser, frame, context->GetGlobal()); +} + +bool ClientHandler::OnDragStart(CefRefPtr browser, + CefRefPtr dragData, + DragOperationsMask mask) { + REQUIRE_UI_THREAD(); + + // Forbid dragging of image files. + if (dragData->IsFile()) { + std::string fileName = dragData->GetFileName(); + if (fileName.find(".png") != std::string::npos || + fileName.find(".jpg") != std::string::npos || + fileName.find(".gif") != std::string::npos) + return true; + } + + return false; +} + +bool ClientHandler::OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, + DragOperationsMask mask) { + REQUIRE_UI_THREAD(); + + // Forbid dragging of link URLs. + if (dragData->IsLink()) + return true; + + return false; +} + +bool ClientHandler::OnBeforeScriptExtensionLoad( + CefRefPtr browser, + CefRefPtr frame, + const CefString& extensionName) { + return false; +} + +void ClientHandler::NotifyDownloadComplete(const CefString& fileName) { + SetLastDownloadFile(fileName); + SendNotification(NOTIFY_DOWNLOAD_COMPLETE); +} + +void ClientHandler::NotifyDownloadError(const CefString& fileName) { + SetLastDownloadFile(fileName); + SendNotification(NOTIFY_DOWNLOAD_ERROR); +} + +void ClientHandler::SetMainHwnd(CefWindowHandle hwnd) { + AutoLock lock_scope(this); + m_MainHwnd = hwnd; +} + +void ClientHandler::SetEditHwnd(CefWindowHandle hwnd) { + AutoLock lock_scope(this); + m_EditHwnd = hwnd; +} + +void ClientHandler::SetButtonHwnds(CefWindowHandle backHwnd, + CefWindowHandle forwardHwnd, + CefWindowHandle reloadHwnd, + CefWindowHandle stopHwnd) { + AutoLock lock_scope(this); + m_BackHwnd = backHwnd; + m_ForwardHwnd = forwardHwnd; + m_ReloadHwnd = reloadHwnd; + m_StopHwnd = stopHwnd; +} + +std::string ClientHandler::GetLogFile() { + AutoLock lock_scope(this); + return m_LogFile; +} + +void ClientHandler::SetLastDownloadFile(const std::string& fileName) { + AutoLock lock_scope(this); + m_LastDownloadFile = fileName; +} + +std::string ClientHandler::GetLastDownloadFile() { + AutoLock lock_scope(this); + return m_LastDownloadFile; +} + +void ClientHandler::AddDOMVisitor(const std::string& path, + CefRefPtr visitor) { + AutoLock lock_scope(this); + DOMVisitorMap::iterator it = m_DOMVisitors.find(path); + if (it == m_DOMVisitors.end()) + m_DOMVisitors.insert(std::make_pair(path, visitor)); + else + it->second = visitor; +} + +CefRefPtr ClientHandler::GetDOMVisitor(const std::string& path) { + AutoLock lock_scope(this); + DOMVisitorMap::iterator it = m_DOMVisitors.find(path); + if (it != m_DOMVisitors.end()) + return it->second; + return NULL; +} diff --git a/cef1/tests/cefclient/client_handler.h b/cef1/tests/cefclient/client_handler.h new file mode 100644 index 000000000..f286d106c --- /dev/null +++ b/cef1/tests/cefclient/client_handler.h @@ -0,0 +1,242 @@ +// 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/cef_client.h" +#include "cefclient/download_handler.h" +#include "cefclient/util.h" + + +// Define this value to redirect all popup URLs to the main application browser +// window. +// #define TEST_REDIRECT_POPUP_URLS + + +// ClientHandler implementation. +class ClientHandler : public CefClient, + public CefLifeSpanHandler, + public CefLoadHandler, + public CefRequestHandler, + public CefDisplayHandler, + public CefFocusHandler, + public CefKeyboardHandler, + public CefPrintHandler, + public CefV8ContextHandler, + public CefDragHandler, + public CefPermissionHandler, + public DownloadListener { + public: + ClientHandler(); + virtual ~ClientHandler(); + + // CefClient methods + virtual CefRefPtr GetLifeSpanHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetLoadHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetRequestHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetDisplayHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetFocusHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetKeyboardHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetPrintHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetV8ContextHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetDragHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetPermissionHandler() OVERRIDE { + return this; + } + + // CefLifeSpanHandler methods + virtual bool OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) OVERRIDE; + virtual void OnAfterCreated(CefRefPtr browser) OVERRIDE; + virtual bool DoClose(CefRefPtr browser) OVERRIDE; + virtual void OnBeforeClose(CefRefPtr browser) OVERRIDE; + + // CefLoadHandler methods + virtual void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) OVERRIDE; + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE; + virtual bool OnLoadError(CefRefPtr browser, + CefRefPtr frame, + ErrorCode errorCode, + const CefString& failedUrl, + CefString& errorText) OVERRIDE; + + // CefRequestHandler methods + virtual bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) OVERRIDE; + virtual bool GetDownloadHandler(CefRefPtr browser, + const CefString& mimeType, + const CefString& fileName, + int64 contentLength, + CefRefPtr& handler) + OVERRIDE; + + // CefDisplayHandler methods + virtual void OnNavStateChange(CefRefPtr browser, + bool canGoBack, + bool canGoForward) OVERRIDE; + virtual void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) OVERRIDE; + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) OVERRIDE; + virtual bool OnConsoleMessage(CefRefPtr browser, + const CefString& message, + const CefString& source, + int line) OVERRIDE; + + // CefFocusHandler methods. + virtual void OnFocusedNodeChanged(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr node) OVERRIDE; + + // CefKeyboardHandler methods. + virtual bool OnKeyEvent(CefRefPtr browser, + KeyEventType type, + int code, + int modifiers, + bool isSystemKey, + bool isAfterJavaScript) OVERRIDE; + + // CefPrintHandler methods. + virtual bool GetPrintHeaderFooter(CefRefPtr browser, + CefRefPtr frame, + const CefPrintInfo& printInfo, + const CefString& url, + const CefString& title, + int currentPage, + int maxPages, + CefString& topLeft, + CefString& topCenter, + CefString& topRight, + CefString& bottomLeft, + CefString& bottomCenter, + CefString& bottomRight) OVERRIDE; + + // CefV8ContextHandler methods + virtual void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE; + + // CefDragHandler methods. + virtual bool OnDragStart(CefRefPtr browser, + CefRefPtr dragData, + DragOperationsMask mask) OVERRIDE; + virtual bool OnDragEnter(CefRefPtr browser, + CefRefPtr dragData, + DragOperationsMask mask) OVERRIDE; + + // CefPermissionHandler methods. + virtual bool OnBeforeScriptExtensionLoad(CefRefPtr browser, + CefRefPtr frame, + const CefString& extensionName) OVERRIDE; + + // DownloadListener methods + virtual void NotifyDownloadComplete(const CefString& fileName) OVERRIDE; + virtual void NotifyDownloadError(const CefString& fileName) OVERRIDE; + + void SetMainHwnd(CefWindowHandle hwnd); + CefWindowHandle GetMainHwnd() { return m_MainHwnd; } + void SetEditHwnd(CefWindowHandle hwnd); + void SetButtonHwnds(CefWindowHandle backHwnd, + CefWindowHandle forwardHwnd, + CefWindowHandle reloadHwnd, + CefWindowHandle stopHwnd); + + CefRefPtr GetBrowser() { return m_Browser; } + CefWindowHandle GetBrowserHwnd() { return m_BrowserHwnd; } + + std::string GetLogFile(); + + void SetLastDownloadFile(const std::string& fileName); + std::string GetLastDownloadFile(); + + // DOM visitors will be called after the associated path is loaded. + void AddDOMVisitor(const std::string& path, CefRefPtr visitor); + CefRefPtr GetDOMVisitor(const std::string& path); + + // Send a notification to the application. Notifications should not block the + // caller. + enum NotificationType { + NOTIFY_CONSOLE_MESSAGE, + NOTIFY_DOWNLOAD_COMPLETE, + NOTIFY_DOWNLOAD_ERROR, + }; + void SendNotification(NotificationType type); + void CloseMainWindow(); + + protected: + void SetLoading(bool isLoading); + void SetNavState(bool canGoBack, bool canGoForward); + + // The child browser window + CefRefPtr m_Browser; + + // The main frame window handle + CefWindowHandle m_MainHwnd; + + // The child browser window handle + CefWindowHandle m_BrowserHwnd; + + // The edit window handle + CefWindowHandle m_EditHwnd; + + // The button window handles + CefWindowHandle m_BackHwnd; + CefWindowHandle m_ForwardHwnd; + CefWindowHandle m_StopHwnd; + CefWindowHandle m_ReloadHwnd; + + // Support for logging. + std::string m_LogFile; + + // Support for downloading files. + std::string m_LastDownloadFile; + + // Support for DOM visitors. + typedef std::map > DOMVisitorMap; + DOMVisitorMap m_DOMVisitors; + + // True if a form element currently has focus + bool m_bFormElementHasFocus; + + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(ClientHandler); + // Include the default locking implementation. + IMPLEMENT_LOCKING(ClientHandler); +}; + +#endif // CEF_TESTS_CEFCLIENT_CLIENT_HANDLER_H_ diff --git a/cef1/tests/cefclient/client_handler_gtk.cpp b/cef1/tests/cefclient/client_handler_gtk.cpp new file mode 100644 index 000000000..68be0c0b1 --- /dev/null +++ b/cef1/tests/cefclient/client_handler_gtk.cpp @@ -0,0 +1,117 @@ +// 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 "cefclient/client_handler.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/resource_util.h" +#include "cefclient/string_util.h" + +// ClientHandler::ClientLifeSpanHandler implementation +bool ClientHandler::OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) { + REQUIRE_UI_THREAD(); + + return false; +} + +bool ClientHandler::OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) { + REQUIRE_IO_THREAD(); + + std::string url = request->GetURL(); + + if (url == "http://tests/request") { + // Show the request contents + std::string dump; + DumpRequestContents(request, dump); + resourceStream = CefStreamReader::CreateForData( + static_cast(const_cast(dump.c_str())), + dump.size()); + response->SetMimeType("text/plain"); + response->SetStatus(200); + } else if (strstr(url.c_str(), "/ps_logo2.png") != NULL) { + // Any time we find "ps_logo2.png" in the URL substitute in our own image + resourceStream = GetBinaryResourceReader("logo.png"); + response->SetMimeType("image/png"); + response->SetStatus(200); + } else if (url == "http://tests/localstorage") { + // Show the localstorage contents + resourceStream = GetBinaryResourceReader("localstorage.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/xmlhttprequest") { + // Show the xmlhttprequest HTML contents + resourceStream = GetBinaryResourceReader("xmlhttprequest.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/domaccess") { + // Show the domaccess HTML contents + resourceStream = GetBinaryResourceReader("domaccess.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } + + return false; +} + +void ClientHandler::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) { + // Set the edit window text + std::string urlStr(url); + gtk_entry_set_text(GTK_ENTRY(m_EditHwnd), urlStr.c_str()); + } +} + +void ClientHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + REQUIRE_UI_THREAD(); + + GtkWidget* window = + gtk_widget_get_ancestor(GTK_WIDGET(browser->GetWindowHandle()), + GTK_TYPE_WINDOW); + std::string titleStr(title); + gtk_window_set_title(GTK_WINDOW(window), titleStr.c_str()); +} + +void ClientHandler::SendNotification(NotificationType type) { + // TODO(port): Implement this method. +} + +void ClientHandler::SetLoading(bool isLoading) { + if (isLoading) + gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), true); + else + gtk_widget_set_sensitive(GTK_WIDGET(m_StopHwnd), false); +} + +void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { + if (canGoBack) + gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), true); + else + gtk_widget_set_sensitive(GTK_WIDGET(m_BackHwnd), false); + + if (canGoForward) + gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), true); + else + gtk_widget_set_sensitive(GTK_WIDGET(m_ForwardHwnd), false); +} + +void ClientHandler::CloseMainWindow() { + // TODO(port): Close main window. +} diff --git a/cef1/tests/cefclient/client_handler_mac.mm b/cef1/tests/cefclient/client_handler_mac.mm new file mode 100644 index 000000000..3eb5a6615 --- /dev/null +++ b/cef1/tests/cefclient/client_handler_mac.mm @@ -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. + +#import + +#include "cefclient/client_handler.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/cefclient.h" +#include "cefclient/resource_util.h" +#include "cefclient/string_util.h" + +#ifdef TEST_REDIRECT_POPUP_URLS +#include "cefclient/client_popup_handler.h" +#endif + +// ClientHandler::ClientLifeSpanHandler implementation + +bool ClientHandler::OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) { + REQUIRE_UI_THREAD(); + +#ifdef TEST_REDIRECT_POPUP_URLS + std::string urlStr = url; + if (urlStr.find("chrome-devtools:") == std::string::npos) { + // Show all popup windows excluding DevTools in the current window. + windowInfo.m_bHidden = true; + client = new ClientPopupHandler(m_Browser); + } +#endif // TEST_REDIRECT_POPUP_URLS + + return false; +} + +bool ClientHandler::OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) { + REQUIRE_IO_THREAD(); + + std::string url = request->GetURL(); + if (url == "http://tests/request") { + // Show the request contents + std::string dump; + DumpRequestContents(request, dump); + resourceStream = CefStreamReader::CreateForData( + static_cast(const_cast(dump.c_str())), + dump.size()); + response->SetMimeType("text/plain"); + response->SetStatus(200); + } else if (strstr(url.c_str(), "/ps_logo2.png") != NULL) { + // Any time we find "ps_logo2.png" in the URL substitute in our own image + resourceStream = GetBinaryResourceReader("logo.png"); + response->SetMimeType("image/png"); + response->SetStatus(200); + } else if (url == "http://tests/localstorage") { + // Show the localstorage contents + resourceStream = GetBinaryResourceReader("localstorage.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/xmlhttprequest") { + // Show the xmlhttprequest HTML contents + resourceStream = GetBinaryResourceReader("xmlhttprequest.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/domaccess") { + // Show the domaccess HTML contents + resourceStream = GetBinaryResourceReader("domaccess.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } + + return false; +} + +void ClientHandler::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) { + // Set the edit window text + NSTextField* textField = (NSTextField*)m_EditHwnd; + std::string urlStr(url); + NSString* str = [NSString stringWithUTF8String:urlStr.c_str()]; + [textField setStringValue:str]; + } +} + +void ClientHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + REQUIRE_UI_THREAD(); + + // Set the frame window title bar + NSView* view = (NSView*)browser->GetWindowHandle(); + NSWindow* window = [view window]; + std::string titleStr(title); + NSString* str = [NSString stringWithUTF8String:titleStr.c_str()]; + [window setTitle:str]; +} + +void ClientHandler::SendNotification(NotificationType type) { + SEL sel = nil; + switch(type) { + case NOTIFY_CONSOLE_MESSAGE: + sel = @selector(notifyConsoleMessage:); + break; + case NOTIFY_DOWNLOAD_COMPLETE: + sel = @selector(notifyDownloadComplete:); + break; + case NOTIFY_DOWNLOAD_ERROR: + sel = @selector(notifyDownloadError:); + break; + } + + if (sel == nil) + return; + + NSWindow* window = [AppGetMainHwnd() window]; + NSObject* delegate = [window delegate]; + [delegate performSelectorOnMainThread:sel withObject:nil waitUntilDone:NO]; +} + +void ClientHandler::SetLoading(bool isLoading) { + // TODO(port): Change button status. +} + +void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { + // TODO(port): Change button status. +} + +void ClientHandler::CloseMainWindow() { + // TODO(port): Close window +} diff --git a/cef1/tests/cefclient/client_handler_win.cpp b/cef1/tests/cefclient/client_handler_win.cpp new file mode 100644 index 000000000..187a2fa0a --- /dev/null +++ b/cef1/tests/cefclient/client_handler_win.cpp @@ -0,0 +1,180 @@ +// 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/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/resource.h" +#include "cefclient/resource_util.h" +#include "cefclient/string_util.h" + +#ifdef TEST_REDIRECT_POPUP_URLS +#include "cefclient/client_popup_handler.h" +#endif + +bool ClientHandler::OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) { + REQUIRE_UI_THREAD(); + +#ifdef TEST_REDIRECT_POPUP_URLS + std::string urlStr = url; + if (urlStr.find("chrome-devtools:") == std::string::npos) { + // Show all popup windows excluding DevTools in the current window. + windowInfo.m_dwStyle &= ~WS_VISIBLE; + client = new ClientPopupHandler(m_Browser); + } +#endif // TEST_REDIRECT_POPUP_URLS + + return false; +} + +bool ClientHandler::OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) { + REQUIRE_IO_THREAD(); + + std::string url = request->GetURL(); + if (url == "http://tests/request") { + // Show the request contents + std::string dump; + DumpRequestContents(request, dump); + resourceStream = CefStreamReader::CreateForData( + static_cast(const_cast(dump.c_str())), + dump.size()); + response->SetMimeType("text/plain"); + response->SetStatus(200); + } else if (strstr(url.c_str(), "/ps_logo2.png") != NULL) { + // Any time we find "ps_logo2.png" in the URL substitute in our own image + resourceStream = GetBinaryResourceReader(IDS_LOGO); + response->SetMimeType("image/png"); + response->SetStatus(200); + } else if (url == "http://tests/uiapp") { + // Show the uiapp contents + resourceStream = GetBinaryResourceReader(IDS_UIPLUGIN); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/osrapp") { + // Show the osrapp contents + resourceStream = GetBinaryResourceReader(IDS_OSRPLUGIN); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/localstorage") { + // Show the localstorage contents + resourceStream = GetBinaryResourceReader(IDS_LOCALSTORAGE); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/xmlhttprequest") { + // Show the xmlhttprequest HTML contents + resourceStream = GetBinaryResourceReader(IDS_XMLHTTPREQUEST); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/domaccess") { + // Show the domaccess HTML contents + resourceStream = GetBinaryResourceReader(IDS_DOMACCESS); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (strstr(url.c_str(), "/logoball.png") != NULL) { + // Load the "logoball.png" image resource. + resourceStream = GetBinaryResourceReader(IDS_LOGOBALL); + response->SetMimeType("image/png"); + response->SetStatus(200); + } else if (url == "http://tests/modalmain") { + resourceStream = GetBinaryResourceReader(IDS_MODALMAIN); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/modaldialog") { + resourceStream = GetBinaryResourceReader(IDS_MODALDIALOG); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/transparency") { + resourceStream = GetBinaryResourceReader(IDS_TRANSPARENCY); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/plugin") { + std::string html = + "\n" + "Client Plugin loaded by Mime Type:
\n" + "\n" + "

Client Plugin loaded by File Extension:
\n" + "\n" + // Add some extra space below the plugin to allow scrolling. + "
 
\n" + ""; + + resourceStream = CefStreamReader::CreateForData( + static_cast(const_cast(html.c_str())), + html.size()); + response->SetMimeType("text/html"); + response->SetStatus(200); + } + + return false; +} + +void ClientHandler::OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) { + REQUIRE_UI_THREAD(); + + if (m_BrowserHwnd == browser->GetWindowHandle() && frame->IsMain()) { + // Set the edit window text + SetWindowText(m_EditHwnd, std::wstring(url).c_str()); + } +} + +void ClientHandler::OnTitleChange(CefRefPtr browser, + const CefString& title) { + REQUIRE_UI_THREAD(); + + // Set the frame window title bar + CefWindowHandle hwnd = browser->GetWindowHandle(); + if (m_BrowserHwnd == hwnd) { + // The frame window will be the parent of the browser window + hwnd = GetParent(hwnd); + } + SetWindowText(hwnd, std::wstring(title).c_str()); +} + +void ClientHandler::SendNotification(NotificationType type) { + UINT id; + switch (type) { + case NOTIFY_CONSOLE_MESSAGE: + id = ID_WARN_CONSOLEMESSAGE; + break; + case NOTIFY_DOWNLOAD_COMPLETE: + id = ID_WARN_DOWNLOADCOMPLETE; + break; + case NOTIFY_DOWNLOAD_ERROR: + id = ID_WARN_DOWNLOADERROR; + break; + default: + return; + } + PostMessage(m_MainHwnd, WM_COMMAND, id, 0); +} + +void ClientHandler::SetLoading(bool isLoading) { + ASSERT(m_EditHwnd != NULL && m_ReloadHwnd != NULL && m_StopHwnd != NULL); + EnableWindow(m_EditHwnd, TRUE); + EnableWindow(m_ReloadHwnd, !isLoading); + EnableWindow(m_StopHwnd, isLoading); +} + +void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { + ASSERT(m_BackHwnd != NULL && m_ForwardHwnd != NULL); + EnableWindow(m_BackHwnd, canGoBack); + EnableWindow(m_ForwardHwnd, canGoForward); +} + +void ClientHandler::CloseMainWindow() { + ::PostMessage(m_MainHwnd, WM_CLOSE, 0, 0); +} diff --git a/cef1/tests/cefclient/client_popup_handler.cpp b/cef1/tests/cefclient/client_popup_handler.cpp new file mode 100644 index 000000000..dfb48fdb7 --- /dev/null +++ b/cef1/tests/cefclient/client_popup_handler.cpp @@ -0,0 +1,30 @@ +// 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_popup_handler.h" +#include "include/cef_frame.h" +#include "cefclient/util.h" + +ClientPopupHandler::ClientPopupHandler(CefRefPtr parentBrowser) + : m_ParentBrowser(parentBrowser) { + ASSERT(m_ParentBrowser.get()); +} + +ClientPopupHandler::~ClientPopupHandler() { +} + +bool ClientPopupHandler::OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, + bool isRedirect) { + REQUIRE_UI_THREAD(); + + // Load the request in the parent browser window. + m_ParentBrowser->GetMainFrame()->LoadRequest(request); + browser->CloseBrowser(); + m_ParentBrowser = NULL; + + return true; +} diff --git a/cef1/tests/cefclient/client_popup_handler.h b/cef1/tests/cefclient/client_popup_handler.h new file mode 100644 index 000000000..522609e7b --- /dev/null +++ b/cef1/tests/cefclient/client_popup_handler.h @@ -0,0 +1,39 @@ +// 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_POPUP_HANDLER_H_ +#define CEF_TESTS_CEFCLIENT_CLIENT_POPUP_HANDLER_H_ +#pragma once + +#include "include/cef_browser.h" +#include "include/cef_client.h" +#include "include/cef_request_handler.h" + +// Handler for popup windows that loads the request in an existing browser +// window. +class ClientPopupHandler : public CefClient, + public CefRequestHandler { + public: + explicit ClientPopupHandler(CefRefPtr parentBrowser); + virtual ~ClientPopupHandler(); + + // CefClient methods + virtual CefRefPtr GetRequestHandler() OVERRIDE { + return this; + } + + // CefRequestHandler methods + virtual bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, + bool isRedirect) OVERRIDE; + protected: + CefRefPtr m_ParentBrowser; + + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(ClientPopupHandler); +}; + +#endif // CEF_TESTS_CEFCLIENT_CLIENT_POPUP_HANDLER_H_ diff --git a/cef1/tests/cefclient/clientplugin.cpp b/cef1/tests/cefclient/clientplugin.cpp new file mode 100644 index 000000000..cfb14762c --- /dev/null +++ b/cef1/tests/cefclient/clientplugin.cpp @@ -0,0 +1,189 @@ +// Copyright (c) 2008 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. + +#include "cefclient/clientplugin.h" + +#if defined(OS_WIN) + +// Initialized in NP_Initialize. +NPNetscapeFuncs* g_browser = NULL; + +namespace { + +NPError NPP_ClientNew(NPMIMEType plugin_type, NPP instance, uint16_t mode, + int16_t argc, char* argn[], char* argv[], NPSavedData* saved) { + if (instance == NULL) + return NPERR_INVALID_INSTANCE_ERROR; + + ClientPlugin* plugin_impl = new ClientPlugin(mode); + plugin_impl->Initialize(GetModuleHandle(NULL), instance, plugin_type, argc, + argn, argv); + instance->pdata = reinterpret_cast(plugin_impl); + return NPERR_NO_ERROR; +} + +NPError NPP_ClientDestroy(NPP instance, NPSavedData** save) { + ClientPlugin* plugin_impl = reinterpret_cast(instance->pdata); + + if (plugin_impl) { + plugin_impl->Shutdown(); + delete plugin_impl; + } + + return NPERR_NO_ERROR; +} + +NPError NPP_ClientSetWindow(NPP instance, NPWindow* window_info) { + if (instance == NULL) + return NPERR_INVALID_INSTANCE_ERROR; + + if (window_info == NULL) + return NPERR_GENERIC_ERROR; + + ClientPlugin* plugin_impl = reinterpret_cast(instance->pdata); + + if (plugin_impl == NULL) + return NPERR_GENERIC_ERROR; + + HWND window_handle = reinterpret_cast(window_info->window); + if (!plugin_impl->SetWindow(window_handle)) { + delete plugin_impl; + return NPERR_GENERIC_ERROR; + } + + return NPERR_NO_ERROR; +} + +} // namespace + +NPError API_CALL NP_ClientGetEntryPoints(NPPluginFuncs* pFuncs) { + pFuncs->newp = NPP_ClientNew; + pFuncs->destroy = NPP_ClientDestroy; + pFuncs->setwindow = NPP_ClientSetWindow; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_ClientInitialize(NPNetscapeFuncs* pFuncs) { + g_browser = pFuncs; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_ClientShutdown(void) { + g_browser = NULL; + return NPERR_NO_ERROR; +} + + +// ClientPlugin Implementation + +ClientPlugin::ClientPlugin(int16 mode) + : mode_(mode) { +} + +ClientPlugin::~ClientPlugin() { +} + +bool ClientPlugin::Initialize(HINSTANCE module_handle, NPP instance, + NPMIMEType mime_type, int16 argc, char* argn[], + char* argv[]) { + RefreshDisplay(); + return true; +} + +bool ClientPlugin::SetWindow(HWND parent_window) { + if (!::IsWindow(parent_window)) { + // No window created yet. Ignore this call. + if (!IsWindow()) + return true; + // Parent window has been destroyed. + Shutdown(); + return true; + } + + RECT parent_rect; + + if (IsWindow()) { + ::GetClientRect(parent_window, &parent_rect); + SetWindowPos(NULL, &parent_rect, SWP_SHOWWINDOW); + return true; + } + // First time in -- no window created by plugin yet. + ::GetClientRect(parent_window, &parent_rect); + Create(parent_window, parent_rect, NULL, WS_CHILD | WS_BORDER); + + UpdateWindow(); + ShowWindow(SW_SHOW); + + return true; +} + +void ClientPlugin::Shutdown() { + if (IsWindow()) { + DestroyWindow(); + } +} + +LRESULT ClientPlugin::OnPaint(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled) { + PAINTSTRUCT paint_struct; + BeginPaint(&paint_struct); + Paint(paint_struct.hdc); + EndPaint(&paint_struct); + return 0; +} + +// PrintClient is necessary to support off-screen rendering. +LRESULT ClientPlugin::OnPrintClient(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled) { + Paint(reinterpret_cast(wparam)); + return 0; +} + +LRESULT ClientPlugin::OnEraseBackGround(UINT message, WPARAM wparam, + LPARAM lparam, BOOL& handled) { + HDC paint_device_context = reinterpret_cast(wparam); + RECT erase_rect; + GetClipBox(paint_device_context, &erase_rect); + HBRUSH brush = CreateSolidBrush(RGB(0, 255, 0)); + FillRect(paint_device_context, &erase_rect, brush); + DeleteObject(brush); + return 1; +} + +LRESULT ClientPlugin::OnLButtonDown(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled) { + MessageBox(L"You clicked on the client plugin!", L"Client Plugin", MB_OK); + return 0; +} + +void ClientPlugin::RefreshDisplay() { + if (!IsWindow()) + return; + + InvalidateRect(NULL, TRUE); + UpdateWindow(); +} + +void ClientPlugin::Paint(HDC hdc) { + static LPCWSTR text = L"Left click in the green area for a message box!"; + + RECT client_rect; + GetClientRect(&client_rect); + + int old_mode = SetBkMode(hdc, TRANSPARENT); + COLORREF old_color = SetTextColor(hdc, RGB(0, 0, 255)); + + RECT text_rect = client_rect; + DrawText(hdc, text, -1, &text_rect, DT_CENTER | DT_CALCRECT); + + client_rect.top = ((client_rect.bottom - client_rect.top) + - (text_rect.bottom - text_rect.top)) / 2; + DrawText(hdc, text, -1, &client_rect, DT_CENTER); + + SetBkMode(hdc, old_mode); + SetTextColor(hdc, old_color); +} + +#endif // OS_WIN diff --git a/cef1/tests/cefclient/clientplugin.h b/cef1/tests/cefclient/clientplugin.h new file mode 100644 index 000000000..a324ee36c --- /dev/null +++ b/cef1/tests/cefclient/clientplugin.h @@ -0,0 +1,103 @@ +// Copyright (c) 2008 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. + +// Portions of this implementation are borrowed from webkit\default_plugin\ +// plugin_impl.h + +#ifndef CEF_TESTS_CEFCLIENT_CLIENTPLUGIN_H_ +#define CEF_TESTS_CEFCLIENT_CLIENTPLUGIN_H_ +#pragma once + +#include "include/internal/cef_types.h" + +#if defined(OS_WIN) + +#include // NOLINT(build/include_order) +#include // NOLINT(build/include_order) +#include "include/cef_nplugin.h" + +extern NPNetscapeFuncs* g_browser; + +NPError API_CALL NP_ClientGetEntryPoints(NPPluginFuncs* pFuncs); +NPError API_CALL NP_ClientInitialize(NPNetscapeFuncs* pFuncs); +NPError API_CALL NP_ClientShutdown(void); + + +// Provides the client plugin functionality. +class ClientPlugin : public CWindowImpl { + public: + // mode is the plugin instantiation mode, i.e. whether it is a full + // page plugin (NP_FULL) or an embedded plugin (NP_EMBED) + explicit ClientPlugin(int16 mode); + virtual ~ClientPlugin(); + + BEGIN_MSG_MAP(ClientPlugin) + MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackGround) + MESSAGE_HANDLER(WM_PAINT, OnPaint) + MESSAGE_HANDLER(WM_PRINTCLIENT, OnPrintClient) + MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown) + END_MSG_MAP() + + // Initializes the plugin with the instance information, mime type + // and the list of parameters passed down to the plugin from the webpage. + // + // Parameters: + // module_handle + // The handle to the dll in which this object is instantiated. + // instance + // The plugins opaque instance handle. + // mime_type + // Identifies the third party plugin which would be eventually installed. + // argc + // Indicates the count of arguments passed in from the webpage. + // argv + // Pointer to the arguments. + // Returns true on success. + bool Initialize(HINSTANCE module_handle, NPP instance, NPMIMEType mime_type, + int16 argc, char* argn[], char* argv[]); + + // Displays the default plugin UI. + // + // Parameters: + // parent_window + // Handle to the parent window. + bool SetWindow(HWND parent_window); + + // Destroys the install dialog and the plugin window. + void Shutdown(); + + HWND window() const { return m_hWnd; } + + // Getter for the NPP instance member. + const NPP instance() const { + return instance_; + } + + protected: + // Window message handlers. + LRESULT OnPaint(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled); + LRESULT OnPrintClient(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + LRESULT OnEraseBackGround(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + LRESULT OnLButtonDown(UINT message, WPARAM wparam, LPARAM lparam, + BOOL& handled); + + // Enables the plugin window if required and initiates an update of the + // the plugin window. + void RefreshDisplay(); + + void Paint(HDC hdc); + + private: + // The plugins opaque instance handle + NPP instance_; + // The plugin instantiation mode (NP_FULL or NP_EMBED) + int16 mode_; +}; + +#endif // OS_WIN + +#endif // CEF_TESTS_CEFCLIENT_CLIENTPLUGIN_H_ diff --git a/cef1/tests/cefclient/download_handler.cpp b/cef1/tests/cefclient/download_handler.cpp new file mode 100644 index 000000000..ae5c9c9d0 --- /dev/null +++ b/cef1/tests/cefclient/download_handler.cpp @@ -0,0 +1,210 @@ +// 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 "cefclient/download_handler.h" +#include +#include +#include +#include "include/cef_download_handler.h" +#include "include/cef_runnable.h" +#include "cefclient/util.h" + +#if defined(OS_WIN) +#include // NOLINT(build/include_order) +#include // NOLINT(build/include_order) +#include // NOLINT(build/include_order) +#endif // OS_WIN + +// Implementation of the CefDownloadHandler interface. +class ClientDownloadHandler : public CefDownloadHandler { + public: + ClientDownloadHandler(CefRefPtr listener, + const CefString& fileName) + : listener_(listener), filename_(fileName), file_(NULL) { + } + + ~ClientDownloadHandler() { + ASSERT(pending_data_.empty()); + ASSERT(file_ == NULL); + + if (!pending_data_.empty()) { + // Delete remaining pending data. + std::vector*>::iterator it = pending_data_.begin(); + for (; it != pending_data_.end(); ++it) + delete (*it); + } + + if (file_) { + // Close the dangling file pointer on the FILE thread. + CefPostTask(TID_FILE, + NewCefRunnableFunction(&ClientDownloadHandler::CloseDanglingFile, + file_)); + + // Notify the listener that the download failed. + listener_->NotifyDownloadError(filename_); + } + } + + // -------------------------------------------------- + // The following methods are called on the UI thread. + // -------------------------------------------------- + + void Initialize() { + // Open the file on the FILE thread. + CefPostTask(TID_FILE, + NewCefRunnableMethod(this, &ClientDownloadHandler::OnOpen)); + } + + // A portion of the file contents have been received. This method will be + // called multiple times until the download is complete. Return |true| to + // continue receiving data and |false| to cancel. + virtual bool ReceivedData(void* data, int data_size) { + REQUIRE_UI_THREAD(); + + if (data_size == 0) + return true; + + // Create a new vector for the data. + std::vector* buffer = new std::vector(data_size); + memcpy(&(*buffer)[0], data, data_size); + + // Add the new data vector to the pending data queue. + { + AutoLock lock_scope(this); + pending_data_.push_back(buffer); + } + + // Write data to file on the FILE thread. + CefPostTask(TID_FILE, + NewCefRunnableMethod(this, &ClientDownloadHandler::OnReceivedData)); + return true; + } + + // The download is complete. + virtual void Complete() { + REQUIRE_UI_THREAD(); + + // Flush and close the file on the FILE thread. + CefPostTask(TID_FILE, + NewCefRunnableMethod(this, &ClientDownloadHandler::OnComplete)); + } + + // ---------------------------------------------------- + // The following methods are called on the FILE thread. + // ---------------------------------------------------- + + void OnOpen() { + REQUIRE_FILE_THREAD(); + + if (file_) + return; + +#if defined(OS_WIN) + TCHAR szFolderPath[MAX_PATH]; + + // Save the file in the user's "My Documents" folder. + if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, + NULL, 0, szFolderPath))) { + std::wstring fileNameStr = filename_; + LPWSTR name = PathFindFileName(fileNameStr.c_str()); + LPWSTR ext = PathFindExtension(fileNameStr.c_str()); + int ct = 0; + std::wstringstream ss; + + if (ext) { + name[ext-name] = 0; + ext++; + } + + // Make sure the file name is unique. + do { + if (ct > 0) + ss.str(L""); + ss << szFolderPath << L"\\" << name; + if (ct > 0) + ss << L" (" << ct << L")"; + if (ext) + ss << L"." << ext; + ct++; + } while (PathFileExists(ss.str().c_str())); + + { + AutoLock lock_scope(this); + filename_ = ss.str(); + } + + file_ = _wfopen(ss.str().c_str(), L"wb"); + ASSERT(file_ != NULL); + } +#else + // TODO(port): Implement this. + ASSERT(false); // Not implemented +#endif + } + + void OnComplete() { + REQUIRE_FILE_THREAD(); + + if (!file_) + return; + + // Make sure any pending data is written. + OnReceivedData(); + + fclose(file_); + file_ = NULL; + + // Notify the listener that the download completed. + listener_->NotifyDownloadComplete(filename_); + } + + void OnReceivedData() { + REQUIRE_FILE_THREAD(); + + std::vector*> data; + + // Remove all data from the pending data queue. + { + AutoLock lock_scope(this); + if (!pending_data_.empty()) { + data = pending_data_; + pending_data_.clear(); + } + } + + if (data.empty()) + return; + + // Write all pending data to file. + std::vector*>::iterator it = data.begin(); + for (; it != data.end(); ++it) { + std::vector* buffer = *it; + if (file_) + fwrite(&(*buffer)[0], buffer->size(), 1, file_); + delete buffer; + } + data.clear(); + } + + static void CloseDanglingFile(FILE *file) { + fclose(file); + } + + private: + CefRefPtr listener_; + CefString filename_; + FILE* file_; + std::vector*> pending_data_; + + IMPLEMENT_REFCOUNTING(ClientDownloadHandler); + IMPLEMENT_LOCKING(ClientDownloadHandler); +}; + +CefRefPtr CreateDownloadHandler( + CefRefPtr listener, const CefString& fileName) { + CefRefPtr handler = + new ClientDownloadHandler(listener, fileName); + handler->Initialize(); + return handler.get(); +} diff --git a/cef1/tests/cefclient/download_handler.h b/cef1/tests/cefclient/download_handler.h new file mode 100644 index 000000000..40a627ea6 --- /dev/null +++ b/cef1/tests/cefclient/download_handler.h @@ -0,0 +1,27 @@ +// 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_TESTS_CEFCLIENT_DOWNLOAD_HANDLER_H_ +#define CEF_TESTS_CEFCLIENT_DOWNLOAD_HANDLER_H_ +#pragma once + +#include "include/cef_base.h" + +class CefDownloadHandler; + +// Implement this interface to receive download notifications. +class DownloadListener : public virtual CefBase { + public: + // Called when the download is complete. + virtual void NotifyDownloadComplete(const CefString& fileName) =0; + + // Called if the download fails. + virtual void NotifyDownloadError(const CefString& fileName) =0; +}; + +// Create a new download handler to manage download of a single file. +CefRefPtr CreateDownloadHandler( + CefRefPtr listener, const CefString& fileName); + +#endif // CEF_TESTS_CEFCLIENT_DOWNLOAD_HANDLER_H_ diff --git a/cef1/tests/cefclient/extension_test.cpp b/cef1/tests/cefclient/extension_test.cpp new file mode 100644 index 000000000..d8eb7a946 --- /dev/null +++ b/cef1/tests/cefclient/extension_test.cpp @@ -0,0 +1,126 @@ +// 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/extension_test.h" +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_stream.h" +#include "include/cef_v8.h" +#include "cefclient/resource_util.h" + +// Implementation of the V8 handler class for the "cef.test" extension. +class ClientV8ExtensionHandler : public CefV8Handler { + public: + ClientV8ExtensionHandler() : test_param_("An initial string value.") {} + virtual ~ClientV8ExtensionHandler() {} + + // Execute with the specified argument list and return value. Return true if + // the method was handled. + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) { + if (name == "Dummy") { + // Used for performance testing. + return true; + } else if (name == "SetTestParam") { + // Handle the SetTestParam native function by saving the string argument + // into the local member. + if (arguments.size() != 1 || !arguments[0]->IsString()) + return false; + + test_param_ = arguments[0]->GetStringValue(); + return true; + } else if (name == "GetTestParam") { + // Handle the GetTestParam native function by returning the local member + // value. + retval = CefV8Value::CreateString(test_param_); + return true; + } else if (name == "GetTestObject") { + // Handle the GetTestObject native function by creating and returning a + // new V8 object. + retval = CefV8Value::CreateObject(NULL); + // Add a string parameter to the new V8 object. + retval->SetValue("param", CefV8Value::CreateString( + "Retrieving a parameter on a native object succeeded."), + V8_PROPERTY_ATTRIBUTE_NONE); + // Add a function to the new V8 object. + retval->SetValue("GetMessage", + CefV8Value::CreateFunction("GetMessage", this), + V8_PROPERTY_ATTRIBUTE_NONE); + return true; + } else if (name == "GetMessage") { + // Handle the GetMessage object function by returning a string. + retval = CefV8Value::CreateString( + "Calling a function on a native object succeeded."); + return true; + } + return false; + } + + private: + CefString test_param_; + + IMPLEMENT_REFCOUNTING(ClientV8ExtensionHandler); +}; + + +void InitExtensionTest() { + // Register a V8 extension with the below JavaScript code that calls native + // methods implemented in ClientV8ExtensionHandler. + std::string code = "var cef;" + "if (!cef)" + " cef = {};" + "if (!cef.test)" + " cef.test = {};" + "(function() {" + " cef.test.__defineGetter__('test_param', function() {" + " native function GetTestParam();" + " return GetTestParam();" + " });" + " cef.test.__defineSetter__('test_param', function(b) {" + " native function SetTestParam();" + " if (b) SetTestParam(b);" + " });" + " cef.test.test_object = function() {" + " native function GetTestObject();" + " return GetTestObject();" + " };" + " cef.test.dummy = function() {" + " native function Dummy();" + " return Dummy();" + " };" + "})();"; + CefRegisterExtension("v8/test", code, new ClientV8ExtensionHandler()); +} + +void RunExtensionTest(CefRefPtr browser) { + std::string html = + "ClientV8ExtensionHandler says:
"
+    ""
+    "
"; + browser->GetMainFrame()->LoadString(html, "about:blank"); +} + +void RunExtensionPerfTest(CefRefPtr browser) { + CefRefPtr resourceStream; +#if defined(OS_WIN) + resourceStream = GetBinaryResourceReader(IDS_EXTENSIONPERF); +#elif defined(OS_MACOSX) + resourceStream = GetBinaryResourceReader("extensionperf.html"); +#endif + browser->GetMainFrame()->LoadStream(resourceStream, "about:blank"); +} diff --git a/cef1/tests/cefclient/extension_test.h b/cef1/tests/cefclient/extension_test.h new file mode 100644 index 000000000..d0a7e04be --- /dev/null +++ b/cef1/tests/cefclient/extension_test.h @@ -0,0 +1,20 @@ +// 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_EXTENSION_TEST_H_ +#define CEF_TESTS_CEFCLIENT_EXTENSION_TEST_H_ +#pragma once + +#include "include/cef_base.h" + +class CefBrowser; + +// Register the V8 extension handler. +void InitExtensionTest(); + +// Run the test. +void RunExtensionTest(CefRefPtr browser); +void RunExtensionPerfTest(CefRefPtr browser); + +#endif // CEF_TESTS_CEFCLIENT_EXTENSION_TEST_H_ diff --git a/cef1/tests/cefclient/mac/English.lproj/InfoPlist.strings b/cef1/tests/cefclient/mac/English.lproj/InfoPlist.strings new file mode 100644 index 000000000..fe2abe11b --- /dev/null +++ b/cef1/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/cef1/tests/cefclient/mac/English.lproj/MainMenu.xib b/cef1/tests/cefclient/mac/English.lproj/MainMenu.xib new file mode 100644 index 000000000..e4f7c1fc3 --- /dev/null +++ b/cef1/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/cef1/tests/cefclient/mac/Info.plist b/cef1/tests/cefclient/mac/Info.plist new file mode 100644 index 000000000..83c535e41 --- /dev/null +++ b/cef1/tests/cefclient/mac/Info.plist @@ -0,0 +1,28 @@ + + + + + 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 + + diff --git a/cef1/tests/cefclient/mac/cefclient.icns b/cef1/tests/cefclient/mac/cefclient.icns new file mode 100644 index 000000000..f36742de2 Binary files /dev/null and b/cef1/tests/cefclient/mac/cefclient.icns differ diff --git a/cef1/tests/cefclient/osrenderer.cpp b/cef1/tests/cefclient/osrenderer.cpp new file mode 100644 index 000000000..486e8f1e7 --- /dev/null +++ b/cef1/tests/cefclient/osrenderer.cpp @@ -0,0 +1,432 @@ +// 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/osrenderer.h" +#include "cefclient/util.h" + +#if defined(OS_WIN) +#include +#include +#elif defined(OS_MACOSX) +#include +#else +#error Platform is not supported. +#endif + +namespace { + +// Convert from BGRA to RGBA format and from upper-left to lower-left origin. +void ConvertToRGBA(const unsigned char* src, unsigned char* dst, + int width, int height) { + int sp = 0, dp = (height-1) * width * 4; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++, dp += 4, sp += 4) { + dst[dp] = src[sp+2]; // R + dst[dp+1] = src[sp+1]; // G + dst[dp+2] = src[sp]; // B + dst[dp+3] = src[sp+3]; // A + } + dp -= width * 8; + } +} + +void ConvertToRGBARect(const CefRect& clipRect, + const unsigned char* src, unsigned char* dst, + int width, int height) { + int sp = 0, dp = (height-1) * width * 4; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++, dp += 4, sp += 4) { + if ((clipRect.x <= j) && (clipRect.x + clipRect.width > j) && + (clipRect.y <= i) && (clipRect.y + clipRect.height > i)) { + dst[dp] = src[sp+2]; // R + dst[dp+1] = src[sp+1]; // G + dst[dp+2] = src[sp]; // B + dst[dp+3] = src[sp+3]; // A + } + } + dp -= width * 8; + } +} + +// Convert from BGRA to RGB format and from upper-left to lower-left origin. +void ConvertToRGB(const unsigned char* src, unsigned char* dst, + int width, int height) { + int sp = 0, dp = (height-1) * width * 3; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++, dp += 3, sp += 4) { + dst[dp] = src[sp+2]; // R + dst[dp+1] = src[sp+1]; // G + dst[dp+2] = src[sp]; // B + } + dp -= width * 6; + } +} + +void ConvertToRGBRect(const CefRect& clipRect, + const unsigned char* src, unsigned char* dst, + int width, int height) { + int sp = 0, dp = (height-1) * width * 3; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++, dp += 3, sp += 4) { + if ((clipRect.x <= j) && (clipRect.x + clipRect.width > j) && + (clipRect.y <= i) && (clipRect.y + clipRect.height > i)) { + dst[dp] = src[sp+2]; // R + dst[dp+1] = src[sp+1]; // G + dst[dp+2] = src[sp]; // B + } + } + dp -= width * 6; + } +} + +} // namespace + +ClientOSRenderer::ClientOSRenderer(bool transparent) + : transparent_(transparent), + initialized_(false), + texture_id_(0), + view_buffer_(NULL), + view_buffer_size_(0), + popup_buffer_(NULL), + popup_buffer_size_(0), + view_width_(0), + view_height_(0), + spin_x_(0), + spin_y_(0) { +} + +ClientOSRenderer::~ClientOSRenderer() { + Cleanup(); +} + +void ClientOSRenderer::Initialize() { + if (initialized_) + return; + + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + + // Necessary for non-power-of-2 textures to render correctly. + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + if (transparent_) { + // Alpha blending style. Texture values have premultiplied alpha. + glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + } + + initialized_ = true; +} + +void ClientOSRenderer::Cleanup() { + if (view_buffer_) { + delete [] view_buffer_; + view_buffer_ = NULL; + view_buffer_size_ = 0; + } + if (popup_buffer_) { + delete [] popup_buffer_; + popup_buffer_ = NULL; + popup_buffer_size_ = 0; + } + + if (texture_id_ != 0) + glDeleteTextures(1, &texture_id_); +} + +void ClientOSRenderer::SetSize(int width, int height) { + if (!initialized_) + Initialize(); + + // Match GL units to screen coordinates. + glViewport(0, 0, width, height); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, 0, width, height, 0.1, 100.0); + + if (transparent_) { + // Enable alpha blending. + glEnable(GL_BLEND); + } + + // Enable 2D textures. + glEnable(GL_TEXTURE_2D); + + GLuint new_texture_id = 0; + + // Create a new texture. + glGenTextures(1, &new_texture_id); + ASSERT(new_texture_id != 0); + glBindTexture(GL_TEXTURE_2D, new_texture_id); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + + // Start with all white contents. + { + int size = width * height * (transparent_?4:3); + unsigned char* buffer = new unsigned char[size]; + memset(buffer, 255, size); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, + transparent_?GL_RGBA:GL_RGB, GL_UNSIGNED_BYTE, buffer); + + delete [] buffer; + } + + if (texture_id_ != 0) { + // Draw the existing view buffer to the new texture. + DrawViewBuffer(width, height); + + // Delete the old texture. + glDeleteTextures(1, &texture_id_); + } + + texture_id_ = new_texture_id; + + // Disable 2D textures. + glDisable(GL_TEXTURE_2D); + + if (transparent_) { + // Disable alpha blending. + glDisable(GL_BLEND); + } +} + +void ClientOSRenderer::Render() { + ASSERT(initialized_); + + struct { + float tu, tv; + float x, y, z; + } static vertices[] = { + {0.0f, 0.0f, -1.0f, -1.0f, 0.0f}, + {1.0f, 0.0f, 1.0f, -1.0f, 0.0f}, + {1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, + {0.0f, 1.0f, -1.0f, 1.0f, 0.0f} + }; + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + // Draw the background gradient. + glPushAttrib(GL_ALL_ATTRIB_BITS); + glBegin(GL_QUADS); + glColor4f(1.0, 0.0, 0.0, 1.0); // red + glVertex2f(-1.0, -1.0); + glVertex2f(1.0, -1.0); + glColor4f(0.0, 0.0, 1.0, 1.0); // blue + glVertex2f(1.0, 1.0); + glVertex2f(-1.0, 1.0); + glEnd(); + glPopAttrib(); + + // Rotate the view based on the mouse spin. + glRotatef(-spin_x_, 1.0f, 0.0f, 0.0f); + glRotatef(-spin_y_, 0.0f, 1.0f, 0.0f); + + if (transparent_) { + // Enable alpha blending. + glEnable(GL_BLEND); + } + + // Enable 2D textures. + glEnable(GL_TEXTURE_2D); + + // Draw the facets with the texture. + ASSERT(texture_id_ != 0); + glBindTexture(GL_TEXTURE_2D, texture_id_); + glInterleavedArrays(GL_T2F_V3F, 0, vertices); + glDrawArrays(GL_QUADS, 0, 4); + + // Disable 2D textures. + glDisable(GL_TEXTURE_2D); + + if (transparent_) { + // Disable alpha blending. + glDisable(GL_BLEND); + } + + glFlush(); +} + +void ClientOSRenderer::OnPopupShow(CefRefPtr browser, + bool show) { + if (!show) { + // Clear the popup buffer. + popup_rect_.Set(0, 0, 0, 0); + if (popup_buffer_) { + delete [] popup_buffer_; + popup_buffer_ = NULL; + popup_buffer_size_ = 0; + } + } +} + +void ClientOSRenderer::OnPopupSize(CefRefPtr browser, + const CefRect& rect) { + if (rect.width > 0) { + // Update the popup rectange. It should always be inside the view. + ASSERT(rect.x + rect.width < view_width_ && + rect.y + rect.height < view_height_); + popup_rect_ = rect; + } +} + +void ClientOSRenderer::OnPaint(CefRefPtr browser, + CefRenderHandler::PaintElementType type, + const CefRenderHandler::RectList& dirtyRects, + const void* buffer) { + ASSERT(initialized_); + + // Retrieve the current size of the browser view. + browser->GetSize(type, view_width_, view_height_); + + if (transparent_) { + // Enable alpha blending. + glEnable(GL_BLEND); + } + + // Enable 2D textures. + glEnable(GL_TEXTURE_2D); + + ASSERT(texture_id_ != 0); + glBindTexture(GL_TEXTURE_2D, texture_id_); + + if (type == PET_VIEW) { + SetBufferSize(view_width_, view_height_, true); + + // Paint the view. + if (transparent_) { + CefRenderHandler::RectList::const_iterator i = dirtyRects.begin(); + for (; i != dirtyRects.end(); ++i) { + ConvertToRGBARect(*i, (unsigned char*)buffer, view_buffer_, + view_width_, view_height_); + } + } else { + CefRenderHandler::RectList::const_iterator i = dirtyRects.begin(); + for (; i != dirtyRects.end(); ++i) { + ConvertToRGBRect(*i, (unsigned char*)buffer, view_buffer_, + view_width_, view_height_); + } + } + + // Update the whole texture. This is done for simplicity instead of + // updating just the dirty region. + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, view_width_, view_height_, + transparent_?GL_RGBA:GL_RGB, GL_UNSIGNED_BYTE, view_buffer_); + } + + if (popup_rect_.width > 0) { + if (type == PET_POPUP) { + // Paint the popup. + if (transparent_) + SetRGBA(buffer, popup_rect_.width, popup_rect_.height, false); + else + SetRGB(buffer, popup_rect_.width, popup_rect_.height, false); + } + + if (popup_buffer_) { + // Update the popup region. + glTexSubImage2D(GL_TEXTURE_2D, 0, popup_rect_.x, + view_height_ - popup_rect_.y - popup_rect_.height, + popup_rect_.width, popup_rect_.height, + transparent_?GL_RGBA:GL_RGB, + GL_UNSIGNED_BYTE, popup_buffer_); + } + } + + // Disable 2D textures. + glDisable(GL_TEXTURE_2D); + + if (transparent_) { + // Disable alpha blending. + glDisable(GL_BLEND); + } +} + +void ClientOSRenderer::SetSpin(float spinX, float spinY) { + spin_x_ = spinX; + spin_y_ = spinY; +} + +void ClientOSRenderer::IncrementSpin(float spinDX, float spinDY) { + spin_x_ -= spinDX; + spin_y_ -= spinDY; +} + +bool ClientOSRenderer::GetPixelValue(int x, int y, unsigned char& r, + unsigned char& g, unsigned char& b, + unsigned char& a) { + if (!view_buffer_) + return false; + + ASSERT(x >= 0 && x < view_width_); + ASSERT(y >= 0 && y < view_height_); + + int pixel_bytes = transparent_ ? 4 : 3; + int y_flipped = view_height_ - y; + int index = (view_width_ * y_flipped * pixel_bytes) + (x * pixel_bytes); + + r = view_buffer_[index]; + g = view_buffer_[index+1]; + b = view_buffer_[index+2]; + if (transparent_) + a = view_buffer_[index+3]; + + return true; +} + +void ClientOSRenderer::SetBufferSize(int width, int height, bool view) { + int dst_size = width * height * (transparent_?4:3); + + // Allocate a new buffer if necesary. + if (view) { + if (dst_size > view_buffer_size_) { + if (view_buffer_) + delete [] view_buffer_; + view_buffer_ = new unsigned char[dst_size]; + view_buffer_size_ = dst_size; + } + } else { + if (dst_size > popup_buffer_size_) { + if (popup_buffer_) + delete [] popup_buffer_; + popup_buffer_ = new unsigned char[dst_size]; + popup_buffer_size_ = dst_size; + } + } +} + +// Set the contents of the RGBA buffer. +void ClientOSRenderer::SetRGBA(const void* src, int width, int height, + bool view) { + SetBufferSize(width, height, view); + ConvertToRGBA((unsigned char*)src, view?view_buffer_:popup_buffer_, width, + height); +} + +// Set the contents of the RGB buffer. +void ClientOSRenderer::SetRGB(const void* src, int width, int height, + bool view) { + SetBufferSize(width, height, view); + ConvertToRGB((unsigned char*)src, view?view_buffer_:popup_buffer_, width, + height); +} + +void ClientOSRenderer::DrawViewBuffer(int max_width, int max_height) { + if (max_width < view_width_ || max_height < view_height_) { + // The requested max size is smaller than the current view buffer. + int width = std::min(max_width, view_width_); + int height = std::min(max_height, view_height_); + + glPixelStorei(GL_UNPACK_ROW_LENGTH, view_width_); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, + transparent_?GL_RGBA:GL_RGB, GL_UNSIGNED_BYTE, + view_buffer_); + glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); + } else { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, view_width_, view_height_, + transparent_?GL_RGBA:GL_RGB, GL_UNSIGNED_BYTE, view_buffer_); + } +} diff --git a/cef1/tests/cefclient/osrenderer.h b/cef1/tests/cefclient/osrenderer.h new file mode 100644 index 000000000..75ac808ac --- /dev/null +++ b/cef1/tests/cefclient/osrenderer.h @@ -0,0 +1,71 @@ +// 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_OSRENDERER_H_ +#define CEF_TESTS_CEFCLIENT_OSRENDERER_H_ + +#include "include/cef_browser.h" +#include "include/cef_render_handler.h" + +class ClientOSRenderer { + public: + // The context must outlive this object. + explicit ClientOSRenderer(bool transparent); + virtual ~ClientOSRenderer(); + + // Initialize the OpenGL environment. + void Initialize(); + + // Clean up the OpenGL environment. + void Cleanup(); + + // Set the size of the viewport. + void SetSize(int width, int height); + + // Render to the screen. + void Render(); + + // Forwarded from CefRenderHandler callbacks. + void OnPopupShow(CefRefPtr browser, + bool show); + void OnPopupSize(CefRefPtr browser, + const CefRect& rect); + void OnPaint(CefRefPtr browser, + CefRenderHandler::PaintElementType type, + const CefRenderHandler::RectList& dirtyRects, + const void* buffer); + + // Apply spin. + void SetSpin(float spinX, float spinY); + void IncrementSpin(float spinDX, float spinDY); + + // Retrieve the pixel value from the view buffer. |x| and |y| are relative to + // the upper-left corner of the view. + bool GetPixelValue(int x, int y, unsigned char& r, unsigned char& g, + unsigned char& b, unsigned char& a); + + bool IsTransparent() { return transparent_; } + + private: + void SetBufferSize(int width, int height, bool view); + void SetRGBA(const void* src, int width, int height, bool view); + void SetRGB(const void* src, int width, int height, bool view); + void DrawViewBuffer(int max_width, int max_height); + + bool transparent_; + bool initialized_; + unsigned int texture_id_; + unsigned char* view_buffer_; + int view_buffer_size_; + unsigned char* popup_buffer_; + int popup_buffer_size_; + CefRect popup_rect_; + int view_width_; + int view_height_; + float spin_x_; + float spin_y_; +}; + +#endif // CEF_TESTS_CEFCLIENT_OSR_RENDERER_H_ + diff --git a/cef1/tests/cefclient/osrplugin.cpp b/cef1/tests/cefclient/osrplugin.cpp new file mode 100644 index 000000000..5bbc95c01 --- /dev/null +++ b/cef1/tests/cefclient/osrplugin.cpp @@ -0,0 +1,648 @@ +// 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. + +#include "cefclient/osrplugin.h" +#include "cefclient/osrenderer.h" + +#if defined(OS_WIN) + +#include +#define _USE_MATH_DEFINES +#include +#include +#include +#include +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/cefclient.h" +#include "cefclient/client_popup_handler.h" +#include "cefclient/resource.h" +#include "cefclient/resource_util.h" +#include "cefclient/string_util.h" +#include "cefclient/util.h" + +// Initialized in NP_Initialize. +NPNetscapeFuncs* g_osrbrowser = NULL; + +namespace { + +CefRefPtr g_offscreenBrowser; + +// If set to true alpha transparency will be used. +bool g_offscreenTransparent = false; + +// Class holding pointers for the client plugin window. +class ClientPlugin { + public: + ClientPlugin(bool transparent) + : renderer(transparent), + hWnd(NULL), + hDC(NULL), + hRC(NULL) { + } + + ClientOSRenderer renderer; + HWND hWnd; + HDC hDC; + HGLRC hRC; +}; + +// Handler for off-screen rendering windows. +class ClientOSRHandler : public CefClient, + public CefLifeSpanHandler, + public CefLoadHandler, + public CefRequestHandler, + public CefDisplayHandler, + public CefRenderHandler { + public: + explicit ClientOSRHandler(ClientPlugin* plugin) + : plugin_(plugin) { + } + ~ClientOSRHandler() { + } + + // CefClient methods + virtual CefRefPtr GetLifeSpanHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetLoadHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetRequestHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetDisplayHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetRenderHandler() OVERRIDE { + return this; + } + + // CefLifeSpanHandler methods + + virtual bool OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) OVERRIDE { + REQUIRE_UI_THREAD(); + + windowInfo.m_bWindowRenderingDisabled = TRUE; + client = new ClientPopupHandler(g_offscreenBrowser); + return false; + } + + virtual void OnAfterCreated(CefRefPtr browser) OVERRIDE { + REQUIRE_UI_THREAD(); + + g_offscreenBrowser = browser; + + // Set the off-screen browser size to match the plugin window size. + RECT clientRect; + ::GetClientRect(plugin_->hWnd, &clientRect); + g_offscreenBrowser->SetSize(PET_VIEW, clientRect.right, clientRect.bottom); + } + + virtual void OnBeforeClose(CefRefPtr browser) OVERRIDE { + g_offscreenBrowser = NULL; + } + + // CefLoadHandler methods + + virtual void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!browser->IsPopup() && frame->IsMain()) { + // We've just started loading a page + SetLoading(true); + } + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!browser->IsPopup() && frame->IsMain()) { + // We've just finished loading a page + SetLoading(false); + } + } + + // CefRequestHandler methods + + virtual bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) OVERRIDE { + REQUIRE_IO_THREAD(); + + std::string url = request->GetURL(); + if (url == "http://tests/transparency") { + resourceStream = GetBinaryResourceReader(IDS_TRANSPARENCY); + response->SetMimeType("text/html"); + response->SetStatus(200); + } + + return false; + } + + // CefDisplayHandler methods + + virtual void OnNavStateChange(CefRefPtr browser, + bool canGoBack, + bool canGoForward) OVERRIDE { + REQUIRE_UI_THREAD(); + + // Set the "back" and "forward" button state in the HTML. + std::stringstream ss; + ss << "document.getElementById('back').disabled = " + << (canGoBack?"false":"true") << ";"; + ss << "document.getElementById('forward').disabled = " + << (canGoForward?"false":"true") << ";"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0); + } + + virtual void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) OVERRIDE { + REQUIRE_UI_THREAD(); + + // Set the "url" value in the HTML. + std::stringstream ss; + std::string urlStr = url; + StringReplace(urlStr, "'", "\\'"); + ss << "document.getElementById('url').value = '" << urlStr.c_str() << "'"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0); + } + + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) OVERRIDE { + REQUIRE_UI_THREAD(); + + // Set the "title" value in the HTML. + std::stringstream ss; + std::string titleStr = title; + StringReplace(titleStr, "'", "\\'"); + ss << "document.getElementById('title').innerHTML = '" << + titleStr.c_str() << "'"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0); + } + + // CefRenderHandler methods + + virtual bool GetViewRect(CefRefPtr browser, + CefRect& rect) OVERRIDE { + REQUIRE_UI_THREAD(); + + // The simulated screen and view rectangle are the same. This is necessary + // for popup menus to be located and sized inside the view. + RECT clientRect; + ::GetClientRect(plugin_->hWnd, &clientRect); + + rect.x = rect.y = 0; + rect.width = clientRect.right; + rect.height = clientRect.bottom; + return true; + } + + virtual bool GetScreenRect(CefRefPtr browser, + CefRect& rect) OVERRIDE { + return GetViewRect(browser, rect); + } + + virtual bool GetScreenPoint(CefRefPtr browser, + int viewX, + int viewY, + int& screenX, + int& screenY) OVERRIDE { + REQUIRE_UI_THREAD(); + + // Convert the point from view coordinates to actual screen coordinates. + POINT screen_pt = {viewX, viewY}; + MapWindowPoints(plugin_->hWnd, HWND_DESKTOP, &screen_pt, 1); + screenX = screen_pt.x; + screenY = screen_pt.y; + return true; + } + + virtual void OnPopupShow(CefRefPtr browser, + bool show) OVERRIDE { + REQUIRE_UI_THREAD(); + plugin_->renderer.OnPopupShow(browser, show); + } + + virtual void OnPopupSize(CefRefPtr browser, + const CefRect& rect) OVERRIDE { + REQUIRE_UI_THREAD(); + plugin_->renderer.OnPopupSize(browser, rect); + } + + virtual void OnPaint(CefRefPtr browser, + PaintElementType type, + const RectList& dirtyRects, + const void* buffer) OVERRIDE { + REQUIRE_UI_THREAD(); + + wglMakeCurrent(plugin_->hDC, plugin_->hRC); + plugin_->renderer.OnPaint(browser, type, dirtyRects, buffer); + } + + virtual void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor) OVERRIDE { + REQUIRE_UI_THREAD(); + + // Change the plugin window's cursor. + SetClassLong(plugin_->hWnd, GCL_HCURSOR, + static_cast(reinterpret_cast(cursor))); + SetCursor(cursor); + } + + private: + void SetLoading(bool isLoading) { + // Set the "stop" and "reload" button state in the HTML. + std::stringstream ss; + ss << "document.getElementById('stop').disabled = " + << (isLoading?"false":"true") << ";" + << "document.getElementById('reload').disabled = " + << (isLoading?"true":"false") << ";"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(ss.str(), "", 0); + } + + ClientPlugin* plugin_; + + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(ClientOSRPlugin); +}; + +// Forward declarations of functions included in this code module: +LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam); + +// Enable GL. +void EnableGL(ClientPlugin* plugin) { + PIXELFORMATDESCRIPTOR pfd; + int format; + + // Get the device context. + plugin->hDC = GetDC(plugin->hWnd); + + // Set the pixel format for the DC. + ZeroMemory(&pfd, sizeof(pfd)); + pfd.nSize = sizeof(pfd); + pfd.nVersion = 1; + pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + pfd.iPixelType = PFD_TYPE_RGBA; + pfd.cColorBits = 24; + pfd.cDepthBits = 16; + pfd.iLayerType = PFD_MAIN_PLANE; + format = ChoosePixelFormat(plugin->hDC, &pfd); + SetPixelFormat(plugin->hDC, format, &pfd); + + // Create and enable the render context. + plugin->hRC = wglCreateContext(plugin->hDC); + wglMakeCurrent(plugin->hDC, plugin->hRC); + + plugin->renderer.Initialize(); +} + +// Disable GL. +void DisableGL(ClientPlugin* plugin) { + plugin->renderer.Cleanup(); + + wglMakeCurrent(NULL, NULL); + wglDeleteContext(plugin->hRC); + ReleaseDC(plugin->hWnd, plugin->hDC); +} + +// Size the GL view. +void SizeGL(ClientPlugin* plugin, int width, int height) { + wglMakeCurrent(plugin->hDC, plugin->hRC); + + plugin->renderer.SetSize(width, height); + + if (g_offscreenBrowser.get()) + g_offscreenBrowser->SetSize(PET_VIEW, width, height); +} + +// Render the view contents. +void RenderGL(ClientPlugin* plugin) { + wglMakeCurrent(plugin->hDC, plugin->hRC); + + plugin->renderer.Render(); + + SwapBuffers(plugin->hDC); +} + +NPError NPP_NewImpl(NPMIMEType plugin_type, NPP instance, uint16 mode, + int16 argc, char* argn[], char* argv[], + NPSavedData* saved) { + if (instance == NULL) + return NPERR_INVALID_INSTANCE_ERROR; + + ClientPlugin* plugin = new ClientPlugin(g_offscreenTransparent); + instance->pdata = reinterpret_cast(plugin); + + return NPERR_NO_ERROR; +} + +NPError NPP_DestroyImpl(NPP instance, NPSavedData** save) { + ClientPlugin* plugin = reinterpret_cast(instance->pdata); + + if (plugin) { + if (plugin->hWnd) { + DestroyWindow(plugin->hWnd); + DisableGL(plugin); + } + delete plugin; + } + + return NPERR_NO_ERROR; +} + +NPError NPP_SetWindowImpl(NPP instance, NPWindow* window_info) { + if (instance == NULL) + return NPERR_INVALID_INSTANCE_ERROR; + + if (window_info == NULL) + return NPERR_GENERIC_ERROR; + + ClientPlugin* plugin = reinterpret_cast(instance->pdata); + HWND parent_hwnd = reinterpret_cast(window_info->window); + + if (plugin->hWnd == NULL) { + WNDCLASS wc; + HINSTANCE hInstance = GetModuleHandle(NULL); + + // Register the window class. + wc.style = CS_OWNDC; + wc.lpfnWndProc = PluginWndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); + wc.lpszMenuName = NULL; + wc.lpszClassName = L"ClientOSRPlugin"; + RegisterClass(&wc); + + // Create the main window. + plugin->hWnd = CreateWindow(L"ClientOSRPlugin", L"Client OSR Plugin", + WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 0, 0, 0, 0, parent_hwnd, NULL, + hInstance, NULL); + + SetWindowLongPtr(plugin->hWnd, GWLP_USERDATA, + reinterpret_cast(plugin)); + + // Enable GL drawing for the window. + EnableGL(plugin); + + // Create the off-screen rendering window. + CefWindowInfo windowInfo; + CefBrowserSettings settings; + windowInfo.SetAsOffScreen(plugin->hWnd); + if (g_offscreenTransparent) + windowInfo.SetTransparentPainting(TRUE); + CefBrowser::CreateBrowser(windowInfo, new ClientOSRHandler(plugin), + "http://www.google.com", settings); + } + + // Position the plugin window and make sure it's visible. + RECT parent_rect; + GetClientRect(parent_hwnd, &parent_rect); + SetWindowPos(plugin->hWnd, NULL, parent_rect.left, parent_rect.top, + parent_rect.right - parent_rect.left, + parent_rect.bottom - parent_rect.top, SWP_SHOWWINDOW); + + UpdateWindow(plugin->hWnd); + ShowWindow(plugin->hWnd, SW_SHOW); + + return NPERR_NO_ERROR; +} + +// Plugin window procedure. +LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam) { + static POINT lastMousePos, curMousePos; + static bool mouseRotation = false; + static bool mouseTracking = false; + + ClientPlugin* plugin = + reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); + + switch (message) { + case WM_CREATE: + // Start the timer that's used for redrawing. + SetTimer(hWnd, 1, 20, NULL); + return 0; + + case WM_DESTROY: + // Stop the timer that's used for redrawing. + KillTimer(hWnd, 1); + + // Explicitly close the offscreen browser and release the reference. + g_offscreenBrowser->CloseBrowser(); + g_offscreenBrowser = NULL; + return 0; + + case WM_TIMER: + RenderGL(plugin); + break; + + case WM_LBUTTONDOWN: + case WM_RBUTTONDOWN: + SetCapture(hWnd); + SetFocus(hWnd); + if (wParam & MK_SHIFT) { + // Start rotation effect. + lastMousePos.x = curMousePos.x = LOWORD(lParam); + lastMousePos.y = curMousePos.y = HIWORD(lParam); + mouseRotation = true; + } else if (wParam & MK_CONTROL) { + // Retrieve the pixel value. + int x = LOWORD(lParam); + int y = HIWORD(lParam); + unsigned char r, g, b, a; + if (plugin->renderer.GetPixelValue(x, y, r, g, b, a)) { + std::stringstream ss; + ss << x << "," << y << " = R:" << static_cast(r) << " G:" << + static_cast(g) << " B:" << static_cast(b); + if (plugin->renderer.IsTransparent()) + ss << " A:" << static_cast(a); + + std::string js = + "document.getElementById('pixel').innerText = '" + ss.str() + "';"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(js, "", 0); + } + } else { + if (g_offscreenBrowser.get()) { + g_offscreenBrowser->SendMouseClickEvent(LOWORD(lParam), HIWORD(lParam), + (message == WM_LBUTTONDOWN?MBT_LEFT:MBT_RIGHT), false, 1); + } + } + break; + + case WM_LBUTTONUP: + case WM_RBUTTONUP: + if (GetCapture() == hWnd) + ReleaseCapture(); + if (mouseRotation) { + // End rotation effect. + mouseRotation = false; + plugin->renderer.SetSpin(0, 0); + } else { + if (g_offscreenBrowser.get()) { + g_offscreenBrowser->SendMouseClickEvent(LOWORD(lParam), HIWORD(lParam), + (message == WM_LBUTTONUP?MBT_LEFT:MBT_RIGHT), true, 1); + } + } + break; + + case WM_MOUSEMOVE: + if (mouseRotation) { + // Apply rotation effect. + curMousePos.x = LOWORD(lParam); + curMousePos.y = HIWORD(lParam); + plugin->renderer.IncrementSpin((curMousePos.x - lastMousePos.x), + (curMousePos.y - lastMousePos.y)); + lastMousePos.x = curMousePos.x; + lastMousePos.y = curMousePos.y; + } else { + if (!mouseTracking) { + // Start tracking mouse leave. Required for the WM_MOUSELEAVE event to + // be generated. + TRACKMOUSEEVENT tme; + tme.cbSize = sizeof(TRACKMOUSEEVENT); + tme.dwFlags = TME_LEAVE; + tme.hwndTrack = hWnd; + TrackMouseEvent(&tme); + mouseTracking = true; + } + if (g_offscreenBrowser.get()) { + g_offscreenBrowser->SendMouseMoveEvent(LOWORD(lParam), HIWORD(lParam), + false); + } + } + break; + + case WM_MOUSELEAVE: + if (mouseTracking) { + // Stop tracking mouse leave. + TRACKMOUSEEVENT tme; + tme.cbSize = sizeof(TRACKMOUSEEVENT); + tme.dwFlags = TME_LEAVE & TME_CANCEL; + tme.hwndTrack = hWnd; + TrackMouseEvent(&tme); + mouseTracking = false; + } + if (g_offscreenBrowser.get()) + g_offscreenBrowser->SendMouseMoveEvent(0, 0, true); + break; + + case WM_MOUSEWHEEL: + if (g_offscreenBrowser.get()) { + g_offscreenBrowser->SendMouseWheelEvent(LOWORD(lParam), HIWORD(lParam), + 0, GET_WHEEL_DELTA_WPARAM(wParam)); + } + break; + + case WM_SIZE: { + int width = LOWORD(lParam); + int height = HIWORD(lParam); + if (width > 0 && height > 0) + SizeGL(plugin, width, height); + break; + } + + case WM_SETFOCUS: + case WM_KILLFOCUS: + if (g_offscreenBrowser.get()) + g_offscreenBrowser->SendFocusEvent(message == WM_SETFOCUS); + break; + + case WM_CAPTURECHANGED: + case WM_CANCELMODE: + if (!mouseRotation) { + if (g_offscreenBrowser.get()) + g_offscreenBrowser->SendCaptureLostEvent(); + } + break; + + case WM_KEYDOWN: + case WM_KEYUP: + case WM_SYSKEYDOWN: + case WM_SYSKEYUP: + case WM_CHAR: + case WM_SYSCHAR: + case WM_IME_CHAR: + if (g_offscreenBrowser.get()) { + CefBrowser::KeyType type = KT_CHAR; + CefKeyInfo keyInfo; + keyInfo.key = wParam; + + if (message == WM_KEYDOWN || message == WM_SYSKEYDOWN) + type = KT_KEYDOWN; + else if (message == WM_KEYUP || message == WM_SYSKEYUP) + type = KT_KEYUP; + + if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP || + message == WM_SYSCHAR) + keyInfo.sysChar = true; + + if (message == WM_IME_CHAR) + keyInfo.imeChar = true; + + g_offscreenBrowser->SendKeyEvent(type, keyInfo, lParam); + } + break; + + case WM_PAINT: { + PAINTSTRUCT ps; + BeginPaint(hWnd, &ps); + EndPaint(hWnd, &ps); + return 0; + } + + case WM_ERASEBKGND: + return 0; + } + + return DefWindowProc(hWnd, message, wParam, lParam); +} + +} // namespace + +NPError API_CALL NP_OSRGetEntryPoints(NPPluginFuncs* pFuncs) { + pFuncs->newp = NPP_NewImpl; + pFuncs->destroy = NPP_DestroyImpl; + pFuncs->setwindow = NPP_SetWindowImpl; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_OSRInitialize(NPNetscapeFuncs* pFuncs) { + g_osrbrowser = pFuncs; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_OSRShutdown(void) { + g_osrbrowser = NULL; + return NPERR_NO_ERROR; +} + +CefRefPtr GetOffScreenBrowser() { + return g_offscreenBrowser; +} + +void SetOffScreenTransparent(bool transparent) { + g_offscreenTransparent = transparent; +} + +#endif // OS_WIN diff --git a/cef1/tests/cefclient/osrplugin.h b/cef1/tests/cefclient/osrplugin.h new file mode 100644 index 000000000..737f089e9 --- /dev/null +++ b/cef1/tests/cefclient/osrplugin.h @@ -0,0 +1,33 @@ +// 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. + +// Portions of this implementation are borrowed from webkit\default_plugin\ +// plugin_impl.h + +#ifndef CEF_TESTS_CEFCLIENT_OSRPLUGIN_H_ +#define CEF_TESTS_CEFCLIENT_OSRPLUGIN_H_ +#pragma once + +#include "include/cef_base.h" + +#if defined(OS_WIN) + +#include "include/cef_nplugin.h" + +class CefBrowser; + +extern NPNetscapeFuncs* g_osrbrowser; + +NPError API_CALL NP_OSRGetEntryPoints(NPPluginFuncs* pFuncs); +NPError API_CALL NP_OSRInitialize(NPNetscapeFuncs* pFuncs); +NPError API_CALL NP_OSRShutdown(void); + +CefRefPtr GetOffScreenBrowser(); + +void SetOffScreenTransparent(bool transparent); + +#endif // OS_WIN + +#endif // CEF_TESTS_CEFCLIENT_OSRPLUGIN_H_ diff --git a/cef1/tests/cefclient/osrplugin_test.cpp b/cef1/tests/cefclient/osrplugin_test.cpp new file mode 100644 index 000000000..fa76e389d --- /dev/null +++ b/cef1/tests/cefclient/osrplugin_test.cpp @@ -0,0 +1,126 @@ +// 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/osrplugin_test.h" +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/osrplugin.h" +#include "cefclient/cefclient.h" +#include "cefclient/client_handler.h" +#include "cefclient/plugin_test.h" + +void InitOSRPluginTest() { + // Structure providing information about the client plugin. + CefPluginInfo plugin_info; + CefString(&plugin_info.display_name).FromASCII("Client OSR Plugin"); + CefString(&plugin_info.unique_name).FromASCII("client_osr_plugin"); + CefString(&plugin_info.description).FromASCII("My Example Client OSR Plugin"); + CefString(&plugin_info.mime_types).FromASCII( + "application/x-client-osr-plugin"); + + plugin_info.np_getentrypoints = NP_OSRGetEntryPoints; + plugin_info.np_initialize = NP_OSRInitialize; + plugin_info.np_shutdown = NP_OSRShutdown; + + // Register the internal client plugin + CefRegisterPlugin(plugin_info); +} + +void RunOSRPluginTest(CefRefPtr browser, bool transparent) { + class Listener : public CefDOMEventListener { + public: + Listener() {} + virtual void HandleEvent(CefRefPtr event) { + CefRefPtr browser = GetOffScreenBrowser(); + + CefRefPtr element = event->GetTarget(); + ASSERT(element.get()); + std::string elementId = element->GetElementAttribute("id"); + + if (elementId == "back") { + browser->GoBack(); + } else if (elementId == "forward") { + browser->GoForward(); + } else if (elementId == "stop") { + browser->Reload(); + } else if (elementId == "reload") { + browser->StopLoad(); + } else if (elementId == "go") { + // Retrieve the value of the "url" field and load it in the off-screen + // browser window. + CefRefPtr document = event->GetDocument(); + ASSERT(document.get()); + CefRefPtr url = document->GetElementById("url"); + ASSERT(url.get()); + CefString value = url->GetValue(); + if (!value.empty()) + browser->GetMainFrame()->LoadURL(value); + } else if (elementId == "testTransparency") { + // Transparency test. + browser->GetMainFrame()->LoadURL( + "http://tests/transparency"); + } else if (elementId == "testWindowlessPlugin") { + // Load flash, which is a windowless plugin. + browser->GetMainFrame()->LoadURL( + "http://www.adobe.com/software/flash/about/"); + } else if (elementId == "viewSource") { + // View the page source for the host browser window. + AppGetBrowser()->GetMainFrame()->ViewSource(); + } else { + // Not reached. + ASSERT(false); + } + } + + IMPLEMENT_REFCOUNTING(Listener); + }; + + class Visitor : public CefDOMVisitor { + public: + Visitor() {} + + void RegisterClickListener(CefRefPtr document, + CefRefPtr listener, + const std::string& elementId) { + CefRefPtr element = document->GetElementById(elementId); + ASSERT(element.get()); + element->AddEventListener("click", listener, false); + } + + virtual void Visit(CefRefPtr document) { + CefRefPtr listener(new Listener()); + + // Register click listeners for the various HTML elements. + RegisterClickListener(document, listener, "back"); + RegisterClickListener(document, listener, "forward"); + RegisterClickListener(document, listener, "stop"); + RegisterClickListener(document, listener, "reload"); + RegisterClickListener(document, listener, "go"); + RegisterClickListener(document, listener, "testTransparency"); + RegisterClickListener(document, listener, "testWindowlessPlugin"); + RegisterClickListener(document, listener, "viewSource"); + } + + IMPLEMENT_REFCOUNTING(Visitor); + }; + + // Center the window on the screen. + int screenX = GetSystemMetrics(SM_CXFULLSCREEN); + int screenY = GetSystemMetrics(SM_CYFULLSCREEN); + int width = 1000, height = 760; + int x = (screenX - width) / 2; + int y = (screenY - height) / 2; + + SetWindowPos(AppGetMainHwnd(), NULL, x, y, width, height, + SWP_NOZORDER | SWP_SHOWWINDOW); + + // The DOM visitor will be called after the path is loaded. + CefRefPtr client = browser->GetClient(); + static_cast(client.get())->AddDOMVisitor( + "http://tests/osrapp", new Visitor()); + + SetOffScreenTransparent(transparent); + browser->GetMainFrame()->LoadURL("http://tests/osrapp"); +} diff --git a/cef1/tests/cefclient/osrplugin_test.h b/cef1/tests/cefclient/osrplugin_test.h new file mode 100644 index 000000000..8681a22cc --- /dev/null +++ b/cef1/tests/cefclient/osrplugin_test.h @@ -0,0 +1,19 @@ +// 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_OSRPLUGIN_TEST_H_ +#define CEF_TESTS_CEFCLIENT_OSRPLUGIN_TEST_H_ +#pragma once + +#include "include/cef_base.h" + +class CefBrowser; + +// Register the internal client plugin and V8 extension. +void InitOSRPluginTest(); + +// Run the test. +void RunOSRPluginTest(CefRefPtr browser, bool transparent); + +#endif // CEF_TESTS_CEFCLIENT_OSRPLUGIN_TEST_H_ diff --git a/cef1/tests/cefclient/osrtest_mac.h b/cef1/tests/cefclient/osrtest_mac.h new file mode 100644 index 000000000..a6e1ee297 --- /dev/null +++ b/cef1/tests/cefclient/osrtest_mac.h @@ -0,0 +1,15 @@ +// 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_OSRTEST_MAC_H_ +#define CEF_TESTS_CEFCLIENT_OSRTEST_MAC_H_ + +namespace osrtest { + +void RunTest(bool transparent); + +} // namespace osrtest + +#endif // CEF_TESTS_CEFCLIENT_OSRTEST_MAC_H_ + diff --git a/cef1/tests/cefclient/osrtest_mac.mm b/cef1/tests/cefclient/osrtest_mac.mm new file mode 100644 index 000000000..8fa8243c4 --- /dev/null +++ b/cef1/tests/cefclient/osrtest_mac.mm @@ -0,0 +1,752 @@ + // 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 +#include + +#include "cefclient/osrtest_mac.h" +#include "include/cef_browser.h" +#include "cefclient/osrenderer.h" +#include "cefclient/client_popup_handler.h" +#include "cefclient/resource_util.h" +#include "cefclient/util.h" + +// The client OpenGL view. +@interface ClientOpenGLView : NSOpenGLView { + @public + NSTrackingArea* tracking_area_; + CefRefPtr browser_; + ClientOSRenderer* renderer_; + NSPoint last_mouse_pos_; + NSPoint cur_mouse_pos_; + bool rotating_; +} + +- (id)initWithFrame:(NSRect)frame andTransparency:(bool)transparency; +- (NSPoint)getClickPointForEvent:(NSEvent*)event; +- (void)getKeyInfo:(CefKeyInfo&)info forEvent:(NSEvent*)event; +- (int)getModifiersForEvent:(NSEvent*)event; +- (BOOL)isKeyUpEvent:(NSEvent*)event; +- (BOOL)isKeyPadEvent:(NSEvent*)event; +@end + + +namespace { + +// Handler for off-screen rendering windows. +class ClientOSRHandler : public CefClient, + public CefLifeSpanHandler, + public CefLoadHandler, + public CefRequestHandler, + public CefDisplayHandler, + public CefRenderHandler { + public: + explicit ClientOSRHandler(ClientOpenGLView* view) + : view_(view) { + } + ~ClientOSRHandler() { + } + + void Disconnect() { + view_ = nil; + } + + // CefClient methods + virtual CefRefPtr GetLifeSpanHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetLoadHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetRequestHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetDisplayHandler() OVERRIDE { + return this; + } + virtual CefRefPtr GetRenderHandler() OVERRIDE { + return this; + } + + // CefLifeSpanHandler methods + + virtual bool OnBeforePopup(CefRefPtr parentBrowser, + const CefPopupFeatures& popupFeatures, + CefWindowInfo& windowInfo, + const CefString& url, + CefRefPtr& client, + CefBrowserSettings& settings) OVERRIDE { + REQUIRE_UI_THREAD(); + + windowInfo.m_bWindowRenderingDisabled = TRUE; + client = new ClientPopupHandler(view_->browser_); + return false; + } + + virtual void OnAfterCreated(CefRefPtr browser) OVERRIDE { + REQUIRE_UI_THREAD(); + + // Set the view size to match the window size. + const NSRect bounds = [view_ bounds]; + browser->SetSize(PET_VIEW, bounds.size.width, bounds.size.height); + + view_->browser_ = browser; + } + + virtual void OnBeforeClose(CefRefPtr browser) OVERRIDE { + if (view_) + view_->browser_ = NULL; + } + + // CefLoadHandler methods + + virtual void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!browser->IsPopup() && frame->IsMain()) { + // We've just started loading a page + SetLoading(true); + } + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!browser->IsPopup() && frame->IsMain()) { + // We've just finished loading a page + SetLoading(false); + } + } + + // CefRequestHandler methods + + virtual bool OnBeforeResourceLoad(CefRefPtr browser, + CefRefPtr request, + CefString& redirectUrl, + CefRefPtr& resourceStream, + CefRefPtr response, + int loadFlags) OVERRIDE { + REQUIRE_IO_THREAD(); + + std::string url = request->GetURL(); + if (url == "http://tests/osrtest") { + // Show the osrtest HTML contents + resourceStream = GetBinaryResourceReader("osrtest.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (url == "http://tests/transparency") { + // Show the osrtest HTML contents + resourceStream = GetBinaryResourceReader("transparency.html"); + response->SetMimeType("text/html"); + response->SetStatus(200); + } else if (strstr(url.c_str(), "/logoball.png") != NULL) { + // Load the "logoball.png" image resource. + resourceStream = GetBinaryResourceReader("logoball.png"); + response->SetMimeType("image/png"); + response->SetStatus(200); + } + + return false; + } + + // CefDisplayHandler methods + + virtual void OnNavStateChange(CefRefPtr browser, + bool canGoBack, + bool canGoForward) OVERRIDE { + REQUIRE_UI_THREAD(); + } + + virtual void OnAddressChange(CefRefPtr browser, + CefRefPtr frame, + const CefString& url) OVERRIDE { + REQUIRE_UI_THREAD(); + } + + virtual void OnTitleChange(CefRefPtr browser, + const CefString& title) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!view_) + return; + + // Set the frame window title bar + NSWindow* window = [view_ window]; + std::string titleStr(title); + NSString* str = [NSString stringWithUTF8String:titleStr.c_str()]; + [window setTitle:str]; + } + + // CefRenderHandler methods + + virtual bool GetViewRect(CefRefPtr browser, + CefRect& rect) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!view_) + return false; + + // The simulated screen and view rectangle are the same. This is necessary + // for popup menus to be located and sized inside the view. + const NSRect bounds = [view_ bounds]; + rect.x = rect.y = 0; + rect.width = bounds.size.width; + rect.height = bounds.size.height; + return true; + } + + virtual bool GetScreenRect(CefRefPtr browser, + CefRect& rect) OVERRIDE { + return GetViewRect(browser, rect); + } + + virtual bool GetScreenPoint(CefRefPtr browser, + int viewX, + int viewY, + int& screenX, + int& screenY) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!view_) + return false; + + // Convert the point from view coordinates to actual screen coordinates. + NSRect bounds = [view_ bounds]; + NSPoint view_pt = {viewX, bounds.size.height - viewY}; + NSPoint window_pt = [view_ convertPoint:view_pt toView:nil]; + NSPoint screen_pt = [[view_ window] convertBaseToScreen:window_pt]; + screenX = screen_pt.x; + screenY = screen_pt.y; + return true; + } + + virtual void OnPopupShow(CefRefPtr browser, + bool show) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!view_) + return; + + view_->renderer_->OnPopupShow(browser, show); + } + + virtual void OnPopupSize(CefRefPtr browser, + const CefRect& rect) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!view_) + return; + + view_->renderer_->OnPopupSize(browser, rect); + } + + virtual void OnPaint(CefRefPtr browser, + PaintElementType type, + const RectList& dirtyRects, + const void* buffer) OVERRIDE { + REQUIRE_UI_THREAD(); + + if (!view_) + return; + + [[view_ openGLContext] makeCurrentContext]; + + view_->renderer_->OnPaint(browser, type, dirtyRects, buffer); + + // Notify the view to redraw the invalidated regions. + { + RectList::const_iterator i = dirtyRects.begin(); + for (; i != dirtyRects.end(); ++i) { + NSRect rect = {{i->x, i->y}, {i->width, i->height}}; + [view_ setNeedsDisplayInRect:rect]; + } + } + } + + virtual void OnCursorChange(CefRefPtr browser, + CefCursorHandle cursor) OVERRIDE { + REQUIRE_UI_THREAD(); + [cursor set]; + } + + private: + void SetLoading(bool isLoading) { + } + + ClientOpenGLView* view_; + + // Include the default reference counting implementation. + IMPLEMENT_REFCOUNTING(ClientOSRPlugin); +}; + +} // namespace + + +@implementation ClientOpenGLView + +- (id)initWithFrame:(NSRect)frame andTransparency:(bool)transparency { + NSOpenGLPixelFormat * pixelFormat = + [[NSOpenGLPixelFormat alloc] + initWithAttributes:(NSOpenGLPixelFormatAttribute[]) { + NSOpenGLPFAWindow, + NSOpenGLPFADoubleBuffer, + NSOpenGLPFADepthSize, + 32, + 0}]; + [pixelFormat autorelease]; + + self = [super initWithFrame:frame pixelFormat:pixelFormat]; + if (self) { + renderer_ = new ClientOSRenderer(transparency); + rotating_ = false; + + tracking_area_ = + [[NSTrackingArea alloc] initWithRect:frame + options:NSTrackingMouseMoved | + NSTrackingActiveInActiveApp | + NSTrackingInVisibleRect + owner:self + userInfo:nil]; + [self addTrackingArea:tracking_area_]; + } + return self; +} + +- (void)dealloc { + if (browser_) { + static_cast(browser_->GetClient().get())->Disconnect(); + browser_->CloseBrowser(); + browser_ = NULL; + } + if (renderer_) + delete renderer_; + + [super dealloc]; +} + +- (void)drawRect: (NSRect)bounds { + NSOpenGLContext* context = [self openGLContext]; + [context makeCurrentContext]; + + renderer_->Render(); + + [context flushBuffer]; +} + +- (void)setFrame:(NSRect)frameRect { + [super setFrame:frameRect]; + + int width = frameRect.size.width; + int height = frameRect.size.height; + + [[self openGLContext] makeCurrentContext]; + + renderer_->SetSize(width, height); + + if (browser_) + browser_->SetSize(PET_VIEW, width, height); +} + +- (void)mouseDown:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + int clickCount = [event clickCount]; + + browser_->SendMouseClickEvent(point.x, point.y, MBT_LEFT, false, clickCount); +} + +- (void)rightMouseDown:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + + if ([event modifierFlags] & NSShiftKeyMask) { + // Start rotation effect. + last_mouse_pos_ = cur_mouse_pos_ = point; + rotating_ = true; + return; + } + + int clickCount = [event clickCount]; + + browser_->SendMouseClickEvent(point.x, point.y, MBT_RIGHT, false, clickCount); +} + +- (void)otherMouseDown:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + int clickCount = [event clickCount]; + + browser_->SendMouseClickEvent(point.x, point.y, MBT_MIDDLE, false, + clickCount); +} + +- (void)mouseUp:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + int clickCount = [event clickCount]; + + browser_->SendMouseClickEvent(point.x, point.y, MBT_LEFT, true, clickCount); +} + +- (void)rightMouseUp:(NSEvent *)event { + if (!browser_) + return; + + if (rotating_) { + // End rotation effect. + renderer_->SetSpin(0, 0); + rotating_ = false; + [self setNeedsDisplay:YES]; + return; + } + + NSPoint point = [self getClickPointForEvent:event]; + int clickCount = [event clickCount]; + + browser_->SendMouseClickEvent(point.x, point.y, MBT_RIGHT, true, clickCount); +} + +- (void)otherMouseUp:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + int clickCount = [event clickCount]; + + browser_->SendMouseClickEvent(point.x, point.y, MBT_MIDDLE, true, clickCount); +} + +- (void)mouseMoved:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + + if (rotating_) { + // Apply rotation effect. + cur_mouse_pos_ = point; + renderer_->IncrementSpin((cur_mouse_pos_.x - last_mouse_pos_.x), + (cur_mouse_pos_.y - last_mouse_pos_.y)); + last_mouse_pos_ = cur_mouse_pos_; + [self setNeedsDisplay:YES]; + return; + } + + browser_->SendMouseMoveEvent(point.x, point.y, false); +} + +- (void)mouseDragged:(NSEvent *)event { + [self mouseMoved:event]; +} + +- (void)rightMouseDragged:(NSEvent *)event { + [self mouseMoved:event]; +} + +- (void)otherMouseDragged:(NSEvent *)event { + [self mouseMoved:event]; +} + +- (void)mouseEntered:(NSEvent *)event { + [self mouseMoved:event]; +} + +- (void)mouseExited:(NSEvent *)event { + if (!browser_) + return; + + NSPoint point = [self getClickPointForEvent:event]; + + browser_->SendMouseMoveEvent(point.x, point.y, true); +} + +- (void)keyDown:(NSEvent *)event { + if (!browser_) + return; + + CefKeyInfo keyInfo; + [self getKeyInfo:keyInfo forEvent:event]; + int modifiers = [self getModifiersForEvent:event]; + + browser_->SendKeyEvent(KT_KEYDOWN, keyInfo, modifiers); + + if ([event modifierFlags] & (NSNumericPadKeyMask | NSFunctionKeyMask)) { + // Don't send a Char event for non-char keys like arrows, function keys and + // clear. + switch (keyInfo.keyCode) { + case 81: // = + case 75: // / + case 67: // * + case 78: // - + case 69: // + + case 76: // Enter + case 65: // . + case 82: // 0 + case 83: // 1 + case 84: // 2 + case 85: // 3 + case 86: // 4 + case 87: // 5 + case 88: // 6 + case 89: // 7 + case 91: // 8 + case 92: // 9 + break; + default: + return; + } + } + + browser_->SendKeyEvent(KT_CHAR, keyInfo, modifiers); +} + +- (void)keyUp:(NSEvent *)event { + if (!browser_) + return; + + CefKeyInfo keyInfo; + [self getKeyInfo:keyInfo forEvent:event]; + int modifiers = [self getModifiersForEvent:event]; + + browser_->SendKeyEvent(KT_KEYUP, keyInfo, modifiers); +} + +- (void)flagsChanged:(NSEvent *)event { + if ([self isKeyUpEvent:event]) + [self keyUp:event]; + else + [self keyDown:event]; +} + +- (void)scrollWheel:(NSEvent *)event { + if (!browser_) + return; + + CGEventRef cgEvent = [event CGEvent]; + ASSERT(cgEvent); + + NSPoint point = [self getClickPointForEvent:event]; + int deltaX = + CGEventGetIntegerValueField(cgEvent, kCGScrollWheelEventPointDeltaAxis2); + int deltaY = + CGEventGetIntegerValueField(cgEvent, kCGScrollWheelEventPointDeltaAxis1); + + browser_->SendMouseWheelEvent(point.x, point.y, deltaX, deltaY); +} + +- (BOOL)canBecomeKeyView { + return (browser_ != NULL); +} + +- (BOOL)acceptsFirstResponder { + return (browser_ != NULL); +} + +- (BOOL)becomeFirstResponder { + if (browser_) { + browser_->SendFocusEvent(true); + return [super becomeFirstResponder]; + } + + return NO; +} + +- (BOOL)resignFirstResponder { + if (browser_) { + browser_->SendFocusEvent(false); + return [super resignFirstResponder]; + } + + return NO; +} + +- (void)undo:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Undo(); +} + +- (void)redo:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Redo(); +} + +- (void)cut:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Cut(); +} + +- (void)copy:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Copy(); +} + +- (void)paste:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Paste(); +} + +- (void)delete:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->Delete(); +} + +- (void)selectAll:(id)sender { + if (browser_) + browser_->GetFocusedFrame()->SelectAll(); +} + +- (NSPoint)getClickPointForEvent:(NSEvent*)event { + NSPoint windowLocal = [event locationInWindow]; + NSPoint contentLocal = [self convertPoint:windowLocal fromView:nil]; + int x = contentLocal.x; + int y = [self frame].size.height - contentLocal.y; // Flip y. + + return {x,y}; +} + +- (void)getKeyInfo:(CefKeyInfo&)info forEvent:(NSEvent*)event { + if ([event type] == NSKeyDown || [event type] == NSKeyUp) { + NSString* s = [event characters]; + if ([s length] > 0) + info.character = [s characterAtIndex:0]; + + s = [event charactersIgnoringModifiers]; + if ([s length] > 0) + info.characterNoModifiers = [s characterAtIndex:0]; + } + + info.keyCode = [event keyCode]; +} + +- (int)getModifiersForEvent:(NSEvent*)event { + int modifiers = 0; + + if ([event modifierFlags] & NSControlKeyMask) + modifiers |= KEY_CTRL; + if ([event modifierFlags] & NSShiftKeyMask) + modifiers |= KEY_SHIFT; + if ([event modifierFlags] & NSAlternateKeyMask) + modifiers |= KEY_ALT; + if ([event modifierFlags] & NSCommandKeyMask) + modifiers |= KEY_META; + if ([self isKeyPadEvent:event]) + modifiers |= KEY_KEYPAD; + + return modifiers; +} + +- (BOOL)isKeyUpEvent:(NSEvent*)event { + if ([event type] != NSFlagsChanged) + return [event type] == NSKeyUp; + + // FIXME: This logic fails if the user presses both Shift keys at once, for + // example: we treat releasing one of them as keyDown. + switch ([event keyCode]) { + case 54: // Right Command + case 55: // Left Command + return ([event modifierFlags] & NSCommandKeyMask) == 0; + + case 57: // Capslock + return ([event modifierFlags] & NSAlphaShiftKeyMask) == 0; + + case 56: // Left Shift + case 60: // Right Shift + return ([event modifierFlags] & NSShiftKeyMask) == 0; + + case 58: // Left Alt + case 61: // Right Alt + return ([event modifierFlags] & NSAlternateKeyMask) == 0; + + case 59: // Left Ctrl + case 62: // Right Ctrl + return ([event modifierFlags] & NSControlKeyMask) == 0; + + case 63: // Function + return ([event modifierFlags] & NSFunctionKeyMask) == 0; + } + return false; +} + +- (BOOL)isKeyPadEvent:(NSEvent*)event { + if ([event modifierFlags] & NSNumericPadKeyMask) + return true; + + switch ([event keyCode]) { + case 71: // Clear + case 81: // = + case 75: // / + case 67: // * + case 78: // - + case 69: // + + case 76: // Enter + case 65: // . + case 82: // 0 + case 83: // 1 + case 84: // 2 + case 85: // 3 + case 86: // 4 + case 87: // 5 + case 88: // 6 + case 89: // 7 + case 91: // 8 + case 92: // 9 + return true; + } + + return false; +} + +@end + + +namespace osrtest { + +void RunTest(bool transparent) { + NSRect screen_rect = [[NSScreen mainScreen] visibleFrame]; + NSRect window_rect = {{0, screen_rect.size.height}, {700, 700}}; + NSWindow* newWnd = [[NSWindow alloc] + initWithContentRect:window_rect + styleMask:(NSTitledWindowMask | + NSClosableWindowMask | + NSMiniaturizableWindowMask | + NSResizableWindowMask | + NSUnifiedTitleAndToolbarWindowMask) + backing:NSBackingStoreBuffered + defer:NO]; + ASSERT(newWnd); + + ClientOpenGLView* view = [[ClientOpenGLView alloc] initWithFrame:window_rect + andTransparency:transparent]; + [view setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)]; + + [newWnd setContentView:view]; + [view release]; + + CefWindowInfo info; + CefBrowserSettings settings; + + // Initialize the window info as off-screen. + info.SetAsOffScreen(view); + info.SetTransparentPainting(transparent); + + // Creat the browser window. + CefBrowser::CreateBrowser(info, new ClientOSRHandler(view), + "http://tests/osrtest", settings); + + [newWnd makeKeyAndOrderFront: nil]; +} + +} // namespace osrtest + diff --git a/cef1/tests/cefclient/plugin_test.cpp b/cef1/tests/cefclient/plugin_test.cpp new file mode 100644 index 000000000..4bb3e00b9 --- /dev/null +++ b/cef1/tests/cefclient/plugin_test.cpp @@ -0,0 +1,31 @@ +// 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/cef_base.h" +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_nplugin.h" +#include "cefclient/clientplugin.h" + +void InitPluginTest() { + // Structure providing information about the client plugin. + CefPluginInfo plugin_info; + CefString(&plugin_info.display_name).FromASCII("Client Plugin"); + CefString(&plugin_info.unique_name).FromASCII("client_plugin"); + CefString(&plugin_info.description).FromASCII("My Example Client Plugin"); + CefString(&plugin_info.mime_types).FromASCII("application/x-client-plugin"); + CefString(&plugin_info.file_extensions).FromASCII("xcp"); + + plugin_info.np_getentrypoints = NP_ClientGetEntryPoints; + plugin_info.np_initialize = NP_ClientInitialize; + plugin_info.np_shutdown = NP_ClientShutdown; + + // Register the internal client plugin + CefRegisterPlugin(plugin_info); +} + +void RunPluginTest(CefRefPtr browser) { + // Page content is provided in ClientHandler::OnBeforeResourceLoad(). + browser->GetMainFrame()->LoadURL("http://tests/plugin"); +} diff --git a/cef1/tests/cefclient/plugin_test.h b/cef1/tests/cefclient/plugin_test.h new file mode 100644 index 000000000..26133d9f9 --- /dev/null +++ b/cef1/tests/cefclient/plugin_test.h @@ -0,0 +1,19 @@ +// 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_PLUGIN_TEST_H_ +#define CEF_TESTS_CEFCLIENT_PLUGIN_TEST_H_ +#pragma once + +#include "include/cef_base.h" + +class CefBrowser; + +// Register the internal client plugin. +void InitPluginTest(); + +// Run the test. +void RunPluginTest(CefRefPtr browser); + +#endif // CEF_TESTS_CEFCLIENT_PLUGIN_TEST_H_ diff --git a/cef1/tests/cefclient/res/cefclient.ico b/cef1/tests/cefclient/res/cefclient.ico new file mode 100644 index 000000000..d551aa3aa Binary files /dev/null and b/cef1/tests/cefclient/res/cefclient.ico differ diff --git a/cef1/tests/cefclient/res/domaccess.html b/cef1/tests/cefclient/res/domaccess.html new file mode 100644 index 000000000..68ff69647 --- /dev/null +++ b/cef1/tests/cefclient/res/domaccess.html @@ -0,0 +1,13 @@ + + +

Select some portion of the below page content and click the "Describe Selection" button. The selected region will then be described below.

+

This is p1

+

This is p2

+

This is p3

+

This is p4

+
+ +

The description will appear here.

+
+ + diff --git a/cef1/tests/cefclient/res/extensionperf.html b/cef1/tests/cefclient/res/extensionperf.html new file mode 100644 index 000000000..5ac6e7925 --- /dev/null +++ b/cef1/tests/cefclient/res/extensionperf.html @@ -0,0 +1,131 @@ + + + + JavaScript Extension: Performance + + + +

JavaScript Extension: Performance

+ +
+ +
+ + + + + + + + + + + +
NameMinAvgMaxProbes
+
+ + + + + diff --git a/cef1/tests/cefclient/res/localstorage.html b/cef1/tests/cefclient/res/localstorage.html new file mode 100644 index 000000000..a794305b7 --- /dev/null +++ b/cef1/tests/cefclient/res/localstorage.html @@ -0,0 +1,24 @@ + + + +Click the "Add Line" button to add a line or the "Clear" button to clear.
+This data will persist across sessions if a cache path was specified.
+ + +
+ + + diff --git a/cef1/tests/cefclient/res/logo.png b/cef1/tests/cefclient/res/logo.png new file mode 100644 index 000000000..41dd728df Binary files /dev/null and b/cef1/tests/cefclient/res/logo.png differ diff --git a/cef1/tests/cefclient/res/logoball.png b/cef1/tests/cefclient/res/logoball.png new file mode 100644 index 000000000..ef115ca07 Binary files /dev/null and b/cef1/tests/cefclient/res/logoball.png differ diff --git a/cef1/tests/cefclient/res/modaldialog.html b/cef1/tests/cefclient/res/modaldialog.html new file mode 100644 index 000000000..07e05cf36 --- /dev/null +++ b/cef1/tests/cefclient/res/modaldialog.html @@ -0,0 +1,78 @@ + + + + A Modal Dialog + + +Argument:
+
+Reply:
+

+ +

+

+ + + diff --git a/cef1/tests/cefclient/res/modalmain.html b/cef1/tests/cefclient/res/modalmain.html new file mode 100644 index 000000000..44a060507 --- /dev/null +++ b/cef1/tests/cefclient/res/modalmain.html @@ -0,0 +1,58 @@ + + + +Test Modal Dialog + + + +

Tests

+
+ + +

Time (timers are suppresed while the modal dialog is open)

+
+ +

Result Log

+
+ + + + + diff --git a/cef1/tests/cefclient/res/osrplugin.html b/cef1/tests/cefclient/res/osrplugin.html new file mode 100644 index 000000000..0115ee7e6 --- /dev/null +++ b/cef1/tests/cefclient/res/osrplugin.html @@ -0,0 +1,54 @@ + + +Off-Screen Rendering App Example + + +
+ + + + +
+ + + + + + + + + + + + + + +
Off-Screen Rendering App Example
An embedded OpenGL plugin window that renders content from an off-screen browser window. + View Page Source
You can rotate the view! +
    +
  • Click and drag the view with the left mouse button while holding the shift key.
  • +
  • Enter a URL and click the "Go!" button to browse to a new Website.
  • +
  • Click here to test transparency.
  • +
  • Click here to test a windowless plugin.
  • +
+
+ +
+   +
+ + + + + +
+
+ +
+
+ Pixel value: Click the left mouse button while holding the control key to test a pixel value. +
+
+
+ + diff --git a/cef1/tests/cefclient/res/osrtest.html b/cef1/tests/cefclient/res/osrtest.html new file mode 100644 index 000000000..c3fdc2eee --- /dev/null +++ b/cef1/tests/cefclient/res/osrtest.html @@ -0,0 +1,40 @@ + + +Off-Screen Rendering Test + + +
+ + + + + + + + + + + + + + + + + +
Off-Screen Rendering App Example
An OpenGL view that renders content from an off-screen browser window.
You can rotate the view! +
    +
  • Click and drag the view with the left mouse button while holding the shift key.
  • +
  • Enter a URL and click the "Go!" button to browse to a new Website.
  • +
  • Click here to test transparency.
  • +
  • Click here to test a windowless plugin.
  • +
+
+
+ + +
+
+
+ + + diff --git a/cef1/tests/cefclient/res/small.ico b/cef1/tests/cefclient/res/small.ico new file mode 100644 index 000000000..d551aa3aa Binary files /dev/null and b/cef1/tests/cefclient/res/small.ico differ diff --git a/cef1/tests/cefclient/res/transparency.html b/cef1/tests/cefclient/res/transparency.html new file mode 100644 index 000000000..a8dd3b46e --- /dev/null +++ b/cef1/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/cef1/tests/cefclient/res/uiplugin.html b/cef1/tests/cefclient/res/uiplugin.html new file mode 100644 index 000000000..8d982db0b --- /dev/null +++ b/cef1/tests/cefclient/res/uiplugin.html @@ -0,0 +1,57 @@ + + +User Interface App Example + + +
+ + + + +
+ + + + + + + + + + + + + + +
User Interface App Example
An embedded OpenGL plugin window that communicates with the Chromium browser control via JavaScript calls. + View Page Source
You can make the square rotate! +
    +
  • Click the square with the left mouse button or click the Decrement Rotation button to decrement the rotation value.
  • +
  • Click the square with the right mouse button or click the Increment Rotation button to increment the rotation value.
  • +
  • Click the Reset Rotation button to reset the rotation value to zero.
  • +
+
+ +
+ +
+ +
+ Rotation Value: +
+ + +
+
+
+ + + diff --git a/cef1/tests/cefclient/res/xmlhttprequest.html b/cef1/tests/cefclient/res/xmlhttprequest.html new file mode 100644 index 000000000..638c63c82 --- /dev/null +++ b/cef1/tests/cefclient/res/xmlhttprequest.html @@ -0,0 +1,19 @@ + + + +
+URL: +
+
+
+ + diff --git a/cef1/tests/cefclient/resource.h b/cef1/tests/cefclient/resource.h new file mode 100644 index 000000000..725f12b88 --- /dev/null +++ b/cef1/tests/cefclient/resource.h @@ -0,0 +1,87 @@ +// 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. + +//{{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 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_WARN_CONSOLEMESSAGE 32000 +#define ID_WARN_DOWNLOADCOMPLETE 32001 +#define ID_WARN_DOWNLOADERROR 32002 +#define ID_FIND 32101 +#define ID_PRINT 32102 +#define ID_TESTS_GETSOURCE 32769 +#define ID_TESTS_GETTEXT 32770 +#define ID_TESTS_JAVASCRIPT_BINDING 32771 +#define ID_TESTS_JAVASCRIPT_EXTENSION 32772 +#define ID_TESTS_JAVASCRIPT_EXECUTE 32773 +#define ID_TESTS_PLUGIN 32774 +#define ID_TESTS_POPUP 32775 +#define ID_TESTS_REQUEST 32776 +#define ID_TESTS_SCHEME_HANDLER 32777 +#define ID_TESTS_UIAPP 32778 +#define ID_TESTS_LOCALSTORAGE 32779 +#define ID_TESTS_ACCELERATED2DCANVAS 32780 +#define ID_TESTS_ACCELERATEDLAYERS 32781 +#define ID_TESTS_WEBGL 32782 +#define ID_TESTS_HTML5VIDEO 32783 +#define ID_TESTS_XMLHTTPREQUEST 32784 +#define ID_TESTS_ZOOM_IN 32785 +#define ID_TESTS_ZOOM_OUT 32786 +#define ID_TESTS_ZOOM_RESET 32787 +#define ID_TESTS_DEVTOOLS_SHOW 32788 +#define ID_TESTS_DEVTOOLS_CLOSE 32789 +#define ID_TESTS_WEBURLREQUEST 32790 +#define ID_TESTS_DOMACCESS 32791 +#define ID_TESTS_DRAGDROP 32792 +#define ID_TESTS_OSRAPP 32793 +#define ID_TESTS_MODALDIALOG 32794 +#define ID_TESTS_JAVASCRIPT_PERFORMANCE 32795 +#define ID_TESTS_TRANSPARENT_POPUP 32796 +#define ID_TESTS_TRANSPARENT_OSRAPP 32797 +#define ID_TESTS_JAVASCRIPT_INVOKE 32798 +#define ID_TESTS_GETIMAGE 32799 +#define ID_TESTS_PLUGIN_INFO 32800 +#define IDC_STATIC -1 +#define IDS_LOGO 1000 +#define IDS_UIPLUGIN 1001 +#define IDS_LOGOBALL 1002 +#define IDS_LOCALSTORAGE 1003 +#define IDS_XMLHTTPREQUEST 1004 +#define IDS_DOMACCESS 1005 +#define IDS_OSRPLUGIN 1006 +#define IDS_MODALMAIN 1007 +#define IDS_MODALDIALOG 1008 +#define IDS_EXTENSIONPERF 1009 +#define IDS_TRANSPARENCY 1010 + +// 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 130 +#define _APS_NEXT_COMMAND_VALUE 32795 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 110 +#endif +#endif diff --git a/cef1/tests/cefclient/resource_util.h b/cef1/tests/cefclient/resource_util.h new file mode 100644 index 000000000..ad8cf5a36 --- /dev/null +++ b/cef1/tests/cefclient/resource_util.h @@ -0,0 +1,31 @@ +// 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_RESOURCE_UTIL_H_ +#define CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_ +#pragma once + +#include "include/cef_base.h" + +class CefStreamReader; + +#if defined(OS_WIN) + +#include "cefclient/resource.h" + +// Load a resource of type BINARY +bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes); +CefRefPtr GetBinaryResourceReader(int binaryId); + +#elif defined(OS_MACOSX) || defined(OS_POSIX) + +#include // NOLINT(build/include_order) + +// Load the resource with the specified name. +bool LoadBinaryResource(const char* resource_name, std::string& resource_data); +CefRefPtr GetBinaryResourceReader(const char* resource_name); + +#endif + +#endif // CEF_TESTS_CEFCLIENT_RESOURCE_UTIL_H_ diff --git a/cef1/tests/cefclient/resource_util_linux.cpp b/cef1/tests/cefclient/resource_util_linux.cpp new file mode 100644 index 000000000..66b46267d --- /dev/null +++ b/cef1/tests/cefclient/resource_util_linux.cpp @@ -0,0 +1,67 @@ +// 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. + +#include "cefclient/resource_util.h" +#include +#include +#include "include/cef_stream.h" +#include "cefclient/util.h" + +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; +} + +bool LoadBinaryResource(const char* resource_name, std::string& resource_data) { + std::string path; + if (!GetResourceDir(path)) + return false; + + path.append("/"); + path.append(resource_name); + + FILE* f = fopen(path.c_str(), "rb"); + if (!f) + return false; + + size_t bytes_read; + char buff[1024*8]; + + do { + bytes_read = fread(buff, 1, sizeof(buff)-1, f); + if (bytes_read > 0) + resource_data.append(buff, bytes_read); + } while (bytes_read > 0); + + fclose(f); + return true; +} + +CefRefPtr GetBinaryResourceReader(const char* resource_name) { + std::string path; + if (!GetResourceDir(path)) + return NULL; + + path.append("/"); + path.append(resource_name); + + return CefStreamReader::CreateForFile(path); +} diff --git a/cef1/tests/cefclient/resource_util_mac.mm b/cef1/tests/cefclient/resource_util_mac.mm new file mode 100644 index 000000000..98cfd8605 --- /dev/null +++ b/cef1/tests/cefclient/resource_util_mac.mm @@ -0,0 +1,97 @@ +// 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 +#include +#include +#include "cefclient/resource_util.h" +#include "include/cef_stream.h" +#include "cefclient/util.h" + +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) { + ASSERT(false); + return false; + } + + FSCatalogInfo info; + OSErr fsErr; + if ((fsErr = FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info, + NULL, NULL, NULL)) != noErr) { + ASSERT(false); + return false; + } + + return (info.nodeFlags & kFSNodeIsDirectoryMask); +} + +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 + ASSERT(false); + 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); + + return CefStreamReader::CreateForFile(path); +} diff --git a/cef1/tests/cefclient/resource_util_win.cpp b/cef1/tests/cefclient/resource_util_win.cpp new file mode 100644 index 000000000..a58806ca0 --- /dev/null +++ b/cef1/tests/cefclient/resource_util_win.cpp @@ -0,0 +1,40 @@ +// 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 "cefclient/resource_util.h" +#include "include/cef_stream.h" +#include "include/wrapper/cef_byte_read_handler.h" + +#if defined(OS_WIN) + +bool LoadBinaryResource(int binaryId, DWORD &dwSize, LPBYTE &pBytes) { + extern HINSTANCE hInst; + 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; +} + +CefRefPtr GetBinaryResourceReader(int binaryId) { + DWORD dwSize; + LPBYTE pBytes; + + if (LoadBinaryResource(binaryId, dwSize, pBytes)) { + return CefStreamReader::CreateForHandler( + new CefByteReadHandler(pBytes, dwSize, NULL)); + } + + return NULL; +} + +#endif // OS_WIN diff --git a/cef1/tests/cefclient/scheme_test.cpp b/cef1/tests/cefclient/scheme_test.cpp new file mode 100644 index 000000000..3f06dc040 --- /dev/null +++ b/cef1/tests/cefclient/scheme_test.cpp @@ -0,0 +1,168 @@ +// 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/scheme_test.h" +#include +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_response.h" +#include "include/cef_request.h" +#include "include/cef_scheme.h" +#include "cefclient/resource_util.h" +#include "cefclient/string_util.h" +#include "cefclient/util.h" + +#if defined(OS_WIN) +#include "cefclient/resource.h" +#endif + + +// Implementation of the schema handler for client:// requests. +class ClientSchemeHandler : public CefSchemeHandler { + public: + ClientSchemeHandler() : offset_(0) {} + + virtual bool ProcessRequest(CefRefPtr request, + CefRefPtr callback) + OVERRIDE { + REQUIRE_IO_THREAD(); + + bool handled = false; + + AutoLock lock_scope(this); + + 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;
+      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(), "client.png") != NULL) { + // Load the response image +#if defined(OS_WIN) + DWORD dwSize; + LPBYTE pBytes; + if (LoadBinaryResource(IDS_LOGO, dwSize, pBytes)) { + data_ = std::string(reinterpret_cast(pBytes), dwSize); + handled = true; + // Set the resulting mime type + mime_type_ = "image/jpg"; + } +#elif defined(OS_MACOSX) || defined(OS_LINUX) + if (LoadBinaryResource("logo.png", data_)) { + handled = true; + // Set the resulting mime type + mime_type_ = "image/png"; + } +#else +#error "Unsupported platform" +#endif + } + + if (handled) { + // Indicate the headers are available. + callback->HeadersAvailable(); + return true; + } + + return false; + } + + virtual void GetResponseHeaders(CefRefPtr response, + int64& response_length, + CefString& redirectUrl) OVERRIDE { + REQUIRE_IO_THREAD(); + + ASSERT(!data_.empty()); + + response->SetMimeType(mime_type_); + response->SetStatus(200); + + // Set the resulting response length + response_length = data_.length(); + } + + virtual void Cancel() OVERRIDE { + REQUIRE_IO_THREAD(); + } + + virtual bool ReadResponse(void* data_out, + int bytes_to_read, + int& bytes_read, + CefRefPtr callback) + OVERRIDE { + REQUIRE_IO_THREAD(); + + bool has_data = false; + bytes_read = 0; + + AutoLock lock_scope(this); + + 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); + IMPLEMENT_LOCKING(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, + const CefString& scheme_name, + CefRefPtr request) + OVERRIDE { + REQUIRE_IO_THREAD(); + return new ClientSchemeHandler(); + } + + IMPLEMENT_REFCOUNTING(ClientSchemeHandlerFactory); +}; + +void InitSchemeTest() { + CefRegisterCustomScheme("client", true, false, false); + CefRegisterSchemeHandlerFactory("client", "tests", + new ClientSchemeHandlerFactory()); +} + +void RunSchemeTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("client://tests/handler.html"); +} diff --git a/cef1/tests/cefclient/scheme_test.h b/cef1/tests/cefclient/scheme_test.h new file mode 100644 index 000000000..396cf7973 --- /dev/null +++ b/cef1/tests/cefclient/scheme_test.h @@ -0,0 +1,19 @@ +// 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/cef_base.h" + +class CefBrowser; + +// Register the scheme handler. +void InitSchemeTest(); + +// Run the test. +void RunSchemeTest(CefRefPtr browser); + +#endif // CEF_TESTS_CEFCLIENT_SCHEME_TEST_H_ diff --git a/cef1/tests/cefclient/string_util.cpp b/cef1/tests/cefclient/string_util.cpp new file mode 100644 index 000000000..ebeca5c03 --- /dev/null +++ b/cef1/tests/cefclient/string_util.cpp @@ -0,0 +1,74 @@ +// 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 "cefclient/string_util.h" +#include +#include +#include "include/cef_request.h" + +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(); +} + +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; +} diff --git a/cef1/tests/cefclient/string_util.h b/cef1/tests/cefclient/string_util.h new file mode 100644 index 000000000..c43e6f210 --- /dev/null +++ b/cef1/tests/cefclient/string_util.h @@ -0,0 +1,21 @@ +// 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_TESTS_CEFCLIENT_STRING_UTIL_H_ +#define CEF_TESTS_CEFCLIENT_STRING_UTIL_H_ +#pragma once + +#include +#include "include/cef_base.h" + +class CefRequest; + +// Dump the contents of the request into a string. +void DumpRequestContents(CefRefPtr request, std::string& str); + +// Replace all instances of |from| with |to| in |str|. +std::string StringReplace(const std::string& str, const std::string& from, + const std::string& to); + +#endif // CEF_TESTS_CEFCLIENT_STRING_UTIL_H_ diff --git a/cef1/tests/cefclient/uiplugin.cpp b/cef1/tests/cefclient/uiplugin.cpp new file mode 100644 index 000000000..7558defa3 --- /dev/null +++ b/cef1/tests/cefclient/uiplugin.cpp @@ -0,0 +1,288 @@ +// Copyright (c) 2009 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. + +#include "cefclient/uiplugin.h" + +#if defined(OS_WIN) + +#include +#include +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "cefclient/cefclient.h" + +// Initialized in NP_Initialize. +NPNetscapeFuncs* g_uibrowser = NULL; + +namespace { + +// Global values. +float g_rotationspeed = 0.0f; +float g_theta = 0.0f; + +// Class holding pointers for the client plugin window. +class ClientPlugin { + public: + ClientPlugin() { + hWnd = NULL; + hDC = NULL; + hRC = NULL; + } + + HWND hWnd; + HDC hDC; + HGLRC hRC; +}; + +// Forward declarations of functions included in this code module: +LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam); +void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC); +void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC); + +NPError NPP_NewImpl(NPMIMEType plugin_type, NPP instance, uint16 mode, + int16 argc, char* argn[], char* argv[], + NPSavedData* saved) { + if (instance == NULL) + return NPERR_INVALID_INSTANCE_ERROR; + + ClientPlugin* plugin = new ClientPlugin; + instance->pdata = reinterpret_cast(plugin); + + return NPERR_NO_ERROR; +} + +NPError NPP_DestroyImpl(NPP instance, NPSavedData** save) { + ClientPlugin* plugin = reinterpret_cast(instance->pdata); + + if (plugin) { + if (plugin->hWnd) { + DestroyWindow(plugin->hWnd); + DisableOpenGL(plugin->hWnd, plugin->hDC, plugin->hRC); + } + delete plugin; + g_rotationspeed = 0.0f; + g_theta = 0.0f; + } + + return NPERR_NO_ERROR; +} + +NPError NPP_SetWindowImpl(NPP instance, NPWindow* window_info) { + if (instance == NULL) + return NPERR_INVALID_INSTANCE_ERROR; + + if (window_info == NULL) + return NPERR_GENERIC_ERROR; + + ClientPlugin* plugin = reinterpret_cast(instance->pdata); + HWND parent_hwnd = reinterpret_cast(window_info->window); + + if (plugin->hWnd == NULL) { + WNDCLASS wc; + HINSTANCE hInstance = GetModuleHandle(NULL); + + // Register the window class. + wc.style = CS_OWNDC; + wc.lpfnWndProc = PluginWndProc; + wc.cbClsExtra = 0; + wc.cbWndExtra = 0; + wc.hInstance = hInstance; + wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); + wc.hCursor = LoadCursor(NULL, IDC_ARROW); + wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); + wc.lpszMenuName = NULL; + wc.lpszClassName = L"ClientUIPlugin"; + RegisterClass(&wc); + + // Create the main window. + plugin->hWnd = CreateWindow(L"ClientUIPlugin", L"Client UI Plugin", + WS_CHILD, 0, 0, 0, 0, parent_hwnd, NULL, hInstance, NULL); + + SetWindowLongPtr(plugin->hWnd, GWLP_USERDATA, + reinterpret_cast(plugin)); + + // Enable OpenGL drawing for the window. + EnableOpenGL(plugin->hWnd, &(plugin->hDC), &(plugin->hRC)); + } + + // Position the window and make sure it's visible. + RECT parent_rect; + GetClientRect(parent_hwnd, &parent_rect); + SetWindowPos(plugin->hWnd, NULL, parent_rect.left, parent_rect.top, + parent_rect.right - parent_rect.left, + parent_rect.bottom - parent_rect.top, SWP_SHOWWINDOW); + + UpdateWindow(plugin->hWnd); + ShowWindow(plugin->hWnd, SW_SHOW); + + return NPERR_NO_ERROR; +} + +// Send the notification to the browser as a JavaScript function call. +static void NotifyNewRotation(float value) { + std::stringstream buf; + buf << "notifyNewRotation(" << value << ");"; + AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(buf.str(), CefString(), + 0); +} + +// Nice little fly polygon borrowed from the OpenGL Red Book. +const GLubyte fly[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60, + 0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20, + 0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20, + 0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22, + 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, + 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, + 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, + 0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC, + 0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30, + 0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0, + 0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0, + 0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30, + 0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08, + 0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08, + 0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08}; + + +// Plugin window procedure. +LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam, + LPARAM lParam) { + ClientPlugin* plugin = + reinterpret_cast(GetWindowLongPtr(hWnd, GWLP_USERDATA)); + + switch (message) { + case WM_CREATE: + // Start the timer that's used for redrawing. + SetTimer(hWnd, 1, 1, NULL); + return 0; + + case WM_DESTROY: + // Stop the timer that's used for redrawing. + KillTimer(hWnd, 1); + return 0; + + case WM_LBUTTONDOWN: + // Decrement rotation speed. + ModifyRotation(-2.0f); + return 0; + + case WM_RBUTTONDOWN: + // Increment rotation speed. + ModifyRotation(2.0f); + return 0; + + case WM_SIZE: + if (plugin) { + // Resize the OpenGL viewport to match the window size. + int width = LOWORD(lParam); + int height = HIWORD(lParam); + + wglMakeCurrent(plugin->hDC, plugin->hRC); + glViewport(0, 0, width, height); + } + break; + + case WM_ERASEBKGND: + return 0; + + case WM_TIMER: + wglMakeCurrent(plugin->hDC, plugin->hRC); + + // Adjust the theta value and redraw the display when the timer fires. + glClearColor(1.0f, 1.0f, 1.0f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); + + glPushMatrix(); + glEnable(GL_POLYGON_STIPPLE); + glPolygonStipple(fly); + + glRotatef(g_theta, 0.0f, 0.0f, 1.0f); + glBegin(GL_QUADS); + glColor3f(1.0f, 0.0f, 0.0f); + glVertex2f(0.7f, 0.7f); + glColor3f(0.0f, 1.0f, 0.0f); + glVertex2f(0.7f, -0.7f); + glColor3f(0.0f, 0.0f, 1.0f); + glVertex2f(-0.7f, -0.7f); + glColor3f(1.0f, 0.0f, 1.0f); + glVertex2f(-0.7f, 0.7f); + glEnd(); + + glDisable(GL_POLYGON_STIPPLE); + glPopMatrix(); + + SwapBuffers(plugin->hDC); + + g_theta -= g_rotationspeed; + } + + return DefWindowProc(hWnd, message, wParam, lParam); +} + +// Enable OpenGL. +void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC) { + PIXELFORMATDESCRIPTOR pfd; + int format; + + // Get the device context. + *hDC = GetDC(hWnd); + + // Set the pixel format for the DC. + ZeroMemory(&pfd, sizeof(pfd)); + pfd.nSize = sizeof(pfd); + pfd.nVersion = 1; + pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; + pfd.iPixelType = PFD_TYPE_RGBA; + pfd.cColorBits = 24; + pfd.cDepthBits = 16; + pfd.iLayerType = PFD_MAIN_PLANE; + format = ChoosePixelFormat(*hDC, &pfd); + SetPixelFormat(*hDC, format, &pfd); + + // Create and enable the render contex. + *hRC = wglCreateContext(*hDC); +} + +// Disable OpenGL. +void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) { + wglMakeCurrent(NULL, NULL); + wglDeleteContext(hRC); + ReleaseDC(hWnd, hDC); +} + +} // namespace + +NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs) { + pFuncs->newp = NPP_NewImpl; + pFuncs->destroy = NPP_DestroyImpl; + pFuncs->setwindow = NPP_SetWindowImpl; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_UIInitialize(NPNetscapeFuncs* pFuncs) { + g_uibrowser = pFuncs; + return NPERR_NO_ERROR; +} + +NPError API_CALL NP_UIShutdown(void) { + g_uibrowser = NULL; + return NPERR_NO_ERROR; +} + +void ModifyRotation(float value) { + g_rotationspeed += value; + NotifyNewRotation(g_rotationspeed); +} + +void ResetRotation() { + g_rotationspeed = 0.0; + NotifyNewRotation(g_rotationspeed); +} + +#endif // OS_WIN diff --git a/cef1/tests/cefclient/uiplugin.h b/cef1/tests/cefclient/uiplugin.h new file mode 100644 index 000000000..2ab18ca67 --- /dev/null +++ b/cef1/tests/cefclient/uiplugin.h @@ -0,0 +1,30 @@ +// Copyright (c) 2009 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. + +// Portions of this implementation are borrowed from webkit\default_plugin\ +// plugin_impl.h + +#ifndef CEF_TESTS_CEFCLIENT_UIPLUGIN_H_ +#define CEF_TESTS_CEFCLIENT_UIPLUGIN_H_ +#pragma once + +#include "include/cef_nplugin.h" + +#if defined(OS_WIN) + +extern NPNetscapeFuncs* g_uibrowser; + +NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs); +NPError API_CALL NP_UIInitialize(NPNetscapeFuncs* pFuncs); +NPError API_CALL NP_UIShutdown(void); + +// Function called to modify the rotation value. +void ModifyRotation(float value); +// Function called to reset the rotation value. +void ResetRotation(); + +#endif // OS_WIN + +#endif // CEF_TESTS_CEFCLIENT_UIPLUGIN_H_ diff --git a/cef1/tests/cefclient/uiplugin_test.cpp b/cef1/tests/cefclient/uiplugin_test.cpp new file mode 100644 index 000000000..61e1e6f08 --- /dev/null +++ b/cef1/tests/cefclient/uiplugin_test.cpp @@ -0,0 +1,103 @@ +// 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 "cefclient/uiplugin_test.h" +#include +#include "include/cef_browser.h" +#include "include/cef_frame.h" +#include "include/cef_v8.h" +#include "cefclient/uiplugin.h" +#include "cefclient/cefclient.h" + + +// Implementation of the V8 handler class for the "window.uiapp" functions. +class ClientV8UIHandler : public CefV8Handler { + public: + ClientV8UIHandler() {} + + // Execute with the specified argument list and return value. Return true if + // the method was handled. + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) { + if (name == "modifyRotation") { + // This function requires one argument. + if (arguments.size() != 1) + return false; + + float increment = 0.; + if (arguments[0]->IsInt()) { + // The argument is an integer value. + increment = static_cast(arguments[0]->GetIntValue()); + } else if (arguments[0]->IsDouble()) { + // The argument is an double value. + increment = static_cast(arguments[0]->GetDoubleValue()); + } + + if (increment != 0.) { + // Modify the rotation accordingly. + ModifyRotation(increment); + return true; + } + } else if (name == "resetRotation") { + // Reset the rotation value. + ResetRotation(); + return true; + } else if (name == "viewSource") { + // View the page source. + AppGetBrowser()->GetMainFrame()->ViewSource(); + return true; + } + + return false; + } + + IMPLEMENT_REFCOUNTING(ClientV8UIHandler); +}; + +void InitUIPluginTest() { + // Structure providing information about the client plugin. + CefPluginInfo plugin_info; + CefString(&plugin_info.display_name).FromASCII("Client UI Plugin"); + CefString(&plugin_info.unique_name).FromASCII("client_ui_plugin"); + CefString(&plugin_info.description).FromASCII("My Example Client UI Plugin"); + CefString(&plugin_info.mime_types).FromASCII( + "application/x-client-ui-plugin"); + + plugin_info.np_getentrypoints = NP_UIGetEntryPoints; + plugin_info.np_initialize = NP_UIInitialize; + plugin_info.np_shutdown = NP_UIShutdown; + + // Register the internal client plugin + CefRegisterPlugin(plugin_info); + + // Register a V8 extension with the below JavaScript code that calls native + // methods implemented in ClientV8UIHandler. + std::string code = "var cef;" + "if (!cef)" + " cef = {};" + "if (!cef.uiapp)" + " cef.uiapp = {};" + "(function() {" + " cef.uiapp.modifyRotation = function(val) {" + " native function modifyRotation();" + " return modifyRotation(val);" + " };" + " cef.uiapp.resetRotation = function() {" + " native function resetRotation();" + " return resetRotation();" + " };" + " cef.uiapp.viewSource = function() {" + " native function viewSource();" + " return viewSource();" + " };" + "})();"; + CefRegisterExtension("uiplugin/test", code, new ClientV8UIHandler()); +} + +void RunUIPluginTest(CefRefPtr browser) { + browser->GetMainFrame()->LoadURL("http://tests/uiapp"); +} diff --git a/cef1/tests/cefclient/uiplugin_test.h b/cef1/tests/cefclient/uiplugin_test.h new file mode 100644 index 000000000..cd231f9e5 --- /dev/null +++ b/cef1/tests/cefclient/uiplugin_test.h @@ -0,0 +1,19 @@ +// 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_UIPLUGIN_TEST_H_ +#define CEF_TESTS_CEFCLIENT_UIPLUGIN_TEST_H_ +#pragma once + +#include "include/cef_base.h" + +class CefBrowser; + +// Register the internal client plugin and V8 extension. +void InitUIPluginTest(); + +// Run the test. +void RunUIPluginTest(CefRefPtr browser); + +#endif // CEF_TESTS_CEFCLIENT_UIPLUGIN_TEST_H_ diff --git a/cef1/tests/cefclient/util.h b/cef1/tests/cefclient/util.h new file mode 100644 index 000000000..ba0305c1c --- /dev/null +++ b/cef1/tests/cefclient/util.h @@ -0,0 +1,37 @@ +// 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_UTIL_H_ +#define CEF_TESTS_CEFCLIENT_UTIL_H_ +#pragma once + +#include "include/cef_task.h" + +#if defined(OS_WIN) + +#include // NOLINT(build/include_order) + +#ifndef NDEBUG +#define ASSERT(condition) if (!(condition)) { DebugBreak(); } +#else +#define ASSERT(condition) ((void)0) +#endif + +#else // !OS_WIN + +#include // NOLINT(build/include_order) + +#ifndef NDEBUG +#define ASSERT(condition) if (!(condition)) { assert(false); } +#else +#define ASSERT(condition) ((void)0) +#endif + +#endif // !OS_WIN + +#define REQUIRE_UI_THREAD() ASSERT(CefCurrentlyOn(TID_UI)); +#define REQUIRE_IO_THREAD() ASSERT(CefCurrentlyOn(TID_IO)); +#define REQUIRE_FILE_THREAD() ASSERT(CefCurrentlyOn(TID_FILE)); + +#endif // CEF_TESTS_CEFCLIENT_UTIL_H_ diff --git a/cef1/tests/unittests/command_line_unittest.cc b/cef1/tests/unittests/command_line_unittest.cc new file mode 100644 index 000000000..031432fe7 --- /dev/null +++ b/cef1/tests/unittests/command_line_unittest.cc @@ -0,0 +1,112 @@ +// 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_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); +} + +} // 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/cef1/tests/unittests/content_filter_unittest.cc b/cef1/tests/unittests/content_filter_unittest.cc new file mode 100644 index 000000000..d155bcd4a --- /dev/null +++ b/cef1/tests/unittests/content_filter_unittest.cc @@ -0,0 +1,219 @@ +// 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_content_filter.h" +#include "tests/unittests/test_handler.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +bool g_ContentFilterTestHandlerHandleResourceResponseCalled; +bool g_ContentFilterProcessDataCalled; +bool g_ContentFilterDrainCalled; + +class TestContentFilter : public CefContentFilter { + public: + TestContentFilter() { + look_for_ = "FAILURE!"; + replace_with_ = "BIG SUCCESS!"; + } + + virtual void ProcessData(const void* data, int data_size, + CefRefPtr& substitute_data) + OVERRIDE { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + + g_ContentFilterProcessDataCalled = true; + + std::string in_out(static_cast(data), data_size); + std::string::const_iterator look_for_it = look_for_.begin(); + + bool is_modified = false; + if (!remainder_.empty()) { + in_out.insert(in_out.begin(), remainder_.begin(), remainder_.end()); + remainder_.clear(); + } + + std::string::size_type off = 0; + do { + if ((look_for_it == look_for_.end()) || + (look_for_it == look_for_.begin())) { + // start over + off = in_out.find(look_for_[0], off); + if (off == in_out.npos) + break; + look_for_it = look_for_.begin(); + } + + while (look_for_it != look_for_.end()) { + if (*look_for_it != in_out[off]) { + look_for_it = look_for_.begin(); + break; + } + + if (++off == in_out.length()) + off = in_out.npos; + + if (off == in_out.npos) + break; + + look_for_it++; + } + + if (look_for_it == look_for_.end()) { + // found it + in_out.replace(in_out.begin() + off - look_for_.length(), + in_out.begin() + off, + replace_with_); + off += replace_with_.length() - look_for_.length(); + if (off >= in_out.length()) + off = in_out.npos; + + look_for_it = look_for_.begin(); + is_modified = true; + } + } while (off != in_out.npos); + + if (look_for_it != look_for_.begin()) { + // partial match at the end of the buffer + // save for next packet + size_t slice_off = + in_out.length() - (look_for_it - look_for_.begin()) - 1; + + remainder_ = in_out.substr(slice_off); + in_out.erase(slice_off); + } + + if (is_modified) { + substitute_data = CefStreamReader::CreateForData( + static_cast(const_cast(in_out.data())), + in_out.size()); + } + } + + virtual void Drain(CefRefPtr& remainder) OVERRIDE { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + + g_ContentFilterDrainCalled = true; + + if (remainder_.empty()) + return; + + remainder = CefStreamReader::CreateForData( + static_cast(const_cast(remainder_.data())), + remainder_.size()); + } + + protected: + IMPLEMENT_REFCOUNTING(TestContentFilter); + + private: + std::string look_for_; + std::string replace_with_; + std::string remainder_; +}; + +class ContentFilterTestHandler : public TestHandler { + public: + class Visitor : public CefDOMVisitor { + public: + explicit Visitor(ContentFilterTestHandler* handler) : handler_(handler) {} + + // Test if the filter succeeded in modifying the content + void TestContentReplaced(CefRefPtr document) { + // Navigate the complete document structure. + CefRefPtr resultNode = + document->GetElementById("test_result"); + + EXPECT_TRUE(resultNode.get()); + EXPECT_EQ("BIG SUCCESS!", resultNode->GetElementInnerText().ToString()); + } + + virtual void Visit(CefRefPtr document) OVERRIDE { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + + handler_->got_visitor_called_.yes(); + + TestContentReplaced(document); + + handler_->DestroyTest(); + } + + protected: + ContentFilterTestHandler* handler_; + IMPLEMENT_REFCOUNTING(Visitor); + }; + + ContentFilterTestHandler() { + visitor_ = new Visitor(this); + } + + virtual void RunTest() OVERRIDE { + std::string mainHtml = + "

If filtering works you should see BIG SUCCESS! below:

" + "
FAILURE!
"; + + AddResource("http://tests/test_filter.html", mainHtml, "text/html"); + CreateBrowser("http://tests/test_filter.html"); + } + + virtual void OnResourceResponse(CefRefPtr browser, + const CefString& url, + CefRefPtr response, + CefRefPtr& filter) + OVERRIDE { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + + g_ContentFilterTestHandlerHandleResourceResponseCalled = true; + + ASSERT_EQ(url, "http://tests/test_filter.html"); + + CefResponse::HeaderMap headers; + response->GetHeaderMap(headers); + std::string mime_type = response->GetMimeType(); + int status_code = response->GetStatus(); + std::string status_text = response->GetStatusText(); + + ASSERT_TRUE(headers.empty()); + ASSERT_EQ(mime_type, "text/html"); + ASSERT_EQ(status_code, 200); + ASSERT_EQ(status_text, "OK"); + + filter = new TestContentFilter(); + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + EXPECT_TRUE(CefCurrentlyOn(TID_UI)); + + if (frame->IsMain()) { + // The page is done loading so visit the DOM. + browser->GetMainFrame()->VisitDOM(visitor_.get()); + } + } + + TrackCallback got_visitor_called_; + + private: + CefRefPtr visitor_; +}; + +} // namespace + +// Verify send and recieve +TEST(ContentFilterTest, ContentFilter) { + g_ContentFilterTestHandlerHandleResourceResponseCalled = false; + g_ContentFilterProcessDataCalled = false; + g_ContentFilterDrainCalled = false; + + CefRefPtr handler = + new ContentFilterTestHandler(); + handler->ExecuteTest(); + + ASSERT_TRUE(handler->got_visitor_called_); + ASSERT_TRUE(g_ContentFilterTestHandlerHandleResourceResponseCalled); + ASSERT_TRUE(g_ContentFilterProcessDataCalled); + ASSERT_TRUE(g_ContentFilterDrainCalled); +} diff --git a/cef1/tests/unittests/cookie_unittest.cc b/cef1/tests/unittests/cookie_unittest.cc new file mode 100644 index 000000000..53ff58bd1 --- /dev/null +++ b/cef1/tests/unittests/cookie_unittest.cc @@ -0,0 +1,954 @@ +// 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_cookie.h" +#include "include/cef_runnable.h" +#include "include/cef_scheme.h" +#include "tests/unittests/test_handler.h" +#include "tests/unittests/test_suite.h" +#include "base/scoped_temp_dir.h" +#include "base/synchronization/waitable_event.h" +#include "testing/gtest/include/gtest/gtest.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) { + } + virtual ~TestVisitor() { + event_->Signal(); + } + + virtual bool Visit(const CefCookie& cookie, int count, int total, + bool& deleteCookie) { + 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, NewCefRunnableFunction(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, NewCefRunnableFunction(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, + 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); + 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_TRUE(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, NewCefRunnableFunction(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, 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, 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; + + 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())); + + // 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, event); + + // Retrieve and verify the domain cookie. + GetCookie(manager, cookie, true, event, false); + + // Restore the original storage location. + EXPECT_TRUE(manager->SetStoragePath(original_dir)); + + // 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())); + + // 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)); + + // 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()); + EXPECT_TRUE(manager.get()); + + TestDomainCookie(manager); +} + +// Test creation of a domain cookie. +TEST(CookieTest, DomainCookieOnDisk) { + ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value()); + 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()); + EXPECT_TRUE(manager.get()); + + TestHostCookie(manager); +} + +// Test creation of a host cookie. +TEST(CookieTest, HostCookieOnDisk) { + ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value()); + 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()); + EXPECT_TRUE(manager.get()); + + TestMultipleCookies(manager); +} + +// Test creation of multiple cookies. +TEST(CookieTest, MultipleCookiesOnDisk) { + ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value()); + 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()); + EXPECT_TRUE(manager.get()); + + TestAllCookies(manager); +} + +TEST(CookieTest, AllCookiesOnDisk) { + ScopedTempDir temp_dir; + + // Create a new temporary directory. + EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); + + CefRefPtr manager = + CefCookieManager::CreateManager(temp_dir.path().value()); + 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()); + EXPECT_TRUE(manager.get()); + + TestChangeDirectory(manager, CefString()); +} + + +namespace { + +const char* kCookieJSUrl1 = "http://tests/cookie1.html"; +const char* kCookieJSUrl2 = "http://tests/cookie2.html"; + +class CookieTestJSHandler : public TestHandler { + public: + CookieTestJSHandler() {} + + virtual void RunTest() OVERRIDE { + // Create =new in-memory managers. + manager1_ = CefCookieManager::CreateManager(CefString()); + manager2_ = CefCookieManager::CreateManager(CefString()); + + std::string page = + "" + "" + "COOKIE TEST1"; + AddResource(kCookieJSUrl1, page, "text/html"); + + page = + "" + "" + "COOKIE TEST2"; + AddResource(kCookieJSUrl2, page, "text/html"); + + // Create the browser + CreateBrowser(kCookieJSUrl1); + } + + virtual 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 + frame->LoadURL(kCookieJSUrl2); + } else { + got_load_end2_.yes(); + VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_); + + DestroyTest(); + } + } + + virtual CefRefPtr GetCookieManager( + CefRefPtr browser, + const CefString& main_url) OVERRIDE { + if (main_url == kCookieJSUrl1) { + // Return the first cookie manager. + got_cookie_manager1_.yes(); + return manager1_; + } else { + // Return the second cookie manager. + got_cookie_manager2_.yes(); + return manager2_; + } + } + + // 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 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_); +} + + +namespace { + +class CookieTestSchemeHandler : public TestHandler { + public: + class SchemeHandler : public CefSchemeHandler { + public: + explicit SchemeHandler(CookieTestSchemeHandler* handler) + : handler_(handler), + offset_(0) {} + + virtual 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->HeadersAvailable(); + return true; + } + + virtual 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); + } + } + + virtual 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; + } + + virtual 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) {} + + virtual CefRefPtr Create(CefRefPtr browser, + 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); + }; + + 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"; + } + + virtual void RunTest() OVERRIDE { + // Create new in-memory managers. + manager1_ = CefCookieManager::CreateManager(CefString()); + manager2_ = CefCookieManager::CreateManager(CefString()); + + if (scheme_ != "http") { + CefRegisterCustomScheme(scheme_, true, false, false); + + 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)); + + // Create the browser + CreateBrowser(url1_); + } + + virtual 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 + frame->LoadURL(url2_); + } else if (url == url2_) { + got_load_end2_.yes(); + VerifyCookie(manager2_, url, "name2", "value2", got_cookie2_); + + // Go to the next URL + 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(); + } + } + + virtual CefRefPtr GetCookieManager( + CefRefPtr browser, + const CefString& main_url) OVERRIDE { + if (main_url == url1_) { + // Return the first cookie manager. + got_cookie_manager1_.yes(); + return manager1_; + } else { + // Return the second cookie manager. + got_cookie_manager2_.yes(); + return manager2_; + } + } + + // 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 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_); +} + +// 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_); +} diff --git a/cef1/tests/unittests/dom_unittest.cc b/cef1/tests/unittests/dom_unittest.cc new file mode 100644 index 000000000..67b8f86fc --- /dev/null +++ b/cef1/tests/unittests/dom_unittest.cc @@ -0,0 +1,260 @@ +// 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_dom.h" +#include "tests/unittests/test_handler.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +class TestDOMHandler : public TestHandler { + public: + class Visitor : public CefDOMVisitor { + public: + explicit Visitor(TestDOMHandler* handler) : handler_(handler) {} + + 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(), "http://tests/main.html"); + 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")); + } + + virtual void Visit(CefRefPtr document) { + handler_->got_visitor_called_.yes(); + + if (handler_->test_type_ == STRUCTURE) + TestStructure(document); + else if (handler_->test_type_ == MODIFY) + TestModify(document); + + handler_->DestroyTest(); + } + + protected: + TestDOMHandler* handler_; + + IMPLEMENT_REFCOUNTING(Visitor); + }; + + enum TestType { + STRUCTURE, + MODIFY, + }; + + explicit TestDOMHandler(TestType test) : test_type_(test) { + visitor_ = new Visitor(this); + } + + virtual void RunTest() OVERRIDE { + std::stringstream mainHtml; + mainHtml << + "" + "The Title" + "" + "

Hello From
" + "Main Frame

" + "" + ""; + + AddResource("http://tests/main.html", mainHtml.str(), "text/html"); + CreateBrowser("http://tests/main.html"); + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + if (frame->IsMain()) { + // The page is done loading so visit the DOM. + browser->GetMainFrame()->VisitDOM(visitor_.get()); + } + } + + CefRefPtr visitor_; + TestType test_type_; + + TrackCallback got_visitor_called_; +}; + +} // namespace + +// Test DOM structure reading. +TEST(DOMTest, Read) { + CefRefPtr handler = + new TestDOMHandler(TestDOMHandler::STRUCTURE); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_visitor_called_); +} + +// Test DOM modifications. +TEST(DOMTest, Modify) { + CefRefPtr handler = + new TestDOMHandler(TestDOMHandler::MODIFY); + handler->ExecuteTest(); + + EXPECT_TRUE(handler->got_visitor_called_); +} diff --git a/cef1/tests/unittests/mac/English.lproj/InfoPlist.strings b/cef1/tests/unittests/mac/English.lproj/InfoPlist.strings new file mode 100644 index 000000000..fe2abe11b --- /dev/null +++ b/cef1/tests/unittests/mac/English.lproj/InfoPlist.strings @@ -0,0 +1,3 @@ +/* Localized versions of Info.plist keys */ + +NSHumanReadableCopyright = "© Chromium Embedded Framework Authors, 2010"; diff --git a/cef1/tests/unittests/mac/English.lproj/MainMenu.xib b/cef1/tests/unittests/mac/English.lproj/MainMenu.xib new file mode 100644 index 000000000..e4f7c1fc3 --- /dev/null +++ b/cef1/tests/unittests/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/cef1/tests/unittests/mac/Info.plist b/cef1/tests/unittests/mac/Info.plist new file mode 100644 index 000000000..3d5f27c20 --- /dev/null +++ b/cef1/tests/unittests/mac/Info.plist @@ -0,0 +1,28 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIconFile + unittests.icns + CFBundleIdentifier + org.cef.unittests + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.0 + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/cef1/tests/unittests/mac/unittests.icns b/cef1/tests/unittests/mac/unittests.icns new file mode 100644 index 000000000..f36742de2 Binary files /dev/null and b/cef1/tests/unittests/mac/unittests.icns differ diff --git a/cef1/tests/unittests/navigation_unittest.cc b/cef1/tests/unittests/navigation_unittest.cc new file mode 100644 index 000000000..54328649d --- /dev/null +++ b/cef1/tests/unittests/navigation_unittest.cc @@ -0,0 +1,619 @@ +// 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_scheme.h" +#include "tests/unittests/test_handler.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +static const char* kNav1 = "http://tests/nav1.html"; +static const char* kNav2 = "http://tests/nav2.html"; +static const char* kNav3 = "http://tests/nav3.html"; +static const char* kNav4 = "http://tests/nav4.html"; + +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 kNavList[] = { + // kNav1 | kNav2 | kNav3 + {NA_LOAD, kNav1, false, false}, // X + {NA_LOAD, kNav2, true, false}, // . X + {NA_BACK, kNav1, false, true}, // X . + {NA_FORWARD, kNav2, true, false}, // . X + {NA_LOAD, kNav3, true, false}, // . . X + {NA_BACK, kNav2, true, true}, // . X . + {NA_CLEAR, kNav2, false, false}, // X +}; + +#define NAV_LIST_SIZE() (sizeof(kNavList) / sizeof(NavListItem)) + +class HistoryNavTestHandler : public TestHandler { + public: + HistoryNavTestHandler() : nav_(0) {} + + virtual void RunTest() OVERRIDE { + // Add the resources that we will navigate to/from. + AddResource(kNav1, "Nav1", "text/html"); + AddResource(kNav2, "Nav2", "text/html"); + AddResource(kNav3, "Nav3", "text/html"); + + // Create the browser. + CreateBrowser(CefString()); + } + + void RunNav(CefRefPtr browser) { + if (nav_ == NAV_LIST_SIZE()) { + // End of the nav list. + DestroyTest(); + return; + } + + const NavListItem& item = kNavList[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: + browser->ClearHistory(); + // Not really a navigation action so go to the next one. + nav_++; + RunNav(browser); + break; + default: + break; + } + } + + virtual void OnAfterCreated(CefRefPtr browser) OVERRIDE { + TestHandler::OnAfterCreated(browser); + + RunNav(browser); + } + + virtual bool OnBeforeBrowse(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr request, + NavType navType, + bool isRedirect) OVERRIDE { + const NavListItem& item = kNavList[nav_]; + + got_before_browse_[nav_].yes(); + + std::string url = request->GetURL(); + if (url == item.target) + got_correct_target_[nav_].yes(); + + if (((item.action == NA_BACK || item.action == NA_FORWARD) && + navType == NAVTYPE_BACKFORWARD) || + (item.action == NA_LOAD && navType == NAVTYPE_OTHER)) { + got_correct_nav_type_[nav_].yes(); + } + + return false; + } + + virtual void OnNavStateChange(CefRefPtr browser, + bool canGoBack, + bool canGoForward) OVERRIDE { + const NavListItem& item = kNavList[nav_]; + + got_nav_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(); + } + + virtual void OnLoadStart(CefRefPtr browser, + CefRefPtr frame) OVERRIDE { + if(browser->IsPopup() || !frame->IsMain()) + return; + + const NavListItem& item = kNavList[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(); + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + if (browser->IsPopup() || !frame->IsMain()) + return; + + const NavListItem& item = kNavList[nav_]; + + got_load_end_[nav_].yes(); + + 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(); + + nav_++; + RunNav(browser); + } + + int nav_; + + TrackCallback got_before_browse_[NAV_LIST_SIZE()]; + TrackCallback got_correct_target_[NAV_LIST_SIZE()]; + TrackCallback got_correct_nav_type_[NAV_LIST_SIZE()]; + TrackCallback got_nav_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_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) { + CefRefPtr handler = + new HistoryNavTestHandler(); + handler->ExecuteTest(); + + for (size_t i = 0; i < NAV_LIST_SIZE(); ++i) { + if (kNavList[i].action != NA_CLEAR) { + ASSERT_TRUE(handler->got_before_browse_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_target_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_nav_type_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_load_start_[i]) << "i = " << i; + ASSERT_TRUE(handler->got_correct_load_start_url_[i]) << "i = " << i; + } + + if (i == 0 || kNavList[i].can_go_back != kNavList[i-1].can_go_back || + kNavList[i].can_go_forward != kNavList[i-1].can_go_forward) { + // Back/forward state has changed from one navigation to the next. + ASSERT_TRUE(handler->got_nav_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; + } else { + ASSERT_FALSE(handler->got_nav_state_change_[i]) << "i = " << i; + ASSERT_FALSE(handler->got_correct_can_go_back_[i]) << "i = " << i; + ASSERT_FALSE(handler->got_correct_can_go_forward_[i]) << "i = " << i; + } + + if (kNavList[i].action != NA_CLEAR) { + ASSERT_TRUE(handler->got_load_end_[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; + } + } +} + + +namespace { + +class FrameNameIdentNavTestHandler : public TestHandler { + public: + FrameNameIdentNavTestHandler() : browse_ct_(0) {} + + virtual void RunTest() OVERRIDE { + // Add the frame resources. + std::stringstream ss; + + // Page with named frame + ss << "Nav1" + "", "text/html"); + AddResource(kV8ContextChildTestUrl, "CHILD", + "text/html"); + CreateBrowser(kV8ContextParentTestUrl); + } else { + EXPECT_TRUE(test_url_ != NULL); + AddResource(test_url_, "TEST", "text/html"); + CreateBrowser(test_url_); + } + } + + // Run the specified test. + void RunTest(V8TestMode test_mode) { + switch (test_mode) { + case V8TEST_NULL_CREATE: + RunNullCreateTest(); + break; + case V8TEST_BOOL_CREATE: + RunBoolCreateTest(); + break; + case V8TEST_INT_CREATE: + RunIntCreateTest(); + break; + case V8TEST_UINT_CREATE: + RunUIntCreateTest(); + break; + case V8TEST_DOUBLE_CREATE: + RunDoubleCreateTest(); + break; + case V8TEST_DATE_CREATE: + RunDateCreateTest(); + break; + case V8TEST_STRING_CREATE: + RunStringCreateTest(); + break; + case V8TEST_ARRAY_CREATE: + RunArrayCreateTest(); + break; + case V8TEST_ARRAY_VALUE: + RunArrayValueTest(); + break; + case V8TEST_OBJECT_CREATE: + RunObjectCreateTest(); + break; + case V8TEST_OBJECT_USERDATA: + RunObjectUserDataTest(); + break; + case V8TEST_OBJECT_ACCESSOR: + RunObjectAccessorTest(); + break; + case V8TEST_OBJECT_ACCESSOR_EXCEPTION: + RunObjectAccessorExceptionTest(); + break; + case V8TEST_OBJECT_ACCESSOR_FAIL: + RunObjectAccessorFailTest(); + break; + case V8TEST_OBJECT_ACCESSOR_READONLY: + RunObjectAccessorReadOnlyTest(); + break; + case V8TEST_OBJECT_VALUE: + RunObjectValueTest(); + break; + case V8TEST_OBJECT_VALUE_READONLY: + RunObjectValueReadOnlyTest(); + break; + case V8TEST_OBJECT_VALUE_ENUM: + RunObjectValueEnumTest(); + break; + case V8TEST_OBJECT_VALUE_DONTENUM: + RunObjectValueDontEnumTest(); + break; + case V8TEST_OBJECT_VALUE_DELETE: + RunObjectValueDeleteTest(); + break; + case V8TEST_OBJECT_VALUE_DONTDELETE: + RunObjectValueDontDeleteTest(); + break; + case V8TEST_FUNCTION_CREATE: + RunFunctionCreateTest(); + break; + case V8TEST_FUNCTION_HANDLER: + RunFunctionHandlerTest(); + break; + case V8TEST_FUNCTION_HANDLER_EXCEPTION: + RunFunctionHandlerExceptionTest(); + break; + case V8TEST_FUNCTION_HANDLER_FAIL: + RunFunctionHandlerFailTest(); + break; + case V8TEST_FUNCTION_HANDLER_NO_OBJECT: + RunFunctionHandlerNoObjectTest(); + break; + case V8TEST_FUNCTION_HANDLER_WITH_CONTEXT: + RunFunctionHandlerWithContextTest(); + break; + case V8TEST_CONTEXT_EVAL: + RunContextEvalTest(); + break; + case V8TEST_CONTEXT_EVAL_EXCEPTION: + RunContextEvalExceptionTest(); + break; + case V8TEST_CONTEXT_ENTERED: + RunContextEnteredTest(); + break; + case V8TEST_BINDING: + RunBindingTest(); + break; + case V8TEST_STACK_TRACE: + RunStackTraceTest(); + break; + default: + ADD_FAILURE(); + DestroyTest(); + break; + } + } + + void RunNullCreateTest() { + CefRefPtr value = CefV8Value::CreateNull(); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsNull()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsObject()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunBoolCreateTest() { + CefRefPtr value = CefV8Value::CreateBool(true); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsBool()); + EXPECT_EQ(true, value->GetBoolValue()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsObject()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunIntCreateTest() { + CefRefPtr value = CefV8Value::CreateInt(12); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsInt()); + EXPECT_TRUE(value->IsUInt()); + EXPECT_TRUE(value->IsDouble()); + EXPECT_EQ(12, value->GetIntValue()); + EXPECT_EQ((uint32)12, value->GetUIntValue()); + EXPECT_EQ(12, value->GetDoubleValue()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsObject()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunUIntCreateTest() { + CefRefPtr value = CefV8Value::CreateUInt(12); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsInt()); + EXPECT_TRUE(value->IsUInt()); + EXPECT_TRUE(value->IsDouble()); + EXPECT_EQ(12, value->GetIntValue()); + EXPECT_EQ((uint32)12, value->GetUIntValue()); + EXPECT_EQ(12, value->GetDoubleValue()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsObject()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunDoubleCreateTest() { + CefRefPtr value = CefV8Value::CreateDouble(12.1223); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsDouble()); + EXPECT_EQ(12.1223, value->GetDoubleValue()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsObject()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunDateCreateTest() { + CefRefPtr context = GetContext(); + + CefTime date; + date.year = 2200; + date.month = 4; + date.day_of_week = 5; + date.day_of_month = 11; + date.hour = 20; + date.minute = 15; + date.second = 42; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr value = CefV8Value::CreateDate(date); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsDate()); + EXPECT_TRUE(value->IsObject()); + EXPECT_EQ(date.GetTimeT(), value->GetDateValue().GetTimeT()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunStringCreateTest() { + CefRefPtr value = CefV8Value::CreateString("My string"); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsString()); + EXPECT_STREQ("My string", value->GetStringValue().ToString().c_str()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsObject()); + + DestroyTest(); + } + + void RunArrayCreateTest() { + CefRefPtr context = GetContext(); + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr value = CefV8Value::CreateArray(2); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsArray()); + EXPECT_TRUE(value->IsObject()); + EXPECT_EQ(2, value->GetArrayLength()); + EXPECT_FALSE(value->HasValue(0)); + EXPECT_FALSE(value->HasValue(1)); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunArrayValueTest() { + CefRefPtr context = GetContext(); + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr value = CefV8Value::CreateArray(0); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsArray()); + EXPECT_EQ(0, value->GetArrayLength()); + + // Test addng values. + EXPECT_FALSE(value->HasValue(0)); + EXPECT_FALSE(value->HasValue(1)); + + EXPECT_TRUE(value->SetValue(0, CefV8Value::CreateInt(10))); + EXPECT_FALSE(value->HasException()); + EXPECT_TRUE(value->HasValue(0)); + EXPECT_FALSE(value->HasValue(1)); + + EXPECT_TRUE(value->GetValue(0)->IsInt()); + EXPECT_EQ(10, value->GetValue(0)->GetIntValue()); + EXPECT_FALSE(value->HasException()); + EXPECT_EQ(1, value->GetArrayLength()); + + EXPECT_TRUE(value->SetValue(1, CefV8Value::CreateInt(43))); + EXPECT_FALSE(value->HasException()); + EXPECT_TRUE(value->HasValue(0)); + EXPECT_TRUE(value->HasValue(1)); + + EXPECT_TRUE(value->GetValue(1)->IsInt()); + EXPECT_EQ(43, value->GetValue(1)->GetIntValue()); + EXPECT_FALSE(value->HasException()); + EXPECT_EQ(2, value->GetArrayLength()); + + EXPECT_TRUE(value->DeleteValue(0)); + EXPECT_FALSE(value->HasValue(0)); + EXPECT_TRUE(value->HasValue(1)); + EXPECT_EQ(2, value->GetArrayLength()); + + EXPECT_TRUE(value->DeleteValue(1)); + EXPECT_FALSE(value->HasValue(0)); + EXPECT_FALSE(value->HasValue(1)); + EXPECT_EQ(2, value->GetArrayLength()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectCreateTest() { + CefRefPtr context = GetContext(); + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr value = CefV8Value::CreateObject(NULL); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsObject()); + EXPECT_FALSE(value->GetUserData().get()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsFunction()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunObjectUserDataTest() { + CefRefPtr context = GetContext(); + + class UserData : public CefBase { + public: + explicit UserData(int value) : value_(value) {} + int value_; + IMPLEMENT_REFCOUNTING(UserData); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr value = CefV8Value::CreateObject(NULL); + EXPECT_TRUE(value.get()); + + EXPECT_TRUE(value->SetUserData(new UserData(10))); + + CefRefPtr user_data = value->GetUserData(); + EXPECT_TRUE(user_data.get()); + UserData* user_data_impl = static_cast(user_data.get()); + EXPECT_EQ(10, user_data_impl->value_); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectAccessorTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "val"; + static const int kValue = 20; + + class Accessor : public CefV8Accessor { + public: + Accessor() : value_(0) {} + virtual bool Get(const CefString& name, + const CefRefPtr object, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + EXPECT_STREQ(kName, name.ToString().c_str()); + + EXPECT_TRUE(object.get()); + EXPECT_TRUE(object->IsSame(object_)); + + EXPECT_FALSE(retval.get()); + EXPECT_TRUE(exception.empty()); + + got_get_.yes(); + retval = CefV8Value::CreateInt(value_); + EXPECT_EQ(kValue, retval->GetIntValue()); + return true; + } + + virtual bool Set(const CefString& name, + const CefRefPtr object, + const CefRefPtr value, + CefString& exception) OVERRIDE { + EXPECT_STREQ(kName, name.ToString().c_str()); + + EXPECT_TRUE(object.get()); + EXPECT_TRUE(object->IsSame(object_)); + + EXPECT_TRUE(value.get()); + EXPECT_TRUE(exception.empty()); + + got_set_.yes(); + value_ = value->GetIntValue(); + EXPECT_EQ(kValue, value_); + return true; + } + + CefRefPtr object_; + int value_; + TrackCallback got_get_; + TrackCallback got_set_; + + IMPLEMENT_REFCOUNTING(Accessor); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Accessor* accessor = new Accessor; + CefRefPtr accessorPtr(accessor); + + CefRefPtr object = CefV8Value::CreateObject(accessor); + EXPECT_TRUE(object.get()); + accessor->object_ = object; + + EXPECT_FALSE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(kValue), + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(accessor->got_set_); + EXPECT_EQ(kValue, accessor->value_); + + CefRefPtr val = object->GetValue(kName); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(val.get()); + EXPECT_TRUE(accessor->got_get_); + EXPECT_TRUE(val->IsInt()); + EXPECT_EQ(kValue, val->GetIntValue()); + + accessor->object_ = NULL; + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectAccessorExceptionTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "val"; + static const char* kGetException = "My get exception"; + static const char* kSetException = "My set exception"; + static const char* kGetExceptionMsg = "Uncaught Error: My get exception"; + static const char* kSetExceptionMsg = "Uncaught Error: My set exception"; + + class Accessor : public CefV8Accessor { + public: + Accessor() {} + virtual bool Get(const CefString& name, + const CefRefPtr object, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + got_get_.yes(); + exception = kGetException; + return true; + } + + virtual bool Set(const CefString& name, + const CefRefPtr object, + const CefRefPtr value, + CefString& exception) OVERRIDE { + got_set_.yes(); + exception = kSetException; + return true; + } + + TrackCallback got_get_; + TrackCallback got_set_; + + IMPLEMENT_REFCOUNTING(Accessor); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr exception; + Accessor* accessor = new Accessor; + CefRefPtr accessorPtr(accessor); + + CefRefPtr object = CefV8Value::CreateObject(accessor); + EXPECT_TRUE(object.get()); + + EXPECT_FALSE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(object->HasValue(kName)); + + EXPECT_FALSE(object->SetValue(kName, CefV8Value::CreateInt(1), + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_TRUE(object->HasException()); + EXPECT_TRUE(accessor->got_set_); + exception = object->GetException(); + EXPECT_TRUE(exception.get()); + EXPECT_STREQ(kSetExceptionMsg, exception->GetMessage().ToString().c_str()); + + EXPECT_TRUE(object->ClearException()); + EXPECT_FALSE(object->HasException()); + + CefRefPtr val = object->GetValue(kName); + EXPECT_FALSE(val.get()); + EXPECT_TRUE(object->HasException()); + EXPECT_TRUE(accessor->got_get_); + exception = object->GetException(); + EXPECT_TRUE(exception.get()); + EXPECT_STREQ(kGetExceptionMsg, exception->GetMessage().ToString().c_str()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectAccessorFailTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "val"; + + class Accessor : public CefV8Accessor { + public: + Accessor() {} + virtual bool Get(const CefString& name, + const CefRefPtr object, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + got_get_.yes(); + return false; + } + + virtual bool Set(const CefString& name, + const CefRefPtr object, + const CefRefPtr value, + CefString& exception) OVERRIDE { + got_set_.yes(); + return false; + } + + TrackCallback got_get_; + TrackCallback got_set_; + + IMPLEMENT_REFCOUNTING(Accessor); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr exception; + Accessor* accessor = new Accessor; + CefRefPtr accessorPtr(accessor); + + CefRefPtr object = CefV8Value::CreateObject(accessor); + EXPECT_TRUE(object.get()); + + EXPECT_FALSE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(1), + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(accessor->got_set_); + + CefRefPtr val = object->GetValue(kName); + EXPECT_TRUE(val.get()); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(accessor->got_get_); + EXPECT_TRUE(val->IsUndefined()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectAccessorReadOnlyTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "val"; + + class Accessor : public CefV8Accessor { + public: + Accessor() {} + virtual bool Get(const CefString& name, + const CefRefPtr object, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + got_get_.yes(); + return true; + } + + virtual bool Set(const CefString& name, + const CefRefPtr object, + const CefRefPtr value, + CefString& exception) OVERRIDE { + got_set_.yes(); + return true; + } + + TrackCallback got_get_; + TrackCallback got_set_; + + IMPLEMENT_REFCOUNTING(Accessor); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr exception; + Accessor* accessor = new Accessor; + CefRefPtr accessorPtr(accessor); + + CefRefPtr object = CefV8Value::CreateObject(accessor); + EXPECT_TRUE(object.get()); + + EXPECT_FALSE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, V8_ACCESS_CONTROL_DEFAULT, + V8_PROPERTY_ATTRIBUTE_READONLY)); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(object->HasValue(kName)); + + EXPECT_TRUE(object->SetValue(kName, CefV8Value::CreateInt(1), + V8_PROPERTY_ATTRIBUTE_NONE)); + EXPECT_FALSE(object->HasException()); + EXPECT_FALSE(accessor->got_set_); + + CefRefPtr val = object->GetValue(kName); + EXPECT_TRUE(val.get()); + EXPECT_FALSE(object->HasException()); + EXPECT_TRUE(accessor->got_get_); + EXPECT_TRUE(val->IsUndefined()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectValueTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "test_arg"; + static const int kVal1 = 13; + static const int kVal2 = 65; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + object->SetValue(kName, CefV8Value::CreateInt(kVal1), + V8_PROPERTY_ATTRIBUTE_NONE); + + std::stringstream test; + test << + "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << + "window." << kName << " = " << kVal2 << ";"; + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval(test.str(), retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + CefRefPtr newval = object->GetValue(kName); + EXPECT_TRUE(newval.get()); + EXPECT_TRUE(newval->IsInt()); + EXPECT_EQ(kVal2, newval->GetIntValue()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectValueReadOnlyTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "test_arg"; + static const int kVal1 = 13; + static const int kVal2 = 65; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + object->SetValue(kName, CefV8Value::CreateInt(kVal1), + V8_PROPERTY_ATTRIBUTE_READONLY); + + std::stringstream test; + test << + "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << + "window." << kName << " = " << kVal2 << ";"; + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval(test.str(), retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + CefRefPtr newval = object->GetValue(kName); + EXPECT_TRUE(newval.get()); + EXPECT_TRUE(newval->IsInt()); + EXPECT_EQ(kVal1, newval->GetIntValue()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectValueEnumTest() { + CefRefPtr context = GetContext(); + + static const char* kObjName = "test_obj"; + static const char* kArgName = "test_arg"; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + CefRefPtr obj1 = CefV8Value::CreateObject(NULL); + object->SetValue(kObjName, obj1, V8_PROPERTY_ATTRIBUTE_NONE); + + obj1->SetValue(kArgName, CefV8Value::CreateInt(0), + V8_PROPERTY_ATTRIBUTE_NONE); + + std::stringstream test; + test << + "for (var i in window." << kObjName << ") {\n" + "window." << kObjName << "[i]++;\n" + "}"; + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval(test.str(), retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + CefRefPtr newval = obj1->GetValue(kArgName); + EXPECT_TRUE(newval.get()); + EXPECT_TRUE(newval->IsInt()); + EXPECT_EQ(1, newval->GetIntValue()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectValueDontEnumTest() { + CefRefPtr context = GetContext(); + + static const char* kObjName = "test_obj"; + static const char* kArgName = "test_arg"; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + CefRefPtr obj1 = CefV8Value::CreateObject(NULL); + object->SetValue(kObjName, obj1, V8_PROPERTY_ATTRIBUTE_NONE); + + obj1->SetValue(kArgName, CefV8Value::CreateInt(0), + V8_PROPERTY_ATTRIBUTE_DONTENUM); + + std::stringstream test; + test << + "for (var i in window." << kObjName << ") {\n" + "window." << kObjName << "[i]++;\n" + "}"; + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval(test.str(), retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + CefRefPtr newval = obj1->GetValue(kArgName); + EXPECT_TRUE(newval.get()); + EXPECT_TRUE(newval->IsInt()); + EXPECT_EQ(0, newval->GetIntValue()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectValueDeleteTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "test_arg"; + static const int kVal1 = 13; + static const int kVal2 = 65; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + object->SetValue(kName, CefV8Value::CreateInt(kVal1), + V8_PROPERTY_ATTRIBUTE_NONE); + + std::stringstream test; + test << + "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << + "window." << kName << " = " << kVal2 << ";\n" + "delete window." << kName << ";"; + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval(test.str(), retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + CefRefPtr newval = object->GetValue(kName); + EXPECT_TRUE(newval.get()); + EXPECT_TRUE(newval->IsUndefined()); + EXPECT_FALSE(newval->IsInt()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunObjectValueDontDeleteTest() { + CefRefPtr context = GetContext(); + + static const char* kName = "test_arg"; + static const int kVal1 = 13; + static const int kVal2 = 65; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + object->SetValue(kName, CefV8Value::CreateInt(kVal1), + V8_PROPERTY_ATTRIBUTE_DONTDELETE); + + std::stringstream test; + test << + "if (window." << kName << " != " << kVal1 << ") throw 'Fail';\n" << + "window." << kName << " = " << kVal2 << ";\n" + "delete window." << kName << ";"; + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval(test.str(), retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + CefRefPtr newval = object->GetValue(kName); + EXPECT_TRUE(newval.get()); + EXPECT_TRUE(newval->IsInt()); + EXPECT_EQ(kVal2, newval->GetIntValue()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunFunctionCreateTest() { + CefRefPtr context = GetContext(); + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { return false; } + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr value = CefV8Value::CreateFunction("f", new Handler); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsFunction()); + EXPECT_TRUE(value->IsObject()); + + EXPECT_FALSE(value->IsUndefined()); + EXPECT_FALSE(value->IsArray()); + EXPECT_FALSE(value->IsBool()); + EXPECT_FALSE(value->IsDate()); + EXPECT_FALSE(value->IsDouble()); + EXPECT_FALSE(value->IsInt()); + EXPECT_FALSE(value->IsUInt()); + EXPECT_FALSE(value->IsNull()); + EXPECT_FALSE(value->IsString()); + + DestroyTest(); + } + + void RunFunctionHandlerTest() { + CefRefPtr context = GetContext(); + + static const char* kFuncName = "myfunc"; + static const int kVal1 = 32; + static const int kVal2 = 41; + static const int kRetVal = 8; + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + EXPECT_STREQ(kFuncName, name.ToString().c_str()); + EXPECT_TRUE(object->IsSame(object_)); + + EXPECT_EQ((size_t)2, arguments.size()); + EXPECT_TRUE(arguments[0]->IsInt()); + EXPECT_EQ(kVal1, arguments[0]->GetIntValue()); + EXPECT_TRUE(arguments[1]->IsInt()); + EXPECT_EQ(kVal2, arguments[1]->GetIntValue()); + + EXPECT_TRUE(exception.empty()); + + retval = CefV8Value::CreateInt(kRetVal); + EXPECT_TRUE(retval.get()); + EXPECT_EQ(kRetVal, retval->GetIntValue()); + + got_execute_.yes(); + return true; + } + + CefRefPtr object_; + TrackCallback got_execute_; + + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + + CefRefPtr func = + CefV8Value::CreateFunction(kFuncName, handler); + EXPECT_TRUE(func.get()); + + CefRefPtr obj = CefV8Value::CreateObject(NULL); + EXPECT_TRUE(obj.get()); + handler->object_ = obj; + + CefV8ValueList args; + args.push_back(CefV8Value::CreateInt(kVal1)); + args.push_back(CefV8Value::CreateInt(kVal2)); + + CefRefPtr retval = func->ExecuteFunction(obj, args); + EXPECT_TRUE(handler->got_execute_); + EXPECT_TRUE(retval.get()); + EXPECT_FALSE(func->HasException()); + EXPECT_TRUE(retval->IsInt()); + EXPECT_EQ(kRetVal, retval->GetIntValue()); + + handler->object_ = NULL; + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunFunctionHandlerExceptionTest() { + CefRefPtr context = GetContext(); + + static const char* kException = "My error"; + static const char* kExceptionMsg = "Uncaught Error: My error"; + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + exception = kException; + got_execute_.yes(); + return true; + } + + TrackCallback got_execute_; + + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + + CefRefPtr func = + CefV8Value::CreateFunction("myfunc", handler); + EXPECT_TRUE(func.get()); + + CefV8ValueList args; + + CefRefPtr retval = func->ExecuteFunction(NULL, args); + EXPECT_TRUE(handler->got_execute_); + EXPECT_FALSE(retval.get()); + EXPECT_TRUE(func->HasException()); + CefRefPtr exception = func->GetException(); + EXPECT_TRUE(exception.get()); + EXPECT_STREQ(kExceptionMsg, exception->GetMessage().ToString().c_str()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunFunctionHandlerFailTest() { + CefRefPtr context = GetContext(); + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + got_execute_.yes(); + return false; + } + + TrackCallback got_execute_; + + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + + CefRefPtr func = + CefV8Value::CreateFunction("myfunc", handler); + EXPECT_TRUE(func.get()); + + CefV8ValueList args; + + CefRefPtr retval = func->ExecuteFunction(NULL, args); + EXPECT_TRUE(handler->got_execute_); + EXPECT_TRUE(retval.get()); + EXPECT_FALSE(func->HasException()); + EXPECT_TRUE(retval->IsUndefined()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunFunctionHandlerNoObjectTest() { + CefRefPtr context = GetContext(); + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + EXPECT_TRUE(object.get()); + CefRefPtr context = CefV8Context::GetCurrentContext(); + EXPECT_TRUE(context.get()); + CefRefPtr global = context->GetGlobal(); + EXPECT_TRUE(global.get()); + EXPECT_TRUE(global->IsSame(object)); + + got_execute_.yes(); + return true; + } + + TrackCallback got_execute_; + + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + + CefRefPtr func = + CefV8Value::CreateFunction("myfunc", handler); + EXPECT_TRUE(func.get()); + + CefV8ValueList args; + + CefRefPtr retval = func->ExecuteFunction(NULL, args); + EXPECT_TRUE(handler->got_execute_); + EXPECT_TRUE(retval.get()); + EXPECT_FALSE(func->HasException()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunFunctionHandlerWithContextTest() { + CefRefPtr context = GetContext(); + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + CefRefPtr context = CefV8Context::GetCurrentContext(); + EXPECT_TRUE(context.get()); + EXPECT_TRUE(context->IsSame(context_)); + got_execute_.yes(); + return true; + } + + CefRefPtr context_; + TrackCallback got_execute_; + + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + handler->context_ = context; + + CefRefPtr func = + CefV8Value::CreateFunction("myfunc", handler); + EXPECT_TRUE(func.get()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + CefV8ValueList args; + + CefRefPtr retval = + func->ExecuteFunctionWithContext(context, NULL, args); + EXPECT_TRUE(handler->got_execute_); + EXPECT_TRUE(retval.get()); + EXPECT_FALSE(func->HasException()); + + handler->context_ = NULL; + + DestroyTest(); + } + + void RunContextEvalTest() { + CefRefPtr context = GetContext(); + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval("1+2", retval, exception)); + EXPECT_TRUE(retval.get()); + EXPECT_TRUE(retval->IsInt()); + EXPECT_EQ(3, retval->GetIntValue()); + EXPECT_FALSE(exception.get()); + + DestroyTest(); + } + + void RunContextEvalExceptionTest() { + CefRefPtr context = GetContext(); + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_FALSE(context->Eval("1+foo", retval, exception)); + EXPECT_FALSE(retval.get()); + EXPECT_TRUE(exception.get()); + + DestroyTest(); + } + + void RunContextEnteredTest() { + CefRefPtr context = GetContext(); + + CefRefPtr retval; + CefRefPtr exception; + + // Test value defined in OnContextCreated + EXPECT_TRUE(context->Eval( + "document.getElementById('f').contentWindow.v8_context_entered_test()", + retval, exception)); + if (exception.get()) + ADD_FAILURE() << exception->GetMessage().c_str(); + + EXPECT_TRUE(retval.get()); + EXPECT_TRUE(retval->IsInt()); + EXPECT_EQ(21, retval->GetIntValue()); + + DestroyTest(); + } + + void RunBindingTest() { + CefRefPtr context = GetContext(); + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + + // Test value defined in OnContextCreated + CefRefPtr value = object->GetValue("v8_binding_test"); + EXPECT_TRUE(value.get()); + EXPECT_TRUE(value->IsInt()); + EXPECT_EQ(12, value->GetIntValue()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + void RunStackTraceTest() { + CefRefPtr context = GetContext(); + + static const char* kFuncName = "myfunc"; + + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + EXPECT_STREQ(kFuncName, name.ToString().c_str()); + + stack_trace_ = CefV8StackTrace::GetCurrent(10); + + retval = CefV8Value::CreateInt(3); + got_execute_.yes(); + return true; + } + + TrackCallback got_execute_; + CefRefPtr stack_trace_; + + IMPLEMENT_REFCOUNTING(Handler); + }; + + // Enter the V8 context. + EXPECT_TRUE(context->Enter()); + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + + CefRefPtr func = + CefV8Value::CreateFunction(kFuncName, handler); + EXPECT_TRUE(func.get()); + CefRefPtr obj = context->GetGlobal(); + EXPECT_TRUE(obj.get()); + obj->SetValue(kFuncName, func, V8_PROPERTY_ATTRIBUTE_NONE); + + CefRefPtr retval; + CefRefPtr exception; + + EXPECT_TRUE(context->Eval( + "function jsfunc() { return window.myfunc(); }\n" + "jsfunc();", + retval, exception)); + EXPECT_TRUE(retval.get()); + EXPECT_TRUE(retval->IsInt()); + EXPECT_EQ(3, retval->GetIntValue()); + EXPECT_FALSE(exception.get()); + + EXPECT_TRUE(handler->stack_trace_.get()); + EXPECT_EQ(2, handler->stack_trace_->GetFrameCount()); + + CefRefPtr frame; + + frame = handler->stack_trace_->GetFrame(0); + EXPECT_TRUE(frame->GetScriptName().empty()); + EXPECT_TRUE(frame->GetScriptNameOrSourceURL().empty()); + EXPECT_STREQ("jsfunc", frame->GetFunctionName().ToString().c_str()); + EXPECT_EQ(1, frame->GetLineNumber()); + EXPECT_EQ(35, frame->GetColumn()); + EXPECT_TRUE(frame.get()); + EXPECT_TRUE(frame->IsEval()); + EXPECT_FALSE(frame->IsConstructor()); + + frame = handler->stack_trace_->GetFrame(1); + EXPECT_TRUE(frame->GetScriptName().empty()); + EXPECT_TRUE(frame->GetScriptNameOrSourceURL().empty()); + EXPECT_TRUE(frame->GetFunctionName().empty()); + EXPECT_EQ(2, frame->GetLineNumber()); + EXPECT_EQ(1, frame->GetColumn()); + EXPECT_TRUE(frame.get()); + EXPECT_TRUE(frame->IsEval()); + EXPECT_FALSE(frame->IsConstructor()); + + // Exit the V8 context. + EXPECT_TRUE(context->Exit()); + + DestroyTest(); + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + if (frame->IsMain()) + RunTest(test_mode_); + } + + virtual void OnContextCreated(CefRefPtr browser, + CefRefPtr frame, + CefRefPtr context) OVERRIDE { + std::string url = frame->GetURL(); + if (url == kV8ContextChildTestUrl) { + // For V8TEST_CONTEXT_ENTERED + class Handler : public CefV8Handler { + public: + Handler() {} + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) OVERRIDE { + // context for the sub-frame + CefRefPtr context = CefV8Context::GetCurrentContext(); + EXPECT_TRUE(context.get()); + + // entered context should be the same as the main frame context + CefRefPtr entered = CefV8Context::GetEnteredContext(); + EXPECT_TRUE(entered.get()); + EXPECT_TRUE(entered->IsSame(context_)); + + context_ = NULL; + retval = CefV8Value::CreateInt(21); + return true; + } + + CefRefPtr context_; + IMPLEMENT_REFCOUNTING(Handler); + }; + + Handler* handler = new Handler; + CefRefPtr handlerPtr(handler); + + // main frame context + handler->context_ = GetContext(); + + // Function that will be called from the parent frame context. + CefRefPtr func = + CefV8Value::CreateFunction("v8_context_entered_test", handler); + EXPECT_TRUE(func.get()); + + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + EXPECT_TRUE(object->SetValue("v8_context_entered_test", func, + V8_PROPERTY_ATTRIBUTE_NONE)); + } else if (url == kV8BindingTestUrl) { + // For V8TEST_BINDING + CefRefPtr object = context->GetGlobal(); + EXPECT_TRUE(object.get()); + EXPECT_TRUE(object->SetValue("v8_binding_test", + CefV8Value::CreateInt(12), + V8_PROPERTY_ATTRIBUTE_NONE)); + } + } + + // Return the V8 context. + CefRefPtr GetContext() { + CefRefPtr context = + GetBrowser()->GetMainFrame()->GetV8Context(); + EXPECT_TRUE(context.get()); + return context; + } + + V8TestMode test_mode_; + const char* test_url_; +}; + +} // namespace + + +// Helpers for defining V8 tests. +#define V8_TEST_EX(name, test_mode, test_url) \ + TEST(V8Test, name) { \ + CefRefPtr handler = \ + new V8TestHandler(test_mode, test_url); \ + handler->ExecuteTest(); \ + } + +#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(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(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(ContextEval, V8TEST_CONTEXT_EVAL); +V8_TEST(ContextEvalException, V8TEST_CONTEXT_EVAL_EXCEPTION); +V8_TEST_EX(ContextEntered, V8TEST_CONTEXT_ENTERED, NULL); +V8_TEST_EX(Binding, V8TEST_BINDING, kV8BindingTestUrl); +V8_TEST(StackTrace, V8TEST_STACK_TRACE); + + +namespace { + +// ExternalMemoryAllocation test handler. +class V8ExternalMemTestHandler : public TestHandler { + public: + explicit V8ExternalMemTestHandler(const std::string& code) { + html_ = ""; + } + + virtual void RunTest() OVERRIDE { + const std::string url = "http://tests/run.html"; + AddResource(url, html_, "text/html"); + CreateBrowser(url); + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) OVERRIDE { + if (!browser->IsPopup() && frame->IsMain()) { + frame->ExecuteJavaScript("gc();", "", 0); + DestroyTest(); + } + } + + private: + std::string html_; +}; + +// Base class for V8 unit test handlers. +class V8TestV8Handler : public CefV8Handler { + IMPLEMENT_REFCOUNTING(V8TestV8Handler); +}; + +} // namespace + +TEST(V8Test, ExternalMemoryAllocation) { + class Test : public V8TestV8Handler { + public: + static std::string GetExtensionCode() { + std::string code = + "function createObject() {" + " native function createObject();" + " return createObject();" + "}" + "function checkSize(object) {" + " native function checkSize();" + " return checkSize(object);" + "};"; + return code; + } + + static std::string GetTestCode() { + return "checkSize(createObject());"; + } + + Test() + : object_created_(false), + size_checked_(false) { + } + + virtual bool Execute(const CefString& name, + CefRefPtr object, + const CefV8ValueList& arguments, + CefRefPtr& retval, + CefString& exception) { + static const int kTestSize = 999999999; + if (name == "createObject") { + retval = CefV8Value::CreateObject(CefRefPtr()); + object_created_ = + (retval->AdjustExternallyAllocatedMemory(kTestSize) == kTestSize); + return true; + } else if (name == "checkSize") { + size_checked_ = + arguments[0]->GetExternallyAllocatedMemory() == kTestSize; + return true; + } + return false; + } + + bool object_created_; + bool size_checked_; + }; + + Test* test = new Test(); + CefRegisterExtension("v8/externalMemory", test->GetExtensionCode(), test); + + V8ExternalMemTestHandler* test_handler = new V8ExternalMemTestHandler(test->GetTestCode()); + test_handler->ExecuteTest(); + + ASSERT_TRUE(test->object_created_); + ASSERT_TRUE(test->size_checked_); +} diff --git a/cef1/tests/unittests/web_urlrequest_unittest.cc b/cef1/tests/unittests/web_urlrequest_unittest.cc new file mode 100644 index 000000000..78b43ebb1 --- /dev/null +++ b/cef1/tests/unittests/web_urlrequest_unittest.cc @@ -0,0 +1,523 @@ +// 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_web_urlrequest.h" +#include "tests/unittests/test_handler.h" + +// #define WEB_URLREQUEST_DEBUG + +class TestResults { + public: + TestResults() + : errorCode(0), + contentLength(0), + statusCode(0), + redirectCount(0) { + } + + int errorCode; + size_t contentLength; + int statusCode; + CefString statusText; + CefString contentLengthHeader; + CefString allHeaders; + CefResponse::HeaderMap headerMap; + + int redirectCount; + + TrackCallback + got_redirect, + got_deleted, + got_started, + got_headers, + got_loading, + got_done, + got_progress, + got_abort, + got_error; +}; + +class BrowserTestHandler : public TestHandler { + public: + // Cancel at state WUR_STATE_UNSENT means that no cancellation + // will occur since that state change is never fired. + BrowserTestHandler(TestResults &tr, + cef_weburlrequest_state_t cancelAtState = WUR_STATE_UNSENT) + : cancelAtState_(cancelAtState), + test_results_(tr) { + } + + virtual void RunTest() OVERRIDE { + std::stringstream testHtml; + testHtml << + "" + "

Testing Web Url Request...

" + ""; + + AddResource("http://tests/run.html", testHtml.str(), "text/html"); + CreateBrowser("http://tests/run.html"); + } + + virtual void OnLoadEnd(CefRefPtr browser, + CefRefPtr frame, + int httpStatusCode) { + StartTest(); + } + + void TestCompleted() { + DestroyTest(); + } + + virtual void StartTest() = 0; + + cef_weburlrequest_state_t cancelAtState_; + + TestResults& test_results_; +}; + +class TestWebURLRequestClient : public CefWebURLRequestClient { + public: + TestWebURLRequestClient(TestResults& tr, BrowserTestHandler* browser) + : test_results_(tr), + cancelAtState_(WUR_STATE_UNSENT), + browser_(browser) { + } + + virtual ~TestWebURLRequestClient() { + test_results_.got_deleted.yes(); + } + + bool MaybeCancelRequest(CefRefPtr requester, + RequestState state) { + if (cancelAtState_ == state) { +#ifdef WEB_URLREQUEST_DEBUG + printf(" Cancelling at state %d\n", cancelAtState_); +#endif + requester->Cancel(); + return true; + } + return false; + } + + void OnStateChange(CefRefPtr requester, + RequestState state) { +#ifdef WEB_URLREQUEST_DEBUG + printf("OnStateChange(0x%p, %d)\n", requester.get(), state); +#endif + + if (MaybeCancelRequest(requester, state)) + return; + + switch (state) { + case WUR_STATE_STARTED: + test_results_.got_started.yes(); + break; + case WUR_STATE_HEADERS_RECEIVED: + test_results_.got_headers.yes(); + break; + case WUR_STATE_LOADING: + test_results_.got_loading.yes(); + break; + case WUR_STATE_DONE: + test_results_.got_done.yes(); + if ( contents_.length() ) { + size_t len = contents_.length(); + test_results_.contentLength = len; +#ifdef WEB_URLREQUEST_DEBUG + printf("Response: %lu - %s\n", len, contents_.c_str()); +#endif + } + TestCompleted(); + break; + case WUR_STATE_ABORT: + test_results_.got_abort.yes(); + TestCompleted(); + break; + default: + break; + } + } + + void OnRedirect(CefRefPtr requester, + CefRefPtr request, + CefRefPtr response) { +#ifdef WEB_URLREQUEST_DEBUG + printf("OnRedirect(0x%p, 0x%p, 0x%p)\n", + requester.get(), request.get(), response.get()); +#endif + test_results_.got_redirect.yes(); + ++test_results_.redirectCount; + + CefString url = request->GetURL(); +#ifdef WEB_URLREQUEST_DEBUG + printf("URL = %s\n", url.ToString().c_str()); +#endif + } + + void OnHeadersReceived(CefRefPtr requester, + CefRefPtr response) { +#ifdef WEB_URLREQUEST_DEBUG + printf("OnHeadersReceived(0x%p, 0x%p)\n", requester.get(), response.get()); +#endif + + test_results_.statusCode = response->GetStatus(); + test_results_.statusText = response->GetStatusText(); + test_results_.contentLengthHeader = response->GetHeader("Content-Length"); + response->GetHeaderMap(test_results_.headerMap); + } + + void OnData(CefRefPtr requester, const void *data, + int dataLength) { +#ifdef WEB_URLREQUEST_DEBUG + printf("OnData(0x%p, 0x%p, %d)\n", requester.get(), data, dataLength); +#endif + + // Add data to buffer, create if not already + contents_.append(static_cast(data), dataLength); + } + + void TestCompleted() { + browser_->TestCompleted(); + browser_ = NULL; + requester_ = NULL; + Release(); + } + + void OnProgress(CefRefPtr requester, + uint64 bytesSent, + uint64 totalBytesToBeSent) { +#ifdef WEB_URLREQUEST_DEBUG + printf("OnProgress(0x%p, %d, %d)\n", requester.get(), + (unsigned int)bytesSent, (unsigned int)totalBytesToBeSent); +#endif + test_results_.got_progress.yes(); + } + + void OnError(CefRefPtr requester, + CefWebURLRequestClient::ErrorCode errorCode) { +#ifdef WEB_URLREQUEST_DEBUG + printf("Error(0x%p, %d)\n", requester.get(), errorCode); +#endif + test_results_.errorCode = static_cast(errorCode); + test_results_.got_error.yes(); + TestCompleted(); + } + + bool Run(CefRefPtr req, RequestState + cancelAtState = WUR_STATE_UNSENT) { + if ( requester_.get() ) + return false; + + cancelAtState_ = cancelAtState; + request_ = req; + + // Keep ourselves alive... blanced in TestCompleted() when done. + AddRef(); + + requester_ = CefWebURLRequest::CreateWebURLRequest(request_, this); +#ifdef WEB_URLREQUEST_DEBUG + printf("Created requester at address 0x%p\n", requester_.get()); +#endif + + return requester_.get() != NULL; + } + + protected: + TestResults& test_results_; + RequestState cancelAtState_; + + CefRefPtr browser_; + CefRefPtr requester_; + CefRefPtr request_; + std::string contents_; + + IMPLEMENT_REFCOUNTING(TestWebURLRequestClient); +}; + +TEST(WebURLRequestTest, GET) { + class BrowserForTest : public BrowserTestHandler { + public: + explicit BrowserForTest(TestResults &tr) : BrowserTestHandler(tr) { } + + void StartTest() { + CefRefPtr req; + CefRefPtr postdata; + CefRequest::HeaderMap headers; + + req = CefRequest::CreateRequest(); + + CefString url( + "http://search.twitter.com/search.json?result_type=popular&q=webkit"); + CefString method("GET"); + + req->Set(url, method, postdata, headers); + + CefRefPtr handler = + new TestWebURLRequestClient(test_results_, this); + + req->SetFlags((CefRequest::RequestFlags)( + WUR_FLAG_SKIP_CACHE | + WUR_FLAG_REPORT_LOAD_TIMING | + WUR_FLAG_REPORT_RAW_HEADERS | + WUR_FLAG_REPORT_UPLOAD_PROGRESS)); + + ASSERT_TRUE(handler->Run(req)); + } + }; + + TestResults tr; + CefRefPtr browser = new BrowserForTest(tr); + browser->ExecuteTest(); + + EXPECT_TRUE(tr.got_started); + EXPECT_TRUE(tr.got_headers); + EXPECT_TRUE(tr.got_loading); + EXPECT_TRUE(tr.got_done); + EXPECT_TRUE(tr.got_deleted); + EXPECT_FALSE(tr.got_abort); + EXPECT_FALSE(tr.got_error); + EXPECT_FALSE(tr.got_redirect); + EXPECT_FALSE(tr.got_progress); + EXPECT_GT(tr.contentLength, static_cast(0)); + EXPECT_EQ(200, tr.statusCode); +} + +TEST(WebURLRequestTest, POST) { + class BrowserForTest : public BrowserTestHandler { + public: + explicit BrowserForTest(TestResults &tr) : BrowserTestHandler(tr) { } + + void StartTest() { + CefRefPtr req; + CefRefPtr postdata; + CefRefPtr postitem; + CefRequest::HeaderMap headers; + + headers.insert(std::make_pair("Content-Type", + "application/x-www-form-urlencoded")); + + req = CefRequest::CreateRequest(); + + CefString url("http://pastebin.com/api_public.php"); + CefString method("POST"); + + postdata = CefPostData::CreatePostData(); + postitem = CefPostDataElement::CreatePostDataElement(); + + static char posttext[] = + "paste_name=CEF%20Test%20Post&paste_code=testing a post call." + "&paste_expire_date=10M"; + + postitem->SetToBytes(strlen(posttext), posttext); + postdata->AddElement(postitem); + + req->Set(url, method, postdata, headers); + + CefRefPtr handler = + new TestWebURLRequestClient(test_results_, this); + + req->SetFlags((CefRequest::RequestFlags)( + WUR_FLAG_SKIP_CACHE | + WUR_FLAG_REPORT_LOAD_TIMING | + WUR_FLAG_REPORT_RAW_HEADERS | + WUR_FLAG_REPORT_UPLOAD_PROGRESS)); + + ASSERT_TRUE(handler->Run(req)); + } + }; + + TestResults tr; + CefRefPtr browser = new BrowserForTest(tr); + browser->ExecuteTest(); + + EXPECT_TRUE(tr.got_started); + EXPECT_TRUE(tr.got_headers); + EXPECT_TRUE(tr.got_loading); + EXPECT_TRUE(tr.got_done); + EXPECT_TRUE(tr.got_deleted); + EXPECT_FALSE(tr.got_redirect); + EXPECT_TRUE(tr.got_progress); + EXPECT_FALSE(tr.got_error); + EXPECT_FALSE(tr.got_abort); + EXPECT_GT(tr.contentLength, static_cast(0)); + EXPECT_EQ(200, tr.statusCode); +} + +TEST(WebURLRequestTest, BADHOST) { + class BrowserForTest : public BrowserTestHandler { + public: + explicit BrowserForTest(TestResults &tr) : BrowserTestHandler(tr) { } + + void StartTest() { + CefRefPtr req; + CefRefPtr postdata; + CefRefPtr postitem; + CefRequest::HeaderMap headers; + + req = CefRequest::CreateRequest(); + + CefString url("http://this.host.does.not.exist/not/really/here"); + CefString method("GET"); + + req->Set(url, method, postdata, headers); + + CefRefPtr handler = + new TestWebURLRequestClient(test_results_, this); + + req->SetFlags((CefRequest::RequestFlags)( + WUR_FLAG_SKIP_CACHE | + WUR_FLAG_REPORT_LOAD_TIMING | + WUR_FLAG_REPORT_RAW_HEADERS | + WUR_FLAG_REPORT_UPLOAD_PROGRESS)); + + ASSERT_TRUE(handler->Run(req)); + } + }; + + TestResults tr; + CefRefPtr browser = new BrowserForTest(tr); + browser->ExecuteTest(); + + // NOTE: THIS TEST WILL FAIL IF YOUR ISP REDIRECTS YOU TO + // THEIR SEARCH PAGE ON NXDOMAIN ERRORS. + EXPECT_TRUE(tr.got_started); + EXPECT_FALSE(tr.got_headers); + EXPECT_FALSE(tr.got_loading); + EXPECT_FALSE(tr.got_done); + EXPECT_TRUE(tr.got_deleted); + EXPECT_FALSE(tr.got_redirect); + EXPECT_FALSE(tr.got_progress); + EXPECT_FALSE(tr.got_abort); + EXPECT_TRUE(tr.got_error); + EXPECT_EQ(ERR_NAME_NOT_RESOLVED, tr.errorCode); + EXPECT_EQ(static_cast(0), tr.contentLength); + EXPECT_EQ(0, tr.statusCode); +} + +#define COUNTOF_(ar) (sizeof(ar)/sizeof(ar[0])) + +TEST(WebURLRequestTest, CANCEL) { + class BrowserForTest : public BrowserTestHandler { + public: + BrowserForTest(TestResults &tr, cef_weburlrequest_state_t cancelAtState) + : BrowserTestHandler(tr, cancelAtState) { + } + + void StartTest() { + CefRefPtr req; + CefRefPtr postdata; + CefRefPtr postitem; + CefRequest::HeaderMap headers; + + req = CefRequest::CreateRequest(); + + CefString url( + "http://search.twitter.com/search.json?result_type=popular&q=webkit"); + CefString method("GET"); + + req->Set(url, method, postdata, headers); + + CefRefPtr handler = + new TestWebURLRequestClient(test_results_, this); + + req->SetFlags((CefRequest::RequestFlags)( + WUR_FLAG_SKIP_CACHE | + WUR_FLAG_REPORT_LOAD_TIMING | + WUR_FLAG_REPORT_RAW_HEADERS | + WUR_FLAG_REPORT_UPLOAD_PROGRESS)); + + ASSERT_TRUE(handler->Run(req, cancelAtState_)); + } + }; + + cef_weburlrequest_state_t cancelAt[] = { + WUR_STATE_STARTED, + WUR_STATE_HEADERS_RECEIVED + }; + + for (unsigned int i = 0; i < COUNTOF_(cancelAt); ++i) { + TestResults tr; + CefRefPtr browser = new BrowserForTest(tr, cancelAt[i]); + browser->ExecuteTest(); + EXPECT_TRUE(tr.got_abort) << "i = " << i; + EXPECT_TRUE(tr.got_deleted); + } +} + +// Enable this test if you have installed the php test page. +#if 0 + +TEST(WebURLRequestTest, REDIRECT) { + /* // PHP Script for a local server to test this: + // You can run a zwamp server on windows to run this. + // http://sourceforge.net/projects/zwamp/ + + + */ + + + class BrowserForTest : public BrowserTestHandler { + public: + explicit BrowserForTest(TestResults &tr) : BrowserTestHandler(tr) { } + + void StartTest() { + CefRefPtr req; + CefRefPtr postdata; + CefRefPtr postitem; + CefRequest::HeaderMap headers; + + req = CefRequest::CreateRequest(); + + CefString url("http://localhost/cef/redirect.php?max=4"); + CefString method("GET"); + + req->Set(url, method, postdata, headers); + + CefRefPtr handler = + new TestWebURLRequestClient(test_results_, this); + + req->SetFlags((CefRequest::RequestFlags)( + WUR_FLAG_SKIP_CACHE | + WUR_FLAG_REPORT_LOAD_TIMING | + WUR_FLAG_REPORT_RAW_HEADERS | + WUR_FLAG_REPORT_UPLOAD_PROGRESS)); + + ASSERT_TRUE(handler->Run(req, cancelAtState_)); + } + }; + + TestResults tr; + CefRefPtr browser = new BrowserForTest(tr); + browser->ExecuteTest(); + EXPECT_TRUE(tr.got_started); + EXPECT_TRUE(tr.got_headers); + EXPECT_TRUE(tr.got_loading); + EXPECT_TRUE(tr.got_done); + EXPECT_TRUE(tr.got_deleted); + EXPECT_TRUE(tr.got_redirect); + EXPECT_FALSE(tr.got_progress); + EXPECT_FALSE(tr.got_error); + EXPECT_FALSE(tr.got_abort); + EXPECT_GT(tr.contentLength, static_cast(0)); + EXPECT_EQ(200, tr.statusCode); + EXPECT_EQ(3, tr.redirectCount); +} + +#endif // 0 diff --git a/cef1/tests/unittests/xml_reader_unittest.cc b/cef1/tests/unittests/xml_reader_unittest.cc new file mode 100644 index 000000000..fcc85600e --- /dev/null +++ b/cef1/tests/unittests/xml_reader_unittest.cc @@ -0,0 +1,642 @@ +// 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/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/cef1/tests/unittests/zip_reader_unittest.cc b/cef1/tests/unittests/zip_reader_unittest.cc new file mode 100644 index 000000000..41f83fdde --- /dev/null +++ b/cef1/tests/unittests/zip_reader_unittest.cc @@ -0,0 +1,253 @@ +// 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/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, 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/cef1/tools/automate/automate-git.py b/cef1/tools/automate/automate-git.py new file mode 100644 index 000000000..67dceae12 --- /dev/null +++ b/cef1/tools/automate/automate-git.py @@ -0,0 +1,362 @@ +# 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. + +from optparse import OptionParser +from subprocess import Popen, PIPE, STDOUT +from tempfile import mktemp +import os +import shlex +import shutil +import sys +import urllib + +# default URL values +chromium_url = 'http://git.chromium.org/chromium/src.git' +depot_tools_url = 'http://src.chromium.org/svn/trunk/tools/depot_tools' + +def check_url(url): + """ Check the URL and raise an exception if invalid. """ + if ':' in url[:7]: + parts = url.split(':', 1) + if (parts[0] in ["http", "https", "git"] and \ + parts[1] == urllib.quote(parts[1])): + return url + sys.stderr.write('Invalid URL: '+url+"\n") + raise Exception('Invalid URL: '+url) + +def get_exec_environ(): + env = os.environ + env['PATH'] = depot_tools_dir + os.pathsep + env['PATH'] + return env + +def run(args, **kwargs): + '''Run a command and capture the output iteratively''' + if isinstance(args, str): + args = shlex.split(args.replace('\\', '\\\\')) + cwd = kwargs.get("cwd", os.getcwd()) + quiet = kwargs.get("quiet", False) + print "-> Running '%s' in %s" % (" ".join(args), os.path.relpath(cwd)) + cmd = Popen(args, cwd=cwd, stdout=PIPE, stderr=STDOUT, + env=kwargs.get("env", get_exec_environ()), + shell=(sys.platform == 'win32')) + output = '' + while True: + out = cmd.stdout.read(1) + if out == '' and cmd.poll() != None: + break + output += out + if not quiet: + sys.stdout.write(out) + if cmd.wait() != 0: + raise Exception("Command failed: \"%s\"" % " ".join(args), output) + return output + +def get_current_branch(path): + return run("git rev-parse --abbrev-ref HEAD", cwd=path, quiet=True) + +def get_chromium_compat_rev(cef_url, path, cef_rev): + if not os.path.isdir(path): + path = mktemp() + run("git clone --depth 1 %s %s" % (cef_url, path), quiet = True) + if cef_rev == "None": + cef_rev = get_git_rev(path, get_current_branch(path)) + compat_cmd = "git cat-file -p %s:CHROMIUM_BUILD_COMPATIBILITY.txt" % cef_rev + compat_value = run(compat_cmd, cwd = path, quiet = True) + config = eval(compat_value, {'__builtins__': None}, None) + if not 'chromium_revision' in config: + raise Exception("Missing chromium_revision value") + return str(int(config['chromium_revision'])) + +def get_svn_rev(path, branch): + svn_rev = "None" + cmd = ("git log --grep=^git-svn-id: -n 1 %s" % branch).split() + try: + process = Popen(cmd, cwd=path, stdout = PIPE, stderr = PIPE) + for line in process.stdout: + if line.find("git-svn-id") > 0: + svn_rev = line.split("@")[1].split()[0] + break + except IOError, (errno, strerror): + sys.stderr.write('Failed to read git log: ' + strerror + "\n") + raise + return svn_rev + +def get_git_rev_for_svn_rvn(path, svn_rev): + git_rev = "None" + cmd = ("git log --grep=^git-svn-id:.*@%s --oneline" % svn_rev).split() + try: + process = Popen(cmd, cwd=path, stdout = PIPE, stderr = PIPE) + git_rev = process.communicate()[0].split()[0] + except IOError, (errno, strerror): + sys.stderr.write('Failed to read git log: ' + strerror + "\n") + raise + return git_rev + +def get_git_rev(path, branch): + git_rev = "None" + cmd = ("git describe --always %s" % branch).split() + try: + process = Popen(cmd, cwd=path, stdout = PIPE, stderr = PIPE) + git_rev = process.communicate()[0].strip() + except IOError, (errno, strerror): + sys.stderr.write('Failed to read git log: ' + strerror + "\n") + raise + return git_rev + +def get_git_origin(path): + git_origin = "None" + get_origin_cmd = "git remote show origin -n".split() + try: + process = Popen(get_origin_cmd, cwd=path, stdout = PIPE, stderr = PIPE) + for line in process.stdout: + if line.startswith(" Fetch URL: "): + git_origin = line.replace(" Fetch URL: ", "").strip() + break + except IOError, (errno, strerror): + sys.stderr.write('Failed to read git log: ' + strerror + "\n") + raise + return git_origin + +def get_checkout_info(path, fetch_latest = True): + """ Retrieves the origin URL, git HEAD revision and last SVN revision """ + url = 'None' + origin_svn_rev = 'None' + origin_git_rev = 'None' + local_svn_rev = 'None' + local_git_rev = 'None' + if os.path.isdir(path): + if fetch_latest: + run("git fetch", cwd = path, quiet = True) + url = get_git_origin(path) + branch = get_current_branch(path) + origin_svn_rev = get_svn_rev(path, "origin/%s" % branch) + origin_git_rev = get_git_rev(path, "origin/%s" % branch) + local_svn_rev = get_svn_rev(path, branch) + local_git_rev = get_git_rev(path, branch) + return { + 'url' : url, + 'local' : { + 'svn-revision' : local_svn_rev, + 'git-revision' : local_git_rev + }, + 'origin' : { + 'svn-revision' : origin_svn_rev, + 'git-revision' : origin_git_rev + } + } + +# 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 +desc = """ +This utility implements automation for the download, update, build and +distribution of CEF. +""" + +parser = OptionParser(description=desc) +parser.add_option('--url', dest='url', + help='CEF source URL') +parser.add_option('--download-dir', dest='downloaddir', metavar='DIR', + help='download directory with no spaces [required]') +parser.add_option('--revision', dest='revision', + help='CEF source revision') +parser.add_option('--force-config', + action='store_true', dest='forceconfig', default=False, + help='force Chromium configuration') +parser.add_option('--force-clean', + action='store_true', dest='forceclean', default=False, + help='force revert of all Chromium changes, deletion of '+\ + 'all unversioned files including the CEF folder and '+\ + 'trigger the force-update, force-build and '+\ + 'force-distrib options') +parser.add_option('--force-update', + action='store_true', dest='forceupdate', default=False, + help='force Chromium and CEF update') +parser.add_option('--force-build', + action='store_true', dest='forcebuild', default=False, + help='force CEF debug and release builds') +parser.add_option('--force-distrib', + action='store_true', dest='forcedistrib', default=False, + help='force creation of CEF binary distribution') +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('--no-distrib', + action='store_true', dest='nodistrib', default=False, + help="don't create the CEF binary distribution") +(options, args) = parser.parse_args() + +# the downloaddir and url options are required +if options.downloaddir is None: + print "ERROR: Download directory is required" + parser.print_help(sys.stderr) + sys.exit() +if options.url is None: + print "ERROR: CEF URL is required" + parser.print_help(sys.stderr) + sys.exit() + +cef_url = check_url(options.url) +download_dir = os.path.abspath(options.downloaddir) +if not os.path.exists(download_dir): + # create the download directory + os.makedirs(download_dir) + +# set the expected script extension +if sys.platform == 'win32': + script_ext = '.bat' +else: + script_ext = '.sh' + +# check if the "depot_tools" directory exists +depot_tools_dir = os.path.join(download_dir, 'depot_tools') +if not os.path.exists(depot_tools_dir): + # checkout depot_tools + run('svn checkout %s %s' % (depot_tools_url, depot_tools_dir), + cwd = download_dir, quiet = True) + +chromium_dir = os.path.join(download_dir, 'chromium') +if not os.path.exists(chromium_dir): + # create the "chromium" directory + os.makedirs(chromium_dir) + +chromium_src_dir = os.path.join(chromium_dir, 'src') +cef_src_dir = os.path.join(chromium_src_dir, 'cef') +cef_tools_dir = os.path.join(cef_src_dir, 'tools') + +# retrieve the current CEF URL and revision +info = get_checkout_info(cef_src_dir) +cef_rev = info['origin']['git-revision'] +if not options.revision is None: + cef_rev = str(options.revision) +current_cef_url = info['url'] +current_cef_rev = info['local']['git-revision'] + +# retrieve the compatible Chromium revision +chromium_rev = get_chromium_compat_rev(cef_url, cef_src_dir, cef_rev) + +# retrieve the current Chromium URL and revision +info = get_checkout_info(chromium_src_dir, False) +current_chromium_url = info['url'] +current_chromium_rev = info['local']['svn-revision'] + +# test if the CEF URL changed +cef_url_changed = current_cef_url != cef_url +print "-- CEF URL: %s" % current_cef_url +if cef_url_changed: + print "\t-> CHANGED TO: %s" % cef_url + +# test if the CEF revision changed +cef_rev_changed = current_cef_rev != cef_rev +print "-- CEF Revision: %s" % current_cef_rev +if cef_url_changed: + print "\t-> CHANGED TO: %s" % cef_rev + +# test if the Chromium URL changed +chromium_url_changed = current_chromium_url != chromium_url +print "-- Chromium URL: %s" % current_chromium_url +if cef_url_changed: + print "\t-> CHANGED TO: %s" % chromium_url + +# test if the Chromium revision changed +chromium_rev_changed = current_chromium_rev != chromium_rev +print "-- Chromium Revision: %s" % current_chromium_rev +if cef_url_changed: + print "\t-> CHANGED TO: %s" % chromium_rev + +# true if anything changed +any_changed = chromium_url_changed or chromium_rev_changed or \ + cef_url_changed or cef_rev_changed +if not any_changed: + print "*** NO CHANGE ***" + +if chromium_url_changed or options.forceconfig: + # run gclient config to create the .gclient file + run('gclient config %s --git-deps' % chromium_url, cwd = chromium_dir) + + path = os.path.join(chromium_dir, '.gclient') + if not os.path.exists(path): + raise Exception('.gclient file was not created') + + # read the resulting .gclient file + fp = open(path, 'r') + data = fp.read() + fp.close() + + # populate "custom_deps" section + data = data.replace('"custom_deps" : {', '"custom_deps" : {'+\ + "\n "+'"src/third_party/WebKit/LayoutTests": None,'+\ + "\n "+'"src/chrome_frame/tools/test/reference_build/chrome": None,'+\ + "\n "+'"src/chrome/tools/test/reference_build/chrome_mac": None,'+\ + "\n "+'"src/chrome/tools/test/reference_build/chrome_win": None,'+\ + "\n "+'"src/chrome/tools/test/reference_build/chrome_linux": None,') + + # write the new .gclient file + fp = open(path, 'w') + fp.write(data) + fp.close() + +if options.forceclean: + if os.path.exists(chromium_src_dir): + # revert all Chromium changes and delete all unversioned files + run('gclient revert -n', cwd = chromium_dir) + + # force update, build and distrib steps + options.forceupdate = True + options.forcebuild = True + options.forcedistrib = True + +if chromium_url_changed or chromium_rev_changed or options.forceupdate: + # download/update the Chromium source cod + fetch_rev = "HEAD" + if os.path.isdir(chromium_src_dir): + fetch_rev = get_git_rev_for_svn_rvn( + chromium_src_dir, current_chromium_rev) + run('gclient sync --jobs 8 -n --force --revision=src@%s' % fetch_rev, + cwd = chromium_dir) + checkout_rev = get_git_rev_for_svn_rvn(chromium_src_dir, chromium_rev) + run('gclient sync --jobs 8 --revision=src@%s' % checkout_rev, + cwd = chromium_dir) + +if not os.path.exists(cef_src_dir) or cef_url_changed: + if cef_url_changed and os.path.exists(cef_src_dir): + # delete the cef directory (it will be re-downloaded) + shutil.rmtree(cef_src_dir) + # download the CEF source code + run("git clone %s %s" % (cef_url, cef_src_dir)) +elif cef_rev_changed or options.forceupdate: + # update the CEF source code + stashed = run("git stash", cwd = cef_src_dir).find( + "No local changes to save") < 0 + ref = cef_rev + if ref == "None": + ref = "origin/%s" % get_current_branch(cef_src_dir) + run("git fetch origin", cwd = cef_src_dir) + run("git reset --hard %s" % ref, cwd = cef_src_dir) + if stashed: + run("git stash pop", cwd = cef_src_dir) + +if any_changed or options.forceupdate: + # create CEF projects + path = os.path.join(cef_src_dir, 'cef_create_projects' + script_ext) + run(path, cwd = cef_src_dir, quiet = True) + +if any_changed or options.forcebuild: + path = os.path.join(cef_tools_dir, 'build_projects' + script_ext) + if not options.nodebugbuild: + run(path +' Debug', cwd = cef_tools_dir) + if not options.noreleasebuild: + run(path +' Release', cwd = cef_tools_dir) + +if any_changed or options.forcedistrib: + if not options.nodistrib: + # make CEF binary distribution + path = os.path.join(cef_tools_dir, 'make_distrib' + script_ext) + run(path, cwd = cef_tools_dir) diff --git a/cef1/tools/automate/automate.README.txt b/cef1/tools/automate/automate.README.txt new file mode 100644 index 000000000..b897af4c0 --- /dev/null +++ b/cef1/tools/automate/automate.README.txt @@ -0,0 +1,99 @@ +Chromium Embedded Framework (CEF) Automation Tool +------------------------------------------------------------------------------- + +Document Last Updated: October 10, 2011 + + +OVERVIEW +-------- + +The CEF Automation Tool can perform the following actions in an automated manner: + +1. Download/update the Chromium and CEF source code. +2. Build the CEF Debug and Release targets. +3. Create the CEF binary distribution package. + + +SETUP +----- + +1. Install Subversion [1] and Python [2]. Make sure the bin directories for both + programs are discoverable via your system PATH configuration. On Windows + install CppDoc [3] in the default location (assumes a 64bit version of + Windows 7). + +2. Install build tools. On Windows install Visual Studio 2008 or newer and all + required prerequisite software [4]. On Mac install Xcode 3.2 or newer. + +3. Configure the GYP environment. On Windows set the GYP_MSVS_VERSION + environment variable to "2008" or "2010" depending on which version of Visual + Studio you're building with. On Mac Lion set the GYP_DEFINES environment + variable to 'mac_sdk=10.6'. + +4. Checkout the "automate" folder to a location on your hard drive. For the + trunk version of CEF you can use the following command: + + svn checkout http://chromiumembedded.googlecode.com/svn/trunk/cef1/tools/automate /path/to/automate + +5. Run the automate.py script at whatever interval is appropriate (for each + CEF commit, once per day, once per week, etc): + + python /path/to/automate/automate.py --download-dir=/path/to/download + + +HOW IT WORKS +------------ + +The automate.py script performs the following actions in the download directory +specified by the "--download-dir" flag. This path value must contain no spaces. + +1. Retrieve the Chromium URL and revision associated with a CEF URL and + revision. A specific CEF URL and revision can be specified using the "--url" + and "--revision" flags. Otherwise, the current CEF trunk URL [7] and HEAD + revision will be used. The Chromium URL and revision are retrieved by + querying the SVN repository for a CHROMIUM_BUILD_COMPATIBILITY.txt file. + +2. If a "depot_tools" folder does not already exist download depot_tools [5]. + The depot_tools folder will be added to the beginning of the PATH to support + execution of the below steps. + +3. If a "chromium" folder does not already exist create it and configure + gclient [6] using the Chromium URL retrieved in step 1. To force execution of + this step use the "--force-config" flag. + +4. If the "--force-clean" flag is specified all Chromium changes will be + reverted, all unversioned files including the CEF folder will be deleted and + steps 6-10 will be triggered automatically. + +5. If both Chromium and CEF are already at the correct URL and revision the + script will exit at this point. To force execution of steps 6-8 use the + "--force-update" flag. To force execution of step 9 use the "--force-build" + flag. To force execution of step 10 use the "--force-distrib" flag. + +6. Use gclient [6] to update the Chromium source code to the correct revision. + +7. If a "chromium/src/cef" folder does not already exist download the CEF source + code at the correct revision. Otherwise, update CEF source code to the + correct revision. + +8. Run the "chromium/src/cef/cef_create_projects.[sh|bat]" script to apply CEF + patches and generate CEF project files. + +9. Run the "chromium/src/cef/tools/build_projects.[sh|bat]" script twice; once + to build the Debug target and once to build the Release target. + +10.Run the "chromium/src/cef/tools/make_distrib.[sh|bat]" script to build the + binary distribution package. The resulting package will be output in a + "chromium/src/cef/binary_distrib/cef_binary_rXXX_[windows|macosx]" folder. + + +REFERENCES +---------- + +[1] http://subversion.apache.org/ +[2] http://www.python.org/ +[3] http://www.cppdoc.com/ +[4] http://dev.chromium.org/developers/how-tos/build-instructions-windows +[5] http://dev.chromium.org/developers/how-tos/depottools +[6] http://dev.chromium.org/developers/how-tos/get-the-code +[7] http://chromiumembedded.googlecode.com/svn/trunk/cef1 diff --git a/cef1/tools/automate/automate.py b/cef1/tools/automate/automate.py new file mode 100644 index 000000000..0aa76e7cf --- /dev/null +++ b/cef1/tools/automate/automate.py @@ -0,0 +1,347 @@ +# 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 optparse import OptionParser +import os +import re +import shlex +import shutil +import subprocess +import sys +import urllib + +# default URL values +cef_url = 'http://chromiumembedded.googlecode.com/svn/trunk/cef1' +depot_tools_url = 'http://src.chromium.org/svn/trunk/tools/depot_tools' + +def run(command_line, working_dir, depot_tools_dir=None): + # 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") + args = shlex.split(command_line.replace('\\', '\\\\')) + return subprocess.check_call(args, cwd=working_dir, env=env, + shell=(sys.platform == 'win32')) + +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') and \ + parts[1] == urllib.quote(parts[1]): + return url + sys.stderr.write('Invalid URL: '+url+"\n") + raise Exception('Invalid URL: '+url) + +def get_svn_info(path): + """ Retrieves the URL and revision from svn info. """ + url = 'None' + rev = 'None' + if path[0:4] == 'http' or os.path.exists(path): + try: + stream = os.popen('svn info '+path) + for line in stream: + if line[0:4] == "URL:": + url = check_url(line[5:-1]) + elif line[0:9] == "Revision:": + rev = str(int(line[10:-1])) + except IOError, (errno, strerror): + sys.stderr.write('Failed to read svn info: '+strerror+"\n") + raise + return {'url': url, 'revision': rev} + +# 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) +parser.add_option('--download-dir', dest='downloaddir', metavar='DIR', + help='download directory with no spaces [required]') +parser.add_option('--revision', dest='revision', type="int", + help='CEF source revision') +parser.add_option('--url', dest='url', + help='CEF source URL') +parser.add_option('--force-config', + action='store_true', dest='forceconfig', default=False, + help='force Chromium configuration') +parser.add_option('--force-clean', + action='store_true', dest='forceclean', default=False, + help='force revert of all Chromium changes, deletion of '+\ + 'all unversioned files including the CEF folder and '+\ + 'trigger the force-update, force-build and '+\ + 'force-distrib options') +parser.add_option('--force-update', + action='store_true', dest='forceupdate', default=False, + help='force Chromium and CEF update') +parser.add_option('--force-build', + action='store_true', dest='forcebuild', default=False, + help='force CEF debug and release builds') +parser.add_option('--force-distrib', + action='store_true', dest='forcedistrib', default=False, + help='force creation of CEF binary distribution') +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('--no-distrib', + action='store_true', dest='nodistrib', default=False, + help="don't create the CEF binary distribution") +(options, args) = parser.parse_args() + +# the downloaddir option is required +if options.downloaddir is None: + parser.print_help(sys.stderr) + sys.exit() + +# script directory +script_dir = os.path.dirname(__file__) + +if not options.url is None: + # set the CEF URL + cef_url = check_url(options.url) + +if not options.revision is None: + # set the CEF revision + cef_rev = str(options.revision) +else: + # retrieve the CEF revision from the remote repo + info = get_svn_info(cef_url) + cef_rev = info['revision'] + if cef_rev == 'None': + sys.stderr.write('No SVN info for: '+cef_url+"\n") + raise Exception('No SVN info for: '+cef_url) + +# Retrieve the Chromium URL and revision from the CEF repo +compat_url = cef_url + "/CHROMIUM_BUILD_COMPATIBILITY.txt?r="+cef_rev + +release_url = None +chromium_url = None +chromium_rev = None + +try: + # Read the remote URL contents + handle = urllib.urlopen(compat_url) + compat_value = handle.read().strip() + handle.close() + + # Parse the contents + config = eval(compat_value, {'__builtins__': None}, None) + + if 'release_url' in config: + # building from a release + release_url = check_url(config['release_url']) + else: + # building from chromium src + if not 'chromium_url' in config: + raise Exception("Missing chromium_url value") + if not 'chromium_revision' in config: + raise Exception("Missing chromium_revision value") + + chromium_url = check_url(config['chromium_url']) + chromium_rev = str(int(config['chromium_revision'])) +except Exception, e: + sys.stderr.write('Failed to read URL and revision information from '+ \ + compat_url+"\n") + raise + +download_dir = options.downloaddir +if not os.path.exists(download_dir): + # create the download directory + os.makedirs(download_dir) + +# set the expected script extension +if sys.platform == 'win32': + script_ext = '.bat' +else: + script_ext = '.sh' + +# check if the "depot_tools" directory exists +depot_tools_dir = os.path.join(download_dir, 'depot_tools') +if not os.path.exists(depot_tools_dir): + # checkout depot_tools + run('svn checkout '+depot_tools_url+' '+depot_tools_dir, download_dir) + +# check if the "chromium" directory exists +chromium_dir = os.path.join(download_dir, 'chromium') +if not os.path.exists(chromium_dir): + # create the "chromium" directory + os.makedirs(chromium_dir) + +chromium_src_dir = os.path.join(chromium_dir, 'src') +cef_src_dir = os.path.join(chromium_src_dir, 'cef') +cef_tools_dir = os.path.join(cef_src_dir, 'tools') + +# retrieve the current CEF URL and revision +info = get_svn_info(cef_src_dir) +current_cef_url = info['url'] +current_cef_rev = info['revision'] + +if release_url is None: + # retrieve the current Chromium URL and revision + info = get_svn_info(chromium_src_dir) + current_chromium_url = info['url'] + current_chromium_rev = info['revision'] + +# test if the CEF URL changed +cef_url_changed = current_cef_url != cef_url +sys.stdout.write('CEF URL: '+current_cef_url+"\n") +if cef_url_changed: + sys.stdout.write(' -> CHANGED TO: '+cef_url+"\n") + +# test if the CEF revision changed +cef_rev_changed = current_cef_rev != cef_rev +sys.stdout.write('CEF Revision: '+current_cef_rev+"\n") +if cef_rev_changed: + sys.stdout.write(' -> CHANGED TO: '+cef_rev+"\n") + +release_url_changed = False +chromium_url_changed = False +chromium_rev_changed = False + +if release_url is None: + # test if the Chromium URL changed + chromium_url_changed = current_chromium_url != chromium_url + sys.stdout.write('Chromium URL: '+current_chromium_url+"\n") + if chromium_url_changed: + sys.stdout.write(' -> CHANGED TO: '+chromium_url+"\n") + + # test if the Chromium revision changed + chromium_rev_changed = current_chromium_rev != chromium_rev + sys.stdout.write('Chromium Revision: '+current_chromium_rev+"\n") + if chromium_rev_changed: + sys.stdout.write(' -> CHANGED TO: '+chromium_rev+"\n") +else: + # test if the release URL changed + current_release_url = 'None' + + path = os.path.join(chromium_dir, '.gclient') + if os.path.exists(path): + # read the .gclient file + fp = open(path, 'r') + data = fp.read() + fp.close() + + # Parse the contents + config_dict = {} + try: + exec(data, config_dict) + current_release_url = config_dict['solutions'][0]['url'] + except Exception, e: + sys.stderr.write('Failed to parse existing .glient file.\n') + raise + + release_url_changed = current_release_url != release_url + sys.stdout.write('Release URL: '+current_release_url+"\n") + if release_url_changed: + sys.stdout.write(' -> CHANGED TO: '+release_url+"\n") + +# true if anything changed +any_changed = release_url_changed or chromium_url_changed or \ + chromium_rev_changed or cef_url_changed or cef_rev_changed +if not any_changed: + sys.stdout.write("No changes.\n") + +if release_url_changed or chromium_url_changed or options.forceconfig: + if release_url is None: + url = chromium_url + else: + url = release_url + + # run gclient config to create the .gclient file + run('gclient config '+url, chromium_dir, depot_tools_dir) + + path = os.path.join(chromium_dir, '.gclient') + if not os.path.exists(path): + sys.stderr.write(".gclient file was not created\n") + raise Exception('.gclient file was not created') + + # read the resulting .gclient file + fp = open(path, 'r') + data = fp.read() + fp.close() + + custom_deps = \ + "\n "+'"src/third_party/WebKit/LayoutTests": None,'+\ + "\n "+'"src/chrome_frame/tools/test/reference_build/chrome": None,'+\ + "\n "+'"src/chrome/tools/test/reference_build/chrome_mac": None,'+\ + "\n "+'"src/chrome/tools/test/reference_build/chrome_win": None,'+\ + "\n "+'"src/chrome/tools/test/reference_build/chrome_linux": None,' + + if not release_url is None: + # TODO: Read the DEPS file and exclude all non-src directories. + custom_deps += \ + "\n "+'"chromeos": None,'+\ + "\n "+'"depot_tools": None,' + + # populate "custom_deps" section + data = data.replace('"custom_deps" : {', '"custom_deps" : {'+custom_deps) + + # write the new .gclient file + fp = open(path, 'w') + fp.write(data) + fp.close() + +if options.forceclean: + if os.path.exists(chromium_src_dir): + # revert all Chromium changes and delete all unversioned files + run('gclient revert -n', chromium_dir, depot_tools_dir) + + # force update, build and distrib steps + options.forceupdate = True + options.forcebuild = True + options.forcedistrib = True + +if release_url is None: + if chromium_url_changed or chromium_rev_changed or options.forceupdate: + # download/update the Chromium source code + run('gclient sync --revision src@'+chromium_rev+' --jobs 8 --force', \ + chromium_dir, depot_tools_dir) +elif release_url_changed or options.forceupdate: + # download/update the release source code + run('gclient sync --jobs 8 --force', chromium_dir, depot_tools_dir) + +if not os.path.exists(cef_src_dir) or cef_url_changed: + if cef_url_changed and os.path.exists(cef_src_dir): + # delete the cef directory (it will be re-downloaded) + shutil.rmtree(cef_src_dir) + + # download the CEF source code + run('svn checkout '+cef_url+' -r '+cef_rev+' '+cef_src_dir, download_dir) +elif cef_rev_changed or options.forceupdate: + # update the CEF source code + run('svn update -r '+cef_rev+' '+cef_src_dir, download_dir) + +if any_changed or options.forceupdate: + # create CEF projects + path = os.path.join(cef_src_dir, 'cef_create_projects'+script_ext) + run(path, cef_src_dir, depot_tools_dir) + +if any_changed or options.forcebuild: + path = os.path.join(cef_tools_dir, 'build_projects'+script_ext) + + if not options.nodebugbuild: + # make CEF Debug build + run(path+' Debug', cef_tools_dir, depot_tools_dir) + + if not options.noreleasebuild: + # make CEF Release build + run(path+' Release', cef_tools_dir, depot_tools_dir) + +if any_changed or options.forcedistrib: + if not options.nodistrib: + # make CEF binary distribution + path = os.path.join(cef_tools_dir, 'make_distrib'+script_ext) + run(path, cef_tools_dir, depot_tools_dir) diff --git a/cef1/tools/build_projects.bat b/cef1/tools/build_projects.bat new file mode 100644 index 000000000..6c0739eca --- /dev/null +++ b/cef1/tools/build_projects.bat @@ -0,0 +1,45 @@ +@echo off +set RC= +setlocal + +if "%1" == "" ( +echo ERROR: Please specify a build target: Debug or Release +set ERRORLEVEL=1 +goto end +) + +if "%2" == "" ( +set PROJECT_NAME=cefclient +) else ( +set PROJECT_NAME=%2 +) + +echo Configuring Visual Studio environment... +if "%GYP_MSVS_VERSION%" == "2008" ( +call "%VS90COMNTOOLS%vsvars32.bat" +set PROJECT_EXT=.vcproj +) else ( +call "%VS100COMNTOOLS%vsvars32.bat" +set PROJECT_EXT=.vcxproj +) + +if exist "%DevEnvDir%\devenv.com" ( +echo Building %1 target for %PROJECT_NAME% project... +"%DevEnvDir%\devenv.com" /build %1 ..\cef.sln /project %PROJECT_NAME%%PROJECT_EXT% +) else if exist "%VCINSTALLDIR%\vcpackages\vcbuild.exe" ( +echo Building %1 target for all projects... +"%VCINSTALLDIR%\vcpackages\vcbuild.exe" ..\cef.sln "%1|Win32" +) else ( +echo ERROR: Cannot find Visual Studio builder +set ERRORLEVEL=1 +) + +:end +endlocal & set RC=%ERRORLEVEL% +goto omega + +:returncode +exit /B %RC% + +:omega +call :returncode %RC% diff --git a/cef1/tools/build_projects.sh b/cef1/tools/build_projects.sh new file mode 100755 index 000000000..73dbad4fb --- /dev/null +++ b/cef1/tools/build_projects.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +if [ -z "$1" ]; then + echo "ERROR: Please specify a build target: Debug or Release" +else + if [ -z "$2" ]; then + PROJECT_NAME='cefclient' + else + PROJECT_NAME=$2 + fi + if [ `uname` = "Linux" ]; then + pushd ../../ + make BUILDTYPE=$1 -j 16 + popd + else + xcodebuild -project ../cef.xcodeproj -configuration $1 -target "$PROJECT_NAME" + fi +fi diff --git a/cef1/tools/cef_parser.py b/cef1/tools/cef_parser.py new file mode 100644 index 000000000..722ac4b19 --- /dev/null +++ b/cef1/tools/cef_parser.py @@ -0,0 +1,1849 @@ +# 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 = '' + + if body.find('cef_build_revision()') > 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'], + '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* const': ['char* const', 'NULL'], + 'CefCursorHandle' : ['cef_cursor_handle_t', 'NULL'], + 'CefWindowHandle' : ['cef_window_handle_t', 'NULL'], + 'CefRect' : ['cef_rect_t', 'CefRect()'], + '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): + """ Add all header files from the specified directory. """ + files = get_files(os.path.join(directory, '*.h')) + for file in 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 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, + 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, + 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.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_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 _' + else: + result += 'enum ' + 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/cef1/tools/check_revision.py b/cef1/tools/check_revision.py new file mode 100644 index 000000000..e9334dca2 --- /dev/null +++ b/cef1/tools/check_revision.py @@ -0,0 +1,87 @@ +# 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 file_util import * +from optparse import OptionParser +from svn_util import * +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 checks that the correct Chromium revision is being used. +""" + +parser = OptionParser(description=disc) +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 CEF root directory is the parent directory of _this_ script. +cef_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + +# Retrieve the CEF SVN info. +cef_info = get_svn_info(cef_dir) +if not options.quiet: + sys.stdout.write('Using CEF revision '+cef_info['revision']+' @ '+\ + cef_info['url']+"\n") + +# Retrieve the Chromium SVN info. +src_dir = os.path.join(cef_dir, os.pardir) +chromium_info = get_svn_info(src_dir) +if not options.quiet: + sys.stdout.write('Using Chromium revision '+chromium_info['revision']+' @ '+\ + chromium_info['url']+"\n") + +# Parse the compatibility file contents. +compat_file = os.path.join(cef_dir, 'CHROMIUM_BUILD_COMPATIBILITY.txt') +config = eval(read_file(compat_file), {'__builtins__': None}, None) + +error = False + +if 'release_url' in config: + current_release_url = None + path = os.path.join(os.path.join(src_dir, os.pardir), '.gclient') + if os.path.exists(path): + # read the .gclient file + fp = open(path, 'r') + data = fp.read() + fp.close() + + # Parse the contents + config_dict = {} + try: + exec(data, config_dict) + current_release_url = config_dict['solutions'][0]['url'] + except Exception, e: + sys.stderr.write('Failed to parse existing .glient file.\n') + raise + + if not options.quiet: + sys.stdout.write('Using Chromium release '+current_release_url+"\n") + + if current_release_url != config['release_url']: + error = True + sys.stderr.write("\nWARNING: Incorrect Chromium release URL; found "+\ + current_release_url+', expected '+config['release_url']+"\n") +else: + if chromium_info['url'] != config['chromium_url']: + error = True + sys.stderr.write("\nWARNING: Incorrect Chromium URL; found "+\ + chromium_info['url']+', expected '+config['chromium_url']+"\n") + + if chromium_info['revision'] != config['chromium_revision']: + error = True + sys.stderr.write("\nWARNING: Incorrect Chromium revision; found "+\ + chromium_info['revision']+', expected '+config['chromium_revision']+"\n") + +if error: + sys.stderr.write("\nPlease see CHROMIUM_BUILD_COMPATIBILITY.txt for "\ + "instructions.\n") diff --git a/cef1/tools/check_style.bat b/cef1/tools/check_style.bat new file mode 100644 index 000000000..43612cf91 --- /dev/null +++ b/cef1/tools/check_style.bat @@ -0,0 +1,2 @@ +@echo off +..\..\third_party\python_26\python.exe check_style.py %* diff --git a/cef1/tools/check_style.py b/cef1/tools/check_style.py new file mode 100644 index 000000000..d734e76fb --- /dev/null +++ b/cef1/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/cef1/tools/check_style.sh b/cef1/tools/check_style.sh new file mode 100755 index 000000000..3a38a6ab7 --- /dev/null +++ b/cef1/tools/check_style.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python check_style.py $@ diff --git a/cef1/tools/date_util.py b/cef1/tools/date_util.py new file mode 100644 index 000000000..c19af17b4 --- /dev/null +++ b/cef1/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/cef1/tools/distrib/README-TRANSFER.txt b/cef1/tools/distrib/README-TRANSFER.txt new file mode 100644 index 000000000..6843cc201 --- /dev/null +++ b/cef1/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/cef1/tools/distrib/cefclient.gyp b/cef1/tools/distrib/cefclient.gyp new file mode 100644 index 000000000..d948b3e83 --- /dev/null +++ b/cef1/tools/distrib/cefclient.gyp @@ -0,0 +1,146 @@ +# 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, + 'conditions': [ + [ 'OS=="mac"', { + # Don't use clang with CEF binary releases due to Chromium tree structure dependency. + 'clang': 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"', { + 'msvs_settings': { + 'VCLinkerTool': { + # Set /SUBSYSTEM:WINDOWS. + 'SubSystem': '2', + 'EntryPointSymbol' : 'wWinMainCRTStartup', + }, + }, + 'link_settings': { + 'libraries': [ + '-lcomctl32.lib', + '-lshlwapi.lib', + '-lrpcrt4.lib', + '-lopengl32.lib', + '-lglu32.lib', + '-llib/$(ConfigurationName)/libcef.lib' + ], + }, + 'sources': [ + '<@(includes_win)', + '<@(cefclient_sources_win)', + ], + }], + [ 'OS=="mac"', { + 'product_name': 'cefclient', + 'copies': [ + { + # Add library dependencies to the bundle. + 'destination': '<(PRODUCT_DIR)/cefclient.app/Contents/MacOS/', + 'files': [ + '$(CONFIGURATION)/libcef.dylib', + '$(CONFIGURATION)/ffmpegsumo.so', + ], + }, + { + # Add other resources to the bundle. + 'destination': '<(PRODUCT_DIR)/cefclient.app/Contents/', + 'files': [ + 'Resources/', + ], + }, + ], + 'link_settings': { + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + '$(SDKROOT)/System/Library/Frameworks/OpenGL.framework', + '$(CONFIGURATION)/libcef.dylib' + ], + }, + 'sources': [ + '<@(includes_mac)', + '<@(cefclient_sources_mac)', + ], + }], + [ 'OS=="linux" or OS=="freebsd" or OS=="openbsd"', { + 'copies': [ + { + 'destination': '<(PRODUCT_DIR)/files', + 'files': [ + '<@(cefclient_bundle_resources_linux)', + ], + }, + ], + 'sources': [ + '<@(includes_linux)', + '<@(cefclient_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', + }, + }, + ] +} diff --git a/cef1/tools/distrib/linux/README.txt b/cef1/tools/distrib/linux/README.txt new file mode 100644 index 000000000..0bac8a2cc --- /dev/null +++ b/cef1/tools/distrib/linux/README.txt @@ -0,0 +1,84 @@ +Chromium Embedded Framework (CEF) Binary Distribution +------------------------------------------------------------------------------- + +Date: $DATE$ + +CEF Version: $CEF_VER$ +CEF URL: $CEF_URL$@$CEF_REV$ + +Chromium Verison: $CHROMIUM_VER$ +Chromium URL: $CHROMIUM_URL$@$CHROMIUM_REV$ + + +This distribution contains all components necessary to build and distribute an +application using CEF. Please see the LICENSING section of this document for +licensing terms and conditions. + + +CONTENTS +-------- + +cefclient Contains the cefclient sample application configured to build + using the files in this distribution. + +Debug Contains libcef.so and other components required to run the debug + version of CEF-based applications. + +docs Contains C++ API documentation generated from the CEF header files. + +include Contains all required CEF and NPAPI-related header files. Read + the include/internal/npapi/README-TRANSFER.txt file for more + information about the NPAPI-related 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. + + +USAGE +----- + +Run 'make -j4 cefclient BUILDTYPE=Debug' to build the cefclient target in +Debug mode. + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded + + +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 + +* Localized resources + locales/ + Note: A .pak file is loaded from this folder based on the value of + CefSettings.locale. Only configured locales need to be distributed. If no + locale is configured the default locale of "en-US" will be used. The + locales folder must exist in the same directory as the executable. + +* Other resources + chrome.pak + Note: The chrome.pak file must exist in the same directory as the executable. + + +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 the +below link for complete Chromium and third-party licensing information. + +http://code.google.com/chromium/terms.html diff --git a/cef1/tools/distrib/mac/README.txt b/cef1/tools/distrib/mac/README.txt new file mode 100644 index 000000000..f225b6035 --- /dev/null +++ b/cef1/tools/distrib/mac/README.txt @@ -0,0 +1,95 @@ +Chromium Embedded Framework (CEF) Binary Distribution +------------------------------------------------------------------------------- + +Date: $DATE$ + +CEF Version: $CEF_VER$ +CEF URL: $CEF_URL$@$CEF_REV$ + +Chromium Verison: $CHROMIUM_VER$ +Chromium URL: $CHROMIUM_URL$@$CHROMIUM_REV$ + + +This distribution contains all components necessary to build and distribute an +application using CEF. Please see the LICENSING section of this document for +licensing terms and conditions. + + +CONTENTS +-------- + +cefclient Contains the cefclient sample application configured to build + using the files in this distribution. + +Debug Contains libcef.dylib and other components required to run the debug + version of CEF-based applications. + +docs Contains C++ API documentation generated from the CEF header files. + +include Contains all required CEF and NPAPI-related header files. Read + the include/internal/npapi/README-TRANSFER.txt file for more + information about the NPAPI-related 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.dylib and other components required to run the + release version of CEF-based applications. + +Resources Contains images and resources required by applications using CEF. + The contents of this folder should be transferred to the + Contents/Resources folder in the app bundle. + +tools Scripts that perform post-processing on Mac release targets. + + +USAGE +----- + +Xcode 3 and 4: Open the cefclient.xcodeproj project and build. + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded + + +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.dylib + +* Localized resources + Resources/*.lproj/ + Note: A .pak file is loaded from this folder based on the value of + CefSettings.locale. Only configured locales need to be distributed. If no + locale is configured the default locale of "en" will be used. + +* Other resources + Resources/chrome.pak + Resources/*.png + Resources/*.tiff + +Optional components: + +* FFmpeg audio and video support + ffmpegsumo.so + Note: Without this component HTML5 audio and video will not function. + + +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 the +below link for complete Chromium and third-party licensing information. + +http://code.google.com/chromium/terms.html diff --git a/cef1/tools/distrib/mac/transfer.cfg b/cef1/tools/distrib/mac/transfer.cfg new file mode 100644 index 000000000..a4b9f2900 --- /dev/null +++ b/cef1/tools/distrib/mac/transfer.cfg @@ -0,0 +1,29 @@ +# 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', + }, +] diff --git a/cef1/tools/distrib/transfer.cfg b/cef1/tools/distrib/transfer.cfg new file mode 100644 index 000000000..a4dcd42eb --- /dev/null +++ b/cef1/tools/distrib/transfer.cfg @@ -0,0 +1,64 @@ +# 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' : '../base/basictypes.h', + 'target' : 'include/internal/npapi/basictypes.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../build/build_config.h', + 'target' : 'include/internal/npapi/build_config.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../third_party/npapi/bindings/npapi.h', + 'target' : 'include/internal/npapi/npapi.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../third_party/npapi/bindings/npapi_extensions.h', + 'target' : 'include/internal/npapi/npapi_extensions.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../third_party/npapi/bindings/npfunctions.h', + 'target' : 'include/internal/npapi/npfunctions.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../third_party/npapi/bindings/nphostapi.h', + 'target' : 'include/internal/npapi/nphostapi.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../third_party/npapi/bindings/npruntime.h', + 'target' : 'include/internal/npapi/npruntime.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../third_party/npapi/bindings/nptypes.h', + 'target' : 'include/internal/npapi/nptypes.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : '../base/port.h', + 'target' : 'include/internal/npapi/port.h', + 'post-process' : 'normalize_headers', + }, + { + 'source' : None, + 'target' : 'include/internal/cef_nplugin_types.h', + 'post-process' : 'normalize_headers', + 'new_header_path' : 'include/internal/npapi/', + }, +] \ No newline at end of file diff --git a/cef1/tools/distrib/win/README.txt b/cef1/tools/distrib/win/README.txt new file mode 100644 index 000000000..c51bf9f3b --- /dev/null +++ b/cef1/tools/distrib/win/README.txt @@ -0,0 +1,114 @@ +Chromium Embedded Framework (CEF) Binary Distribution +------------------------------------------------------------------------------- + +Date: $DATE$ + +CEF Version: $CEF_VER$ +CEF URL: $CEF_URL$@$CEF_REV$ + +Chromium Verison: $CHROMIUM_VER$ +Chromium URL: $CHROMIUM_URL$@$CHROMIUM_REV$ + + +This distribution contains all components necessary to build and distribute an +application using CEF. Please see the LICENSING section of this document for +licensing terms and conditions. + + +CONTENTS +-------- + +cefclient Contains the cefclient sample application configured to build + using the files in this distribution. + +Debug Contains libcef.dll and other components required to run the debug + version of CEF-based applications. Also acts as the build target for + the Debug build of cefclient. + +docs Contains C++ API documentation generated from the CEF header files. + +include Contains all required CEF and NPAPI-related header files. Read + the include/internal/npapi/README-TRANSFER.txt file for more + information about the NPAPI-related header files. + +lib Contains Debug and Release versions of the libcef.lib library file + that all CEF-based applications must link against. + +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 and other components required to run the release + version of CEF-based applications. Also acts as the build target for + the Release build of cefclient. + + +USAGE +----- + +Visual Studio 2010: Open the cefclient2010.sln solution and build. +Visual Studio 2008: Open the cefclient2008.sln solution and build. + * If using VS2008 Express Edition add atlthunk.lib to the cefclient + Configuration Properties > Linker > Input > Additional Dependencies +Visual Studio 2005: Open the cefclient2005.sln solution and build. + +Please visit the CEF Website for additional usage information. + +http://code.google.com/p/chromiumembedded + + +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 + icudt.dll + +* Localized resources + locales/ + Note: A .pak file is loaded from this folder based on the value of + CefSettings.locale. Only configured locales need to be distributed. If no + locale is configured the default locale of "en-US" will be used. The + locales folder must exist in the same directory as libcef.dll. + +* Other resources + chrome.pak + Note: The chrome.pak file must exist in the same directory as libcef.dll. + +Optional components: + +* FFmpeg audio and video support + avcodec-54.dll + avformat-54.dll + avutil-51.dll + Note: Without these components HTML5 audio and video will not function. + +* Angle and Direct3D support + d3dcompiler_43.dll + d3dx9_43.dll + libEGL.dll + libGLESv2.dll + Note: Without these components the default ANGLE_IN_PROCESS graphics + implementation for HTML5 accelerated content like 2D canvas, 3D CSS and + WebGL will not function. To use the desktop GL graphics implementation which + does not require these components (and does not work on all systems) set + CefSettings.graphics_implementation to DESKTOP_IN_PROCESS. + + +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 the +below link for complete Chromium and third-party licensing information. + +http://code.google.com/chromium/terms.html diff --git a/cef1/tools/distrib/win/d3dcompiler_43.dll b/cef1/tools/distrib/win/d3dcompiler_43.dll new file mode 100644 index 000000000..ab9616191 Binary files /dev/null and b/cef1/tools/distrib/win/d3dcompiler_43.dll differ diff --git a/cef1/tools/distrib/win/d3dx9_43.dll b/cef1/tools/distrib/win/d3dx9_43.dll new file mode 100644 index 000000000..96cfbe227 Binary files /dev/null and b/cef1/tools/distrib/win/d3dx9_43.dll differ diff --git a/cef1/tools/file_util.py b/cef1/tools/file_util.py new file mode 100644 index 000000000..f6f99cf6b --- /dev/null +++ b/cef1/tools/file_util.py @@ -0,0 +1,111 @@ +# 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 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. """ + return iglob(search_glob) diff --git a/cef1/tools/gclient_hook.py b/cef1/tools/gclient_hook.py new file mode 100644 index 000000000..f79c67645 --- /dev/null +++ b/cef1/tools/gclient_hook.py @@ -0,0 +1,30 @@ +# 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 root directory is the parent directory of _this_ script. +cef_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) + +print "\nChecking CEF and Chromium revisions..." +gyper = [ 'python', 'tools/check_revision.py' ] +RunAction(cef_dir, gyper) + +print "\nGenerating CEF version header file..." +gyper = [ 'python', 'tools/make_version_header.py', + '--header', 'include/cef_version.h', + '--version', '../chrome/VERSION' ] +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..." +os.environ['CEF_DIRECTORY'] = os.path.basename(cef_dir); +gyper = [ 'python', 'tools/gyp_cef', 'cef.gyp', '-I', 'cef.gypi' ] +RunAction(cef_dir, gyper) diff --git a/cef1/tools/gclient_util.py b/cef1/tools/gclient_util.py new file mode 100644 index 000000000..300841456 --- /dev/null +++ b/cef1/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/cef1/tools/git_util.py b/cef1/tools/git_util.py new file mode 100644 index 000000000..a641c83fa --- /dev/null +++ b/cef1/tools/git_util.py @@ -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 + +from subprocess import Popen, PIPE + +def get_svn_revision(path=".", branch="master"): + svn_rev = "None" + cmd = ("git log --grep=^git-svn-id: -n 1 %s" % branch).split() + try: + process = Popen(cmd, cwd=path, stdout = PIPE, stderr = PIPE) + for line in process.stdout: + if line.find("git-svn-id") > 0: + svn_rev = line.split("@")[1].split()[0] + break + except IOError, (errno, strerror): + sys.stderr.write('Failed to read git log: ' + strerror + "\n") + raise + return svn_rev + +def get_changed_files(path="."): + """ Retrieves the list of changed files. """ + # not implemented + return [] diff --git a/cef1/tools/gyp_cef b/cef1/tools/gyp_cef new file mode 100644 index 000000000..f24dc89e0 --- /dev/null +++ b/cef1/tools/gyp_cef @@ -0,0 +1,155 @@ +#!/usr/bin/env python + +# 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. + +# This script is wrapper for CEF/Chromium that adds some support for how GYP +# is invoked by Chromium beyond what can be done in the gclient hooks. + +import glob +import os +import shlex +import subprocess +import sys + +# 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)) + +# The Chromium source directory is the parent directory of CEF. +chrome_src = os.path.abspath(os.path.join(cef_dir, os.pardir)) + +sys.path.insert(0, os.path.join(chrome_src, 'tools', 'gyp', 'pylib')) +import gyp + +# Add paths so that pymod_do_main(grit_info ...) can import files. +sys.path.insert(1, os.path.join(chrome_src, 'tools', 'grit')) +sys.path.insert(1, os.path.join(chrome_src, 'chrome', 'tools', 'build')) + + +# On Windows, Psyco shortens warm runs of build/gyp_chromium by about +# 20 seconds on a z600 machine with 12 GB of RAM, from 90 down to 70 +# seconds. Conversely, memory usage of build/gyp_chromium with Psyco +# maxes out at about 158 MB vs. 132 MB without it. +# +# Psyco uses native libraries, so we need to load a different +# installation depending on which OS we are running under. It has not +# been tested whether using Psyco on our Mac and Linux builds is worth +# it (the GYP running time is a lot shorter, so the JIT startup cost +# may not be worth it). +if sys.platform == 'win32': + try: + sys.path.insert(0, os.path.join(chrome_src, 'third_party', 'psyco_win32')) + import psyco + except: + psyco = None +else: + psyco = None + +def apply_gyp_environment(file_path=None): + """ + Reads in a *.gyp_env file and applies the valid keys to os.environ. + """ + if not file_path or not os.path.exists(file_path): + return + file_contents = open(file_path).read() + try: + file_data = eval(file_contents, {'__builtins__': None}, None) + except SyntaxError, e: + e.filename = os.path.abspath(file_path) + raise + supported_vars = ( 'CHROMIUM_GYP_SYNTAX_CHECK', + 'GYP_DEFINES', + 'GYP_GENERATOR_FLAGS', + 'GYP_GENERATOR_OUTPUT', ) + for var in supported_vars: + val = file_data.get(var) + if val: + if var in os.environ: + print 'INFO: Environment value for "%s" overrides value in %s.' % ( + var, os.path.abspath(file_path) + ) + else: + os.environ[var] = val + +def additional_include_files(args=[]): + """ + Returns a list of additional (.gypi) files to include, without + duplicating ones that are already specified on the command line. + """ + # Determine the include files specified on the command line. + # This doesn't cover all the different option formats you can use, + # but it's mainly intended to avoid duplicating flags on the automatic + # makefile regeneration which only uses this format. + specified_includes = set() + for arg in args: + if arg.startswith('-I') and len(arg) > 2: + specified_includes.add(os.path.realpath(arg[2:])) + + result = [] + def AddInclude(path): + if os.path.realpath(path) not in specified_includes: + result.append(path) + + # Always include common.gypi. + AddInclude(os.path.join(chrome_src, 'build', 'common.gypi')) + + # Optionally add supplemental .gypi files if present. + supplements = glob.glob(os.path.join(chrome_src, '*', 'supplement.gypi')) + for supplement in supplements: + AddInclude(supplement) + + return result + +if __name__ == '__main__': + args = sys.argv[1:] + + # Use the Psyco JIT if available. + if psyco: + psyco.profile() + print "Enabled Psyco JIT." + + # Fall back on hermetic python if we happen to get run under cygwin. + # TODO(bradnelson): take this out once this issue is fixed: + # http://code.google.com/p/gyp/issues/detail?id=177 + if sys.platform == 'cygwin': + python_dir = os.path.join(chrome_src, 'third_party', 'python_26') + env = os.environ.copy() + env['PATH'] = python_dir + os.pathsep + env.get('PATH', '') + p = subprocess.Popen( + [os.path.join(python_dir, 'python.exe')] + sys.argv, + env=env, shell=False) + p.communicate() + sys.exit(p.returncode) + + if 'SKIP_CHROMIUM_GYP_ENV' not in os.environ: + # Update the environment based on chromium.gyp_env + gyp_env_path = os.path.join(os.path.dirname(chrome_src), 'chromium.gyp_env') + apply_gyp_environment(gyp_env_path) + + args.extend(['-I' + i for i in additional_include_files(args)]) + + # There shouldn't be a circular dependency relationship between .gyp files, + # but in Chromium's .gyp files, on non-Mac platforms, circular relationships + # currently exist. The check for circular dependencies is currently + # bypassed on other platforms, but is left enabled on the Mac, where a + # violation of the rule causes Xcode to misbehave badly. + # TODO(mark): Find and kill remaining circular dependencies, and remove this + # option. http://crbug.com/35878. + # TODO(tc): Fix circular dependencies in ChromiumOS then add linux2 to the + # list. + if sys.platform not in ('darwin',): + args.append('--no-circular-check') + + # If CHROMIUM_GYP_SYNTAX_CHECK is set to 1, it will invoke gyp with --check + # to enfore syntax checking. + syntax_check = os.environ.get('CHROMIUM_GYP_SYNTAX_CHECK') + if syntax_check and int(syntax_check): + args.append('--check') + + print 'Updating projects from gyp files...' + sys.stdout.flush() + + # Off we go... + sys.exit(gyp.main(args)) diff --git a/cef1/tools/make_capi_header.py b/cef1/tools/make_capi_header.py new file mode 100644 index 000000000..b0b667a59 --- /dev/null +++ b/cef1/tools/make_capi_header.py @@ -0,0 +1,174 @@ +# 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 + +#ifdef __cplusplus +extern "C" { +#endif + +#include "include/capi/cef_base_capi.h" + +""" + # output global functions + funcs = header.get_funcs(filename) + if len(funcs) > 0: + result += make_capi_global_funcs(funcs, defined_names, translate_map, '') + + # output classes + classes = header.get_classes(filename) + 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' + + # 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/cef1/tools/make_cppdocs.bat b/cef1/tools/make_cppdocs.bat new file mode 100644 index 000000000..f18e3b090 --- /dev/null +++ b/cef1/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="CEF C++ API Docs - Revision %CPPDOC_REV%" -footer="
Chromium Embedded Framework (CEF) Copyright © 2011 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/cef1/tools/make_cpptoc_header.py b/cef1/tools/make_cpptoc_header.py new file mode 100644 index 000000000..4f930e224 --- /dev/null +++ b/cef1/tools/make_cpptoc_header.py @@ -0,0 +1,106 @@ +# 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'+ \ + ' virtual ~'+clsname+'CppToC() {}\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/cef1/tools/make_cpptoc_impl.py b/cef1/tools/make_cpptoc_impl.py new file mode 100644 index 000000000..0872b362e --- /dev/null +++ b/cef1/tools/make_cpptoc_impl.py @@ -0,0 +1,563 @@ +# 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: + result += '\n // Unverified params: '+string.join(optional,', ') + + 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_EQ('+name+'::DebugObjCt, 0);'; + 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<> long 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/cef1/tools/make_ctocpp_header.py b/cef1/tools/make_ctocpp_header.py new file mode 100644 index 000000000..027ac8a14 --- /dev/null +++ b/cef1/tools/make_ctocpp_header.py @@ -0,0 +1,122 @@ +# 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: + 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'+ \ + ' virtual ~'+clsname+'CToCpp() {}\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/cef1/tools/make_ctocpp_impl.py b/cef1/tools/make_ctocpp_impl.py new file mode 100644 index 000000000..0ef21e4bc --- /dev/null +++ b/cef1/tools/make_ctocpp_impl.py @@ -0,0 +1,576 @@ +# 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 revision check + if func.has_attrib('revision_check'): + result += '\n int build_revision = cef_build_revision();'\ + '\n if (build_revision != CEF_REVISION) {'\ + '\n // The libcef build revision does not match the CEF API revision.'\ + '\n DCHECK(false);'\ + '\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: + result += '\n // Unverified params: '+string.join(optional,', ') + + 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_EQ('+name+'::DebugObjCt, 0);'; + 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<> long 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/cef1/tools/make_distrib.bat b/cef1/tools/make_distrib.bat new file mode 100644 index 000000000..b6663905d --- /dev/null +++ b/cef1/tools/make_distrib.bat @@ -0,0 +1,2 @@ +@echo off +..\..\third_party\python_26\python.exe make_distrib.py --output-dir ..\binary_distrib\ %* diff --git a/cef1/tools/make_distrib.py b/cef1/tools/make_distrib.py new file mode 100644 index 000000000..d7ea8692a --- /dev/null +++ b/cef1/tools/make_distrib.py @@ -0,0 +1,446 @@ +# 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 gclient_util import * +from optparse import OptionParser +import os +import re +import shlex +import subprocess +from svn_util import * +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) + 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_readme(src, output_dir, cef_url, cef_rev, cef_ver, chromium_url, \ + chromium_rev, chromium_ver, date): + """ Creates the README.TXT file. """ + data = read_file(src) + 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) + write_file(os.path.join(output_dir, 'README.txt'), data) + if not options.quiet: + sys.stdout.write('Creating README.TXT file.\n') + +def eval_file(src): + """ Loads and evaluates the contents of the specified file. """ + return eval(read_file(src), {'__builtins__': None}, None) + +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 generate_msvs_projects(version): + """ Generate MSVS projects for the specified version. """ + sys.stdout.write('Generating '+version+' project files...') + os.environ['GYP_MSVS_VERSION'] = version + gyper = [ 'python', 'tools/gyp_cef', os.path.relpath(os.path.join(output_dir, 'cefclient.gyp'), cef_dir) ] + RunAction(cef_dir, gyper); + move_file(os.path.relpath(os.path.join(output_dir, 'cefclient.sln')), \ + os.path.relpath(os.path.join(output_dir, 'cefclient'+version+'.sln'))) + +def fix_msvs_projects(): + """ Fix the output directory path in all .vcproj and .vcxproj files. """ + files = [] + for file in get_files(os.path.join(output_dir, '*.vcproj')): + files.append(file) + for file in get_files(os.path.join(output_dir, '*.vcxproj')): + files.append(file) + for file in files: + data = read_file(file) + data = data.replace('../../..\\build\\', '') + write_file(file, data) + +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('-q', '--quiet', + action='store_true', dest='quiet', default=False, + help='do not output detailed status information') +(options, args) = parser.parse_args() + +# the outputdir option is required +if options.outputdir is None: + parser.print_help(sys.stdout) + 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)) + +# retrieve url, revision and date information +cef_info = get_svn_info(cef_dir) +cef_url = cef_info['url'] +cef_rev = cef_info['revision'] +chromium_info = get_svn_info(os.path.join(cef_dir, os.pardir)) +chromium_url = chromium_info['url'] +chromium_rev = chromium_info['revision'] +date = get_date() + +# Read and parse the version file (key=value pairs, one per line) +chrome = {} +lines = read_file(os.path.join(cef_dir, '../chrome/VERSION')).split("\n") +for line in lines: + parts = line.split('=', 1) + if len(parts) == 2: + chrome[parts[0]] = parts[1] + +cef_ver = '1.'+chrome['BUILD']+'.'+cef_rev +chromium_ver = chrome['MAJOR']+'.'+chrome['MINOR']+'.'+chrome['BUILD']+'.'+chrome['PATCH'] + +# Test the operating system. +platform = ''; +if sys.platform == 'win32': + platform = 'windows' +elif sys.platform == 'darwin': + platform = 'macosx' +elif sys.platform.startswith('linux'): + platform = 'linux' + +# output directory +output_dir = os.path.abspath(os.path.join(options.outputdir, \ + 'cef_binary_'+cef_ver+'_'+platform)) +remove_dir(output_dir, options.quiet) +make_dir(output_dir, options.quiet) + +# symbol directory +symbol_dir = os.path.abspath(os.path.join(options.outputdir, \ + 'cef_binary_'+cef_ver+'_'+platform+'_symbols')) +remove_dir(symbol_dir, options.quiet) +make_dir(symbol_dir, options.quiet) + +# 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'] + +# 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 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 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/') +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) + +if platform == 'windows': + # create the README.TXT file + create_readme(os.path.join(script_dir, 'distrib/win/README.txt'), output_dir, cef_url, \ + cef_rev, cef_ver, chromium_url, chromium_rev, chromium_ver, date) + + # 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 build/Debug files + if not options.allowpartial or path_exists(os.path.join(cef_dir, 'Debug')): + 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) + copy_files(os.path.join(cef_dir, 'Debug/*.dll'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, 'Debug/cefclient.exe'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, 'Debug/chrome.pak'), dst_dir, options.quiet) + copy_dir(os.path.join(cef_dir, 'Debug/locales'), os.path.join(dst_dir, 'locales'), \ + options.quiet) + + # transfer lib/Debug files + dst_dir = os.path.join(output_dir, 'lib/Debug') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, 'Debug/lib/libcef.lib'), dst_dir, options.quiet) + else: + sys.stderr.write("No Debug build files.\n") + + # transfer build/Release files + if not options.allowpartial or path_exists(os.path.join(cef_dir, 'Release')): + 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) + copy_files(os.path.join(cef_dir, 'Release/*.dll'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, 'Release/cefclient.exe'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, 'Release/chrome.pak'), dst_dir, options.quiet) + copy_dir(os.path.join(cef_dir, 'Release/locales'), os.path.join(dst_dir, 'locales'), \ + options.quiet) + + # transfer lib/Release files + dst_dir = os.path.join(output_dir, 'lib/Release') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, 'Release/lib/libcef.lib'), dst_dir, options.quiet) + + # transfer symbols + copy_file(os.path.join(cef_dir, 'Release/libcef.pdb'), symbol_dir, options.quiet) + else: + sys.stderr.write("No Release build files.\n") + + # generate doc files + os.popen('make_cppdocs.bat '+cef_rev) + + # transfer docs files + dst_dir = os.path.join(output_dir, 'docs') + src_dir = os.path.join(cef_dir, 'docs') + if path_exists(src_dir): + copy_dir(src_dir, dst_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) + + # generate the project files + generate_msvs_projects('2005'); + generate_msvs_projects('2008'); + generate_msvs_projects('2010'); + fix_msvs_projects(); + +elif platform == 'macosx': + # create the README.TXT file + create_readme(os.path.join(script_dir, 'distrib/mac/README.txt'), output_dir, cef_url, \ + cef_rev, cef_ver, chromium_url, chromium_rev, chromium_ver, date) + + # 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 cefclient/mac files + copy_dir(os.path.join(cef_dir, 'tests/cefclient/mac/'), os.path.join(output_dir, 'cefclient/mac/'), \ + options.quiet) + + # transfer xcodebuild/Debug files + if not options.allowpartial or path_exists(os.path.join(cef_dir, '../xcodebuild/Debug')): + dst_dir = os.path.join(output_dir, 'Debug') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, '../xcodebuild/Debug/ffmpegsumo.so'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, '../xcodebuild/Debug/libcef.dylib'), dst_dir, options.quiet) + + # transfer xcodebuild/Release files + if not options.allowpartial or path_exists(os.path.join(cef_dir, '../xcodebuild/Release')): + dst_dir = os.path.join(output_dir, 'Release') + make_dir(dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, '../xcodebuild/Release/ffmpegsumo.so'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, '../xcodebuild/Release/libcef.dylib'), dst_dir, options.quiet) + + # create the real dSYM file from the "fake" dSYM file + sys.stdout.write("Creating the real dSYM file...\n") + src_path = os.path.join(cef_dir, '../xcodebuild/Release/libcef.dylib.dSYM/Contents/Resources/DWARF/libcef.dylib') + dst_path = os.path.join(symbol_dir, 'libcef.dylib.dSYM') + run('dsymutil '+src_path+' -o '+dst_path, cef_dir) + + # transfer resource files + dst_dir = os.path.join(output_dir, 'Resources') + make_dir(dst_dir, options.quiet) + copy_files(os.path.join(cef_dir, '../third_party/WebKit/Source/WebCore/Resources/*.*'), dst_dir, options.quiet) + copy_file(os.path.join(cef_dir, '../xcodebuild/Release/cefclient.app/Contents/Resources/chrome.pak'), dst_dir, options.quiet) + copy_files(os.path.join(cef_dir, '../xcodebuild/Release/cefclient.app/Contents/Resources/*.lproj'), dst_dir, options.quiet) + remove_dir(os.path.join(dst_dir, 'English.lproj')) + + # transfer additional files, if any + transfer_files(cef_dir, script_dir, os.path.join(script_dir, 'distrib/mac/transfer.cfg'), \ + output_dir, options.quiet) + + # Generate Xcode project files + sys.stdout.write('Generating Xcode project files...') + gyper = [ 'python', 'tools/gyp_cef', os.path.relpath(os.path.join(output_dir, 'cefclient.gyp'), cef_dir) ] + RunAction(cef_dir, gyper); + + # Post-process the Xcode project to fix file paths + src_file = os.path.join(output_dir, 'cefclient.xcodeproj/project.pbxproj') + data = read_file(src_file) + data = data.replace('../../../build/mac/', 'tools/') + data = data.replace('../../../', '') + write_file(src_file, data) + +elif platform == 'linux': + linux_build_dir = os.path.join(cef_dir, os.pardir, 'out') + + # create the README.TXT file + create_readme(os.path.join(script_dir, 'distrib/linux/README.txt'), output_dir, cef_url, \ + cef_rev, cef_ver, chromium_url, chromium_rev, chromium_ver, date) + + # transfer build/Debug files + if not options.allowpartial or path_exists(os.path.join(linux_build_dir, 'Debug')): + dst_dir = os.path.join(output_dir, 'Debug') + make_dir(dst_dir, options.quiet) + copy_dir(os.path.join(linux_build_dir, 'Debug/lib.target'), os.path.join(dst_dir, 'lib.target'), options.quiet) + copy_file(os.path.join(linux_build_dir, 'Debug/cefclient'), dst_dir, options.quiet) + copy_file(os.path.join(linux_build_dir, 'Debug/chrome.pak'), dst_dir, options.quiet) + copy_dir(os.path.join(linux_build_dir, 'Debug/locales'), os.path.join(dst_dir, 'locales'), options.quiet) + + else: + sys.stderr.write("No Debug build files.\n") + + # transfer build/Release files + if not options.allowpartial or path_exists(os.path.join(linux_build_dir, 'Release')): + dst_dir = os.path.join(output_dir, 'Release') + make_dir(dst_dir, options.quiet) + copy_dir(os.path.join(linux_build_dir, 'Release/lib.target'), os.path.join(dst_dir, 'lib.target'), options.quiet) + copy_file(os.path.join(linux_build_dir, 'Release/cefclient'), dst_dir, options.quiet) + copy_file(os.path.join(linux_build_dir, 'Release/chrome.pak'), dst_dir, options.quiet) + copy_dir(os.path.join(linux_build_dir, 'Release/locales'), os.path.join(dst_dir, 'locales'), options.quiet) + + else: + sys.stderr.write("No Release build files.\n") + + # 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 additional files, if any + transfer_files(cef_dir, script_dir, os.path.join(script_dir, 'distrib/linux/transfer.cfg'), \ + output_dir, options.quiet) + +# Create an archive of the output directory +zip_file = os.path.split(output_dir)[1] + '.zip' +if not options.quiet: + sys.stdout.write('Creating '+zip_file+"...\n") +create_archive(output_dir, os.path.join(output_dir, os.pardir, zip_file)) + +# Create an archive of the symbol directory +zip_file = os.path.split(symbol_dir)[1] + '.zip' +if not options.quiet: + sys.stdout.write('Creating '+zip_file+"...\n") +create_archive(symbol_dir, os.path.join(symbol_dir, os.pardir, zip_file)) diff --git a/cef1/tools/make_distrib.sh b/cef1/tools/make_distrib.sh new file mode 100755 index 000000000..273a3e16b --- /dev/null +++ b/cef1/tools/make_distrib.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python make_distrib.py --output-dir ../binary_distrib/ $@ diff --git a/cef1/tools/make_gypi_file.py b/cef1/tools/make_gypi_file.py new file mode 100644 index 000000000..e5cefd7a9 --- /dev/null +++ b/cef1/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/cef1/tools/make_version_header.bat b/cef1/tools/make_version_header.bat new file mode 100644 index 000000000..03337156f --- /dev/null +++ b/cef1/tools/make_version_header.bat @@ -0,0 +1,2 @@ +@echo off +..\third_party\python_26\python.exe tools\make_version_header.py --header include\cef_version.h --version ../chrome/VERSION diff --git a/cef1/tools/make_version_header.py b/cef1/tools/make_version_header.py new file mode 100644 index 000000000..0158a8cd6 --- /dev/null +++ b/cef1/tools/make_version_header.py @@ -0,0 +1,133 @@ +# 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 +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('--version', dest='version', metavar='FILE', + help='input Chrome version config file [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.version is None: + parser.print_help(sys.stdout) + sys.exit() + +def write_svn_header(header, version): + """ 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(version): + raise Exception('Version file '+version+' does not exist.') + + # Read and parse the version file (key=value pairs, one per line) + chrome = {} + lines = read_file(version).split("\n") + for line in lines: + parts = line.split('=', 1) + if len(parts) == 2: + chrome[parts[0]] = parts[1] + + if path_exists(header): + oldcontents = read_file(header) + else: + oldcontents = '' + + year = get_year() + + try: + revision = svn.get_revision() + except: + revision = git.get_svn_revision() + + 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_REVISION ' + revision + '\n'+\ + '#define COPYRIGHT_YEAR ' + year + '\n\n'+\ + '#define CHROME_VERSION_MAJOR ' + chrome['MAJOR'] + '\n'+\ + '#define CHROME_VERSION_MINOR ' + chrome['MINOR'] + '\n'+\ + '#define CHROME_VERSION_BUILD ' + chrome['BUILD'] + '\n'+\ + '#define CHROME_VERSION_PATCH ' + chrome['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'\ + '#ifdef __cplusplus\n'+\ + 'extern "C" {\n'+\ + '#endif\n\n'+\ + '#include "internal/cef_export.h"\n\n'+\ + '///\n'+\ + '// Returns the CEF build revision of the libcef library.\n'+\ + '///\n'+\ + 'CEF_EXPORT int cef_build_revision();\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.version) +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/cef1/tools/patch.bat b/cef1/tools/patch.bat new file mode 100644 index 000000000..b21981a0d --- /dev/null +++ b/cef1/tools/patch.bat @@ -0,0 +1,2 @@ +@echo off +..\third_party\python_26\python.exe tools\patcher.py --patch-config patch/patch.cfg \ No newline at end of file diff --git a/cef1/tools/patch.sh b/cef1/tools/patch.sh new file mode 100755 index 000000000..b9dde9bc0 --- /dev/null +++ b/cef1/tools/patch.sh @@ -0,0 +1,2 @@ +#!/bin/sh +python tools/patcher.py --patch-config patch/patch.cfg diff --git a/cef1/tools/patch_util.py b/cef1/tools/patch_util.py new file mode 100644 index 000000000..990b81f32 --- /dev/null +++ b/cef1/tools/patch_util.py @@ -0,0 +1,560 @@ +""" 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 + ----------- + + 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)) + 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): + 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]): + 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 + + 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/cef1/tools/patcher.README.txt b/cef1/tools/patcher.README.txt new file mode 100644 index 000000000..2078770a4 --- /dev/null +++ b/cef1/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/cef1/tools/patcher.py b/cef1/tools/patcher.py new file mode 100644 index 000000000..ed5ff723e --- /dev/null +++ b/cef1/tools/patcher.py @@ -0,0 +1,98 @@ +# 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) + +# 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/cef1/tools/repack_locales.py b/cef1/tools/repack_locales.py new file mode 100644 index 000000000..d70d9a3bd --- /dev/null +++ b/cef1/tools/repack_locales.py @@ -0,0 +1,180 @@ +#!/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): + """Determine the file that will be generated for the given locale.""" + #e.g. '<(INTERMEDIATE_DIR)/repack/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' + return '%s/repack/%s.lproj/locale.pak' % (INT_DIR, locale.replace('-', '_')) + else: + return os.path.join(INT_DIR, 'repack', locale + '.pak') + + +def calc_inputs(locale): + """Determine the files that need processing for the given locale.""" + inputs = [] + + #e.g. '<(grit_out_dir)/generated_resources_da.pak' + #inputs.append(os.path.join(GRIT_DIR, 'generated_resources_%s.pak' % locale)) + + #e.g. '<(grit_out_dir)/locale_settings_da.pak' + #inputs.append(os.path.join(GRIT_DIR, 'locale_settings_%s.pak' % locale)) + + #e.g. '<(grit_out_dir)/platform_locale_settings_da.pak' + #inputs.append(os.path.join(GRIT_DIR, + # 'platform_locale_settings_%s.pak' % locale)) + + #e.g. '<(SHARED_INTERMEDIATE_DIR)/webkit/webkit_strings_da.pak' + inputs.append(os.path.join(SHARE_INT_DIR, 'webkit', + 'webkit_strings_%s.pak' % locale)) + + #e.g. '<(SHARED_INTERMEDIATE_DIR)/ui/ui_strings_da.pak', + inputs.append(os.path.join(SHARE_INT_DIR, 'ui', 'ui_strings', + 'ui_strings_%s.pak' % locale)) + + #e.g. '<(SHARED_INTERMEDIATE_DIR)/ui/app_locale_settings_da.pak', + inputs.append(os.path.join(SHARE_INT_DIR, 'ui', 'app_locale_settings', + 'app_locale_settings_%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)) + # 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) + 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) + + return repack_locales(locales) + +if __name__ == '__main__': + results = DoMain(sys.argv[1:]) + if results: + print results diff --git a/cef1/tools/svn_util.py b/cef1/tools/svn_util.py new file mode 100644 index 000000000..39f2dda82 --- /dev/null +++ b/cef1/tools/svn_util.py @@ -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. + +import os +import sys +import urllib + +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 + sys.stderr.write('Invalid URL: '+url+"\n") + raise Exception('Invalid URL: '+url) + +def get_svn_info(path): + """ Retrieves the URL and revision from svn info. """ + url = 'None' + rev = 'None' + if path[0:4] == 'http' or os.path.exists(path): + try: + stream = os.popen('svn info '+path) + for line in stream: + if line[0:4] == "URL:": + url = check_url(line[5:-1]) + elif line[0:9] == "Revision:": + rev = str(int(line[10:-1])) + except IOError, (errno, strerror): + sys.stderr.write('Failed to read svn info: '+strerror+"\n") + raise + 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 "'+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): + sys.stderr.write('Failed to read svn status: '+strerror+"\n") + raise + return files diff --git a/cef1/tools/translator.README.txt b/cef1/tools/translator.README.txt new file mode 100644 index 000000000..586133b6d --- /dev/null +++ b/cef1/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. + revision_check (Optional) If set a revision 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/cef1/tools/translator.bat b/cef1/tools/translator.bat new file mode 100644 index 000000000..44b80f385 --- /dev/null +++ b/cef1/tools/translator.bat @@ -0,0 +1,3 @@ +@echo off +..\..\third_party\python_26\python.exe 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/cef1/tools/translator.py b/cef1/tools/translator.py new file mode 100644 index 000000000..ab8b584c3 --- /dev/null +++ b/cef1/tools/translator.py @@ -0,0 +1,163 @@ +# 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() +header.add_directory(options.cppheaderdir) + +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/cef1/tools/translator.sh b/cef1/tools/translator.sh new file mode 100755 index 000000000..abd1c6e91 --- /dev/null +++ b/cef1/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